Spring integration Shiro do the rights control module detailed case study

Source: Internet
Author: User

1. Introducing Shiro's Maven dependency
<!-- Spring  integration of Shiro required dependency  --><dependency><groupid>org.apache.shiro</groupid ><artifactId>shiro-core</artifactId><version>1.2.1</version></dependency>< Dependency><groupid>org.apache.shiro</groupid><artifactid>shiro-web</artifactid> <version>1.2.1</version></dependency><dependency><groupid>org.apache.shiro</ groupid><artifactid>shiro-ehcache</artifactid><version>1.2.1</version></ Dependency><dependency><groupid>org.apache.shiro</groupid><artifactid>shiro-spring </artifactId><version>1.2.1</version></dependency><!--  There are some things you can't do less spring,  spring-mvc, ibatis et  spring.3.1.2 spring-mvc.3.1.2 ibatis.2.3.4 cglib.2.2 - -

Configuration in 2.web.xml
<!--  Configuration Shiro's core interceptor  --><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> 

3. Write your own Userrealm class inherited from realm, mainly to achieve authentication and authorization of management operations
package com.jay.demo.shiro;import java.util.hashset;import java.util.iterator;import  java.util.set;import org.apache.shiro.authc.authenticationexception;import  org.apache.shiro.authc.authenticationinfo;import org.apache.shiro.authc.authenticationtoken;import  org.apache.shiro.authc.lockedaccountexception;import org.apache.shiro.authc.simpleauthenticationinfo; import org.apache.shiro.authc.unknownaccountexception;import  Org.apache.shiro.authz.authorizationinfo;import org.apache.shiro.authz.simpleauthorizationinfo;import  org.apache.shiro.realm.authorizingrealm;import org.apache.shiro.subject.principalcollection;import  org.springframework.beans.factory.annotation.autowired;import com.jay.demo.bean.permission;import  com.jay.demo.bean.Role;import com.jay.demo.bean.User;import com.jay.demo.service.UserService; public class userrealm extends authorizingrealm{@Autowiredprivate  userservice userservice;/** *  authorized Operation  */@Overrideprotected  AuthorizationInfo  Dogetauthorizationinfo (principalcollection principals)  {//String username =  (String)  getavailableprincipal (principals); string username =  (String)  principals.getprimaryprincipal (); Set<role> roleset =  userservice.finduserbyusername (username). GetRoleSet ();// A collection of role names set<string> roles = new hashset<string> ();//collection of permission names set<string>  permissions = new HashSet<String> ();iterator<role> it =  Roleset.iterator (), while (It.hasnext ()) {Roles.add (It.next ()), GetName ()); for (Permission per:it.next (). Getpermissionset ()) {Permissions.add (Per.getname ());}} Simpleauthorizationinfo authorizationinfo = new simpleauthorizationinfo (); Authorizationinfo.addroles (roles); authorizationinfo.addstringpermissions (permissions); Return authoriZationinfo;} /** *  authentication Operation  */@Overrideprotected  authenticationinfo dogetauthenticationinfo ( Authenticationtoken token)  throws authenticationexception {string username =   (String)  token.getprincipal (); User user = userservice.finduserbyusername (username); if (user==null) {//Muyou Find User Throw new  unknownaccountexception ("No Account Found");} /* if (Boolean.TRUE.equals (user.getlocked ()))  {               throw new lockedaccountexception ();  //Account lockout            } *//** *  Give Authenticatingrealm to use Credentialsmatcher for password matching, if you feel bad people can judge or custom implementation    */ Simpleauthenticationinfo info = new simpleauthenticationinfo (User.getUsername (),  User.getpassword (), GetName ()); return info;} @Overridepublic  string getname ()  {return getclaSS (). GetName ();}} 

4. Configuration of Shiro in spring Applicationcontext.xml

1. Add Shirofilter definition

XML code

  1. <!--Shiro Filter--

  2. < Bean id = "Shirofilter" class = "Org.apache.shiro.spring.web.ShiroFilterFactoryBean" >

  3. < property name = "SecurityManager" ref = "SecurityManager"/>

  4. < property name = "Loginurl" value = "/login"/>

  5. < property name = "Successurl" value = "/user/list"/>

  6. < property name = "Unauthorizedurl" value = "/login"/>

  7. < property name = "Filterchaindefinitions" >

  8. < value >

  9. /login = Anon

  10. /user/** = authc

  11. /role/edit/* = Perms[role:edit]

  12. /role/save = perms [Role:edit]

  13. /role/list = perms [Role:view]

  14. /** = authc

  15. </value >

  16. </Property >

  17. </Bean >

2. Add SecurityManager definition

XML code

    1. < Bean id = "SecurityManager" class = "Org.apache.shiro.web.mgt.DefaultWebSecurityManager" >

    2. < property name = "Realm" ref = "Myrealm"/>

    3. </Bean >

3. Add Realm Definition

XML code

  1. < Bean id = "Myrealm" class = "Com.jay.demo.shiro".

    userrealm<span class= "Attribute-value"  style= "Font-size: 1em; font-family: monaco,   ' Dejavu sans mono ',  ' Bitstream vera sans mono ', consolas,  ' Courier new ',  monospace; background-color: rgb (250, 250, 250); > "</span><span style=" color: black; font-size: 1em; font-family:  monaco,  ' Dejavu sans mono ',  ' Bitstream vera sans mono ',  Consolas,   ' Courier new ',  monospace; background-color: rgb (250, 250, 250); " > </span><span class= "tag"  style= "font-size: 1em; font-family:  monaco,  ' Dejavu sans mono ',  ' Bitstream vera sans mono ',  Consolas,   ' Courier new ',  monospace; color: rgb (0, 102, 153); font-weight:  Bold; background-color: rgb (250, 250, 250); " >/></span><span style= "color: black; font-size: 1em; font-family:  Monaco,  ' Dejavu sans mono ',  ' Bitstream vera sans mono ',  consolas ,  ' Courier new ',  monospace; background-color: rgb (250, 250, 250); " >  </span>

4, Configuration Ehcache

< Bean id = "CacheManager" class = "Org.apache.shiro.cache.ehcache.EhCacheManager"/>

5, guaranteed to implement the Shiro internal lifecycle function of the bean execution

<bean id= "Lifecyclebeanpostprocessor" class= "Org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

Special attention:

If you use Shiro-related annotations, you need to configure the information in the Springmvc-servlet.xml

<bean class= "Org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"   depends-on= "Lifecyclebeanpostprocessor"/><bean class= " Org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor ">     <property name= "SecurityManager"  ref= "SecurityManager"/></BEAN> 

Note: Shiro rights-managed filters are explained:
Default filter (10)  anon -- org.apache.shiro.web.filter.authc.AnonymousFilterauthc --  org.apache.shiro.web.filter.authc.formauthenticationfilterauthcbasic --  org.apache.shiro.web.filter.authc.basichttpauthenticationfilterperms --  org.apache.shiro.web.filter.authz.permissionsauthorizationfilterport --  org.apache.shiro.web.filter.authz.portfilterrest --  org.apache.shiro.web.filter.authz.httpmethodpermissionfilterroles --  org.apache.shiro.web.filter.authz.rolesauthorizationfilterssl --  org.apache.shiro.web.filter.authz.sslfilteruser --  org.apache.shiro.web.filter.authc.userfilterlogout --  Org.apache.shiro.web.filter.authc.LogoutFilteranon: Example/admins/**=anon  has no parameters, which means it can be used anonymously. &NBSP;AUTHC: For example,/ADMINS/USER/**=AUTHC indicates the need for authentication (login) to use, no parameters  roles: Example/admins/user/**=roles[admin], parameters can be written multiple, Multiple must be quoted, and the parameters are separated by commas, when there are multiple parameters, such as admins/user/**=roles["Admin,guest"], each parameter is passed, equivalent to the Hasallroles () method.  perms: Example/admins/user/**=perms[user:add:*], parameters can be written multiple, multiple must be quoted, and the parameters are separated by commas, such as/admins/user/**=perms["user:add:*,user:modify:*"], When there are multiple arguments, each argument must pass before it is passed, like the Ispermitedall () method.  rest: Example/admins/user/**=rest[user], according to the method requested, equivalent to/admins/user/**=perms[user:method] , where method is Post,get, Delete, and so on.  port: Example/admins/user/**=port[8081], when the port of the requested URL is not 8081 is jump to schemal://servername:8081?querystring, Where Schmal is the protocol http or HTTPS, servername is the host,8081 you access is the port in the URL configuration, querystring is the URL you visit? The following parameters.  authcbasic: For example/admins/user/**=authcbasic no parameter represents Httpbasic authentication  ssl: Example/admins/user/**=ssl no parameters, represents a secure URL request, The protocol is Https user: for example/admins/user/**=user no parameter indicates that a user must exist and does not check when logged in operation

Code Source: Mingli

Interested friends can go to the ball Oh ~ Share Learning technology: 2042849237


Spring integration Shiro do the rights control module detailed case study

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.