基于Spring框架的Shiro配置方法
一、在web.xml中添加shiro过滤器
<!--Shirofilter--> <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定义
<!--ShiroFilter--> <beanid="shiroFilter"class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <propertyname="securityManager"ref="securityManager"/> <propertyname="loginUrl"value="/login"/> <propertyname="successUrl"value="/user/list"/> <propertyname="unauthorizedUrl"value="/login"/> <propertyname="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定义
<beanid="securityManager"class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <propertyname="realm"ref="myRealm"/> </bean>
3、添加realm定义
<beanid="myRealm"class="com...MyRealm"/>
三、实现MyRealm:继承AuthorizingRealm,并重写认证授权方法
publicclassMyRealmextendsAuthorizingRealm{ privateAccountManageraccountManager; publicvoidsetAccountManager(AccountManageraccountManager){ this.accountManager=accountManager; } /** *授权信息 */ protectedAuthorizationInfodoGetAuthorizationInfo( PrincipalCollectionprincipals){ Stringusername=(String)principals.fromRealm(getName()).iterator().next(); if(username!=null){ Useruser=accountManager.get(username); if(user!=null&&user.getRoles()!=null){ SimpleAuthorizationInfoinfo=newSimpleAuthorizationInfo(); for(SecurityRoleeach:user.getRoles()){ info.addRole(each.getName()); info.addStringPermissions(each.getPermissionsAsString()); } returninfo; } } returnnull; } /** *认证信息 */ protectedAuthenticationInfodoGetAuthenticationInfo( AuthenticationTokenauthcToken)throwsAuthenticationException{ UsernamePasswordTokentoken=(UsernamePasswordToken)authcToken; StringuserName=token.getUsername(); if(userName!=null&&!"".equals(userName)){ Useruser=accountManager.login(token.getUsername(), String.valueOf(token.getPassword())); if(user!=null) returnnewSimpleAuthenticationInfo( user.getLoginName(),user.getPassword(),getName()); } returnnull; } }
参考资料:让ApacheShiro保护你的应用