This article is from NetEase Cloud community
Author: Wang Fei
First, a brief introduction to Shiro:
In the development system, it is necessary to have permissions. Currently, the authorization framework in Java has SpringSecurity and Shiro(formerly called JSecurity). For SpringSecurity, the function is too powerful so that the function is scattered and the use is also more complex. For beginners of Spring Security, the curve is still large, need to in-depth study its source code and framework, configuration also requires a lot of effort, scalability is not particularly strong.
For the rookie Shiro, praise is still more, relatively simple to use, the function is strong enough, the expansion is good. I heard that even the official Spring does not use Spring Security, but Shiro, which shows Shiro’s excellence. Find two introduction: www.infoq.com/cn/articles… www.ibm.com/developerwo… , http://itindex.net/detail/50410-apache-shiro-%E4%BD%BF%E7%94%A8%E6%89%8B%E5%86%8C, the website shiro.apache.org/, is relatively simple to use and configure.
The following is a brief overview of how Shiro is configured and used.
Pom.xml introduces related JAR packages
1 <! --> 2 <dependency> 3 <groupId>org.apache.shiro</groupId> 4 <artifactId>shiro-spring</artifactId> 5 <version>1.4.0</version> 6 </dependency> 7 <! Shiro </groupId> 10 <artifactId>shiro-ehcache</artifactId> 11 <version>1.4.0</version> 12 </dependency> 13 <! Shiro </groupId> 16 <artifactId>shiro-core</artifactId> 17 < version > 1.4.0 < / version > 18 < / dependency >Copy the code
Web. XML adds filtering
1 <! -- Shiro permission control filter --> 2 <filter> 3 <filter-name>shiroFilter</filter-name> 4 <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 5 </filter> 6 7 <filter-mapping> 8 <filter-name>shiroFilter</filter-name> 9 <url-pattern>/*</url-pattern> 10 </filter-mapping>Copy the code
Add a configuration file for shiro.xml
1 <? xml version="1.0" encoding="UTF-8"? > 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee" 4 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:util="http://www.springframework.org/schema/util" 6 xsi:schemaLocation="7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 8 9 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 10 http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd11 http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"12 default-lazy-init="false"13 14 > <! The cache manager uses memory implementation --> 15 16 17 <! <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
19 <constructor-arg value="COOKIE_NAME" />
20 <property name="httpOnly" value="true" />
21 <property name="maxAge" value="2592000"/> 22 23 </bean> 24 25 <! -- rememberMe manager --> 26 <bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
27 <property name="cipherKey" value="#{T(org.apache.shiro.codec.Base64).decode('4AvVhmFLUs0KTA3Kprsdag==')}" />
28 <property name="cookie" ref="rememberMeCookie" />
29 </bean>
30
31 <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> 32 <! -- Class inheriting AuthorizingRealm --> 33 <property name="realm" ref="userRealm" />
34 <property name="rememberMeManager" ref="rememberMeManager"/> 35 </bean> 36 37 <! -- Shiro Filter --> 38 <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
39 <property name="securityManager" ref="securityManager" />
40 <property name="loginUrl" value="/openid" />
41 <property name="successUrl" value="/manage" />
42 <property name="unauthorizedUrl" value="/openid" />
43 <property name="filterChainDefinitions">
44 <value>
45 /api/**=anon46 /res/**=anon47 /src/**=anon48 /health/**=anon49 /logout=authc50 /openid=anon51 /callback=anon52 /=authc53 /**=anon54 </value> 55 </property> 56 </bean> 57 58 59 <! -- Shiro lifecycle handler --> 60 <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
61
62 </beans>Copy the code
Scan configuration of beans
1 <! <aop:config proxy-target-class= -- shiro configuration file and path scan configuration must be in the project MVC configuration file (i.e. Xxx-servlet.xml) --> 2 <aop:config proxy-target-class="true" />
3
4 <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
5 <property name="securityManager" ref="securityManager" />
6 </bean>Copy the code
UserRealm
1 @Component
2 public class UserRealm extends AuthorizingRealm {
3
4 private Logger logger = org.slf4j.LoggerFactory.getLogger(UserRealm.class);
5
6 public final static String CREDENTIALS = "openid"; 7 8 @Autowired 9 private SessionService sessionService; 10 @Autowired 11 private PermissionService permissionService; 12 13 // Record whether PemissionResover is configured. 14 Private Boolean hasSetPemissionResover =false;
15
16 @Override
17 public PermissionResolver getPermissionResolver() {18if(! hasSetPemissionResover) { 19setPermissionResolver(new WildcardExtPermissionResolver());
20 hasSetPemissionResover = true; 21} 22returnsuper.getPermissionResolver(); 23} 24 25 /** 26 * Obtaining Authorization information 27 * 28 * @ Param Principals 29 * @return
30 */
31 @Override
32 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
33 try {
34 Iterator<String> iter = principals.fromRealm(getName()).iterator();
35 if(! iter.hasNext()) { 36 logger.info("Shiro authentication has no permission");
37 return null;
38 }
39 String email = iter.next();
40 if(! Strings.isNullOrEmpty(email)) { 41 //set session
42 SessionObject so = sessionService.getSession(email);
43 if (so == null) {
44 logger.info("So cache is empty");
45 returnnull; 46 } 47 SessionUtils.setSo(so); 48 and 49 / /set auth
50 SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
51 info.addStringPermissions(permissionService.getPermsForUser(so.getRoleId()));
52 return info;
53 }
54 logger.info("Mailbox is empty");
55 return null;
56 } catch (Exception e) {
57 logger.error("Shiro permission obtaining exception :", e);
58 returnnull; 64 * 65 * @param authcToken 66 * @return
67 * @throws AuthenticationException
68 */
69 @Override
70 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { 71 try { 72 UsernamePasswordToken token = (UsernamePasswordToken) authcToken; 73 String email = token.getUsername(); 74 String password = new String(token.getPassword()); 75if(! StringUtils.isEmpty(email) && CREDENTIALS.equals(password)) { 76 SessionObject so = SessionUtils.getSo(); 77 sessionService.addOrUpdateSession(so); 78return new SimpleAuthenticationInfo(email, CREDENTIALS, getName());
79 }
80 logger.info("Login authentication failed, Shiro does not add permission information");
81 return null;
82 } catch (Exception e) {
83 logger.error(Shiro authentication exception:, e);
84 returnnull; 85} 86} 87 88 89}Copy the code
Log on to call
UsernamePasswordToken token = new UsernamePasswordToken(
"username"."password".true);
SecurityUtils.getSubject().login(token);Copy the code
Quit the call
1 SecurityUtils.getSubject().logout();Copy the code
Permissions annotations
@RequiresPermissions(value = {"ROLE_KEY"})Copy the code
NetEase Cloud Free experience pavilion, 0 cost experience 20+ cloud products!
For more information about NetEase’s r&d, product and operation experience, please visit NetEase Cloud Community.
Related articles: Memcached Hash algorithm