欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于Spring框架的Shiro配置方法

程序员文章站 2024-02-29 14:51:22
一、在web.xml中添加shiro过滤器

一、在web.xml中添加shiro过滤器

<!-- shiro filter-->
<filter>
<filter-name>shirofilter</filter-name>
<filter-class>
org.springframework.web.filter.delegatingfilterproxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>shirofilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

二、在spring的applicationcontext.xml中添加shiro配置

1、添加shirofilter定义

<!-- shiro filter -->
<bean id="shirofilter" class="org.apache.shiro.spring.web.shirofilterfactorybean">
 <property name="securitymanager" ref="securitymanager" />
 <property name="loginurl" value="/login" />
 <property name="successurl" value="/user/list" />
 <property name="unauthorizedurl" value="/login" />
 <property name="filterchaindefinitions">
 <value>
 /login = anon
 /user/** = authc
 /role/edit/* = perms[role:edit]
 /role/save = perms[role:edit]
 /role/list = perms[role:view]
 /** = authc
 </value>
 </property>
</bean>

2、添加securitymanager定义

复制代码 代码如下:

<bean id="securitymanager" class="org.apache.shiro.web.mgt.defaultwebsecuritymanager">
 <property name="realm" ref="myrealm" />
</bean>

3、添加realm定义

复制代码 代码如下:

<bean id=" myrealm" class="com...myrealm" />

三、实现myrealm:继承authorizingrealm,并重写认证授权方法

public class myrealm extends authorizingrealm{

 private accountmanager accountmanager;
 public void setaccountmanager(accountmanager accountmanager) {
 this.accountmanager = accountmanager;
 }

 /**
 * 授权信息
 */
 protected authorizationinfo dogetauthorizationinfo(
 principalcollection principals) {
 string username=(string)principals.fromrealm(getname()).iterator().next();
 if( username != null ){
 user user = accountmanager.get( username );
 if( user != null && user.getroles() != null ){
 simpleauthorizationinfo info = new simpleauthorizationinfo();
 for( securityrole each: user.getroles() ){
  info.addrole(each.getname());
  info.addstringpermissions(each.getpermissionsasstring());
 }
 return info;
 }
 }
 return null;
 }

 /**
 * 认证信息
 */
 protected authenticationinfo dogetauthenticationinfo(
 authenticationtoken authctoken ) throws authenticationexception {
 usernamepasswordtoken token = (usernamepasswordtoken) authctoken;
 string username = token.getusername();
 if( username != null && !"".equals(username) ){
 user user = accountmanager.login(token.getusername(),
  string.valueof(token.getpassword()));

 if( user != null )
 return new simpleauthenticationinfo(
  user.getloginname(),user.getpassword(), getname());
 }
 return null;
 }
}

参考资料:让apache shiro保护你的应用