一、在web.xml中添加shiro过滤器
<!-- Shiro过滤器--><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 过滤器 --><bean id="shiroFilter"> <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 > </属性></豆>
2、添加securityManager定义
复制代码代码如下:
<bean id="安全管理器">
<属性名称=“领域”参考=“myRealm”/>
</豆>
3、添加领域定义
复制代码代码如下:
<bean id="myRealm"/>
三、实现MyRealm:继承AuthorizingRealm,并重写认证授权方法
公共类 MyRealm 扩展了 AuthorizingRealm{ 私人 AccountManager accountManager;公共无效 setAccountManager(AccountManager accountManager) { this.accountManager = accountManager; } /** * 授权信息 */ protected AuthorizationInfo doGetAuthorizationInfo( PrimaryCollectionprincipals) { String username=(String)principals.fromRealm(getName()).iterator().next(); if( 用户名 != null ){ 用户 user = accountManager.get( 用户名 ); if( user != null && user.getRoles() != null ){ SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); for( SecurityRole every: user.getRoles() ){ info.addRole(each.getName()); info.addStringPermissions(each.getPermissionsAsString());返回信息;返回 null; } /** * 认证信息 */ protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authcToken ) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; String userName = token.getUsername(); if( userName != null && !"".equals(userName) ){ 用户 user = accountManager.login(token.getUsername(), String.valueOf(token.getPassword())); if( user != null ) return new SimpleAuthenticationInfo( user.getLoginName(),user.getPassword(), getName());返回空值; }}
参考资料:让 Apache Shiro 保护你的应用