Shiro Learning (12) integration with spring

Source: Internet
Author: User

Shiro components are Javabean/pojo-type components, so it's easy to use spring for component management, to easily migrate from INI configuration to spring for management, and to support integration of Javase applications and Web applications.

Before the example, you need to import shiro-spring and Spring-context dependencies, refer to Pom.xml for details.

The Spring-beans.xml configuration file provides the configuration of the underlying components such as DataSource, DAO, and service components.

Javase applications

Spring-shiro.xml provides a spring configuration for common javase standalone applications:

Java code
  1. <!--cache Manager is implemented with Ehcache
  2. <bean id= "CacheManager" class= "Org.apache.shiro.cache.ehcache.EhCacheManager" >
  3. <property name= "Cachemanagerconfigfile" value= "Classpath:ehcache.xml"/>
  4. </bean>
  5. <!--voucher Matching--
  6. <bean id= "Credentialsmatcher" class= "
  7. Com.github.zhangkaitao.shiro.chapter12.credentials.RetryLimitHashedCredentialsMatcher ">
  8. <constructor-arg ref= "CacheManager"/>
  9. <property name= "Hashalgorithmname" value= "MD5"/>
  10. <property name= "Hashiterations" value= "2"/>
  11. <property name= "storedcredentialshexencoded" value= "true"/>
  12. </bean>
  13. <!--Realm
  14. <bean id= "Userrealm" class= "Com.github.zhangkaitao.shiro.chapter12.realm.UserRealm" >
  15. <property name= "UserService" ref= "UserService"/>
  16. <property name= "Credentialsmatcher" ref= "Credentialsmatcher"/>
  17. <property name= "cachingenabled" value= "true"/>
  18. <property name= "authenticationcachingenabled" value= "true"/>
  19. <property name= "Authenticationcachename" value= "Authenticationcache"/>
  20. <property name= "authorizationcachingenabled" value= "true"/>
  21. <property name= "Authorizationcachename" value= "Authorizationcache"/>
  22. </bean>
  23. <!--session ID Generator--
  24. <bean id= "Sessionidgenerator"
  25. class= "Org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>
  26. <!--session DAO--
  27. <bean id= "Sessiondao"
  28. class= "Org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO" >
  29. <property name= "Activesessionscachename" value= "Shiro-activesessioncache"/>
  30. <property name= "Sessionidgenerator" ref= "Sessionidgenerator"/>
  31. </bean>
  32. <!--session Validation Scheduler--
  33. <bean id= "Sessionvalidationscheduler"
  34. class= "Org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler" >
  35. <property name= "Sessionvalidationinterval" value= "1800000"/>
  36. <property name= "SessionManager" ref= "SessionManager"/>
  37. </bean>
  38. <!--Session Manager--
  39. <bean id= "SessionManager" class= "Org.apache.shiro.session.mgt.DefaultSessionManager" >
  40. <property name= "Globalsessiontimeout" value= "1800000"/>
  41. <property name= "Deleteinvalidsessions" value= "true"/>
  42. <property name= "sessionvalidationschedulerenabled" value= "true"/>
  43. <property name= "Sessionvalidationscheduler" ref= "Sessionvalidationscheduler"/>
  44. <property name= "Sessiondao" ref= "Sessiondao"/>
  45. </bean>
  46. <!--security Manager--
  47. <bean id= "SecurityManager" class= "Org.apache.shiro.mgt.DefaultSecurityManager" >
  48. <property name= "Realms" >
  49. <list><ref bean= "Userrealm"/></list>
  50. </property>
  51. <property name= "SessionManager" ref= "SessionManager"/>
  52. <property name= "CacheManager" ref= "CacheManager"/>
  53. </bean>
  54. <!--equivalent to calling Securityutils.setsecuritymanager (SecurityManager)--
  55. <bean class= "Org.springframework.beans.factory.config.MethodInvokingFactoryBean" >
  56. <property name= "Staticmethod"
  57. Value= "Org.apache.shiro.SecurityUtils.setSecurityManager"/>
  58. <property name= "Arguments" ref= "SecurityManager"/>
  59. </bean>
  60. <!--Shiro Life cycle Processor--
  61. <bean id= "Lifecyclebeanpostprocessor"
  62. class= "Org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

As you can see, just translate the previous INI configuration into the spring XML configuration here, without much explanation. The lifecyclebeanpostprocessor is used to invoke the Initializable interface callback when the Shiro bean initialization for the Initializable interface is implemented, destroyable the Shiro interface is implemented The Destroyable interface callback is called when the bean is destroyed. such as Userrealm realized the initializable, and Defaultsecuritymanager realized the destroyable. You can see their inheritance relationships in detail.

Please refer to com.github.zhangkaitao.shiro.chapter12.ShiroTest for test cases.

Web Apps

Some configurations for Web applications and general Javase applications are similar, and there are only a few different configurations available here, and detailed configuration can refer to Spring-shiro-web.xml.

Java code
  1. <!--session cookie template--
  2. <bean id= "Sessionidcookie" class= "Org.apache.shiro.web.servlet.SimpleCookie" >
  3. <constructor-arg value= "Sid"/>
  4. <property name= "HttpOnly" value= "true"/>
  5. <property name= "MaxAge" value= "180000"/>
  6. </bean>
  7. <!--Session Manager--
  8. <bean id= "SessionManager"
  9. class= "Org.apache.shiro.web.session.mgt.DefaultWebSessionManager" >
  10. <property name= "Globalsessiontimeout" value= "1800000"/>
  11. <property name= "Deleteinvalidsessions" value= "true"/>
  12. <property name= "sessionvalidationschedulerenabled" value= "true"/>
  13. <property name= "Sessionvalidationscheduler" ref= "Sessionvalidationscheduler"/>
  14. <property name= "Sessiondao" ref= "Sessiondao"/>
  15. <property name= "sessionidcookieenabled" value= "true"/>
  16. <property name= "Sessionidcookie" ref= "Sessionidcookie"/>
  17. </bean>
  18. <!--security Manager--
  19. <bean id= "SecurityManager" class= "Org.apache.shiro.web.mgt.DefaultWebSecurityManager" >
  20. <property name= "Realm" ref= "Userrealm"/>
  21. <property name= "SessionManager" ref= "SessionManager"/>
  22. <property name= "CacheManager" ref= "CacheManager"/>
  23. </bean>

1, Sessionidcookie is used to produce the session ID cookie template;

2, the session Manager uses the Defaultwebsessionmanager for the web environment;

3. The security Manager uses the Defaultwebsecuritymanager for the web environment.

Java code
  1. <!--authentication filters based on form forms--
  2. <bean id= "Formauthenticationfilter"
  3. class= "Org.apache.shiro.web.filter.authc.FormAuthenticationFilter" >
  4. <property name= "Usernameparam" value= "username"/>
  5. <property name= "Passwordparam" value= "password"/>
  6. <property name= "loginurl" value= "/login.jsp"/>
  7. </bean>
  8. <!--Shiro Web filters--
  9. <bean id= "Shirofilter" class= "Org.apache.shiro.spring.web.ShiroFilterFactoryBean" >
  10. <property name= "SecurityManager" ref= "SecurityManager"/>
  11. <property name= "loginurl" value= "/login.jsp"/>
  12. <property name= "Unauthorizedurl" value= "/unauthorized.jsp"/>
  13. <property name= "Filters" >
  14. <util:map>
  15. <entry key= "authc" value-ref= "Formauthenticationfilter"/>
  16. </util:map>
  17. </property>
  18. <property name= "Filterchaindefinitions" >
  19. <value>
  20. /index.jsp = Anon
  21. /unauthorized.jsp = Anon
  22. /login.jsp = authc
  23. /logout = Logout
  24. /** = user
  25. </value>
  26. </property>
  27. </bean>

1. Formauthenticationfilter is an authentication filter based on form forms; Here you can add your own filter bean definition;

2, Shirofilter: Here use Shirofilterfactorybean to create Shirofilter filter, filters attribute is used to define its own filter, that is, the [filters] section in the INI configuration The filterchaindefinitions is used to declare the relationship between the URL and filter, which is the [URLs] section in the INI configuration.

Next, you need to configure the following in Web. xml:

Java code
    1. <context-param>
    2. <param-name>contextConfigLocation</param-name>
    3. <param-value>
    4. Classpath:spring-beans.xml,
    5. Classpath:spring-shiro-web.xml
    6. </param-value>
    7. </context-param>
    8. <listener>
    9. <listener-class>
    10. Org.springframework.web.context.ContextLoaderListener
    11. </listener-class>
    12. </listener>

Loads the contextconfiglocation specified spring configuration file via Contextloaderlistener.

Java code
    1. <filter>  
    2.     <filter-name>shirofilter </filter-name>  
    3.     <filter-class> org.springframework.web.filter.delegatingfilterproxy</filter-class>  
    4.      <init-param>  
    5.         < param-name>targetfilterlifecycle</param-name>  
    6.          <param-value>true</param-value>  
    7.     < /init-param>  
    8. </filter>  
    9. <filter-mapping>  
    10.     <filter-name>shirofilter</filter-name>  
    11.      <url-pattern>/*</url-pattern>  
    12. </filter-mapping>    

Delegatingfilterproxy automatically looks for the bean named Shirofilter in the spring container and gives the filter request to it for processing.

Please refer to the source code for additional configuration.

Shiro permission Annotations

Shiro provides annotations for permission control, and if you use these annotations you need to use the functionality of AOP to make judgments, such as spring Aop;shiro provides the parsing and validation of the spring AOP integration for permission annotations.

To test this, spring MVC is used here to test Shiro annotations, and of course Shiro annotations are not only available in the Web environment, but are also available in standalone Javase, where the web is just an example.

Add support for Shiro Spring AOP permission annotations in the Spring-mvc.xml profile:

Java code
    1. <aop:config proxy-target-class= "true" ></aop:config>
    2. <bean class= "
    3. Org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor ">
    4. <property name= "SecurityManager" ref= "SecurityManager"/>
    5. </bean>

Configure support for opening Shiro Spring AOP permission annotations as above; <aop:config proxy-target-class= "true" > represents the proxy class.

You can then use the following notation in the corresponding controller (Annotationcontroller):

Java code
    1. @RequiresRoles ("admin")
    2. @RequestMapping ("/hello2")
    3. Public String Hello2 () {
    4. Return "Success";
    5. }

The prerequisite for accessing the Hello2 method is that the current user has the admin role.

When validation fails, it throws a Unauthorizedexception exception, which can be intercepted using spring's Exceptionhandler (Defaultexceptionhandler):

Java code
    1. @ExceptionHandler ({unauthorizedexception.class})
    2. @ResponseStatus (httpstatus.unauthorized)
    3. Public Modelandview processunauthenticatedexception (nativewebrequest request, unauthorizedexception e) {
    4. Modelandview mv = new Modelandview ();
    5. Mv.addobject ("Exception", e);
    6. Mv.setviewname ("Unauthorized");
    7. return MV;
    8. }

If you integrate Struts2, you need to pay attention to "Shiro+struts2+spring3 plus @requirespermissions after @autowired failure" issue:

http://jinnianshilongnian.iteye.com/blog/1850425

permission Annotations

Java code
    1. @RequiresAuthentication

Indicates that the current subject has been authenticated via login, that is, subject. IsAuthenticated () returns True.

Java code
    1. @RequiresUser

Indicates that the current subject is authenticated or logged in by remembering me.

Java code
    1. @RequiresGuest

Indicates that the current subject is not authenticated or by remembering that I have logged in, that is, the visitor identity.

Java code
    1. @RequiresRoles (value={"admin", "user"}, logical= Logical.and)

Indicates that the current subject requires role admin and user.

Java code
    1. @RequiresPermissions (value={"user:a", "User:b"}, logical= logical.or)

Indicates that the current subject requires permission user:a or USER:B.

Shiro Learning (12) integration with spring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.