Web Engineering uses spring Mvc+shiro for permission control

Source: Internet
Author: User

1th Step: Introduce Shiro related jar package

Ehcache-core-2.5.0.jar

Shiro-ehcache-1.2.3.jar

Shiro-core-1.2.3.jar

Shiro-web-1.2.3.jar

Shiro-spring-1.2.3.jar

Step two: Web. XML configuration

<!--Shiro's filter--><!--Shiro filter, Delegatingfilterproxy associates beans and filters in the spring container through proxy mode--><filter ><filter-name>shiroFilter</filter-name><filter-class> org.springframework.web.filter.delegatingfilterproxy</filter-class><!--Set True by the servlet container to control the life cycle of the filter- -><init-param><param-name>targetfilterlifecycle</param-name><param-value>true</ param-value></init-param><!--set the bean ID of the spring container filter, and if not set, find the same bean-->< as Filter-name init-param><param-name>targetbeanname</param-name><param-value>shirofilter</ param-value></init-param></filter><filter-mapping><filter-name>shirofilter</ Filter-name><url-pattern>/*</url-pattern></filter-mapping>

Step Three: Applicationcontext-shiro.xml configuration

<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:mvc=" Http://www.springframework.org/schema/mvc "xmlns:context="/HTTP/ Www.springframework.org/schema/context "xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "xmlns:tx="/HTTP/ Www.springframework.org/schema/tx "xsi:schemalocation=" Http://www.springframework.org/schema/beans/http Www.springframework.org/schema/beans/spring-beans-3.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/MVC/HTTP Www.springframework.org/schema/mvc/spring-mvc-3.2.xsd Http://www.springframework.org/schema/context/HTTP Www.springframework.org/schema/context/spring-context-3.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/HTTP Www.springframework.org/schema/aop/spring-aop-3.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/HTTP Www.springframework.org/schema/tx/spring-tx-3.2.xsd "><!--The bean--><!--of the Shiro filter in Web. XML Shiro Web filter--><bean id= "Shirofilter" class= "Org.apacHe.shiro.spring.web.ShiroFilterFactoryBean "><property name=" SecurityManager "ref=" SecurityManager "/> <!--loginurl Certification submit address, if no certification will request this address for authentication, request this address will be formauthenticationfilter form authentication--><property name= "Loginurl" Value= "/login.action"/><!--certification successfully unified jump to First.action, recommended not configured, Shiro authentication successfully automatically to the previous request path--><property name= " Successurl "value="/first.action "/><!--jump page Unauthorizedurl--><property when no permission action is specified by Name=" Unauthorizedurl "value="/refuse.jsp "/><!--custom Filter configuration--><property name=" Filters "><map><! --Inject the custom formauthenticationfilter into the Shirofilter--><entry key= "authc" value-ref= "Formauthenticationfilter"/ ></map></property><!--filter chain definition, executed from the top down order, generally put/** on the bottom--><property name= " Filterchaindefinitions "><value><!--set Anonymous access to static resources-->/images/** = anon/js/** = anon/styles/** = anon<! --authentication code, can be accessed anonymously-->/validatecode.jsp = anon<!--request Logout.action address, Shiro to clear session-->/logout.action = logout< !--Product Inquiry NeedsProduct query permission, cancel URL interception configuration, use annotation authorization method--><!--/items/queryitems.action = perms[item:query]/items/edititems.action = perms[ Item:edit]--><!--configuration Remember me or authentication by accessible address-->/index.jsp = User/first.action = user/welcome.jsp = user<!--/** = au THC all URLs must be authenticated to access-->/** = authc<!--/** = anon All URLs can be accessed anonymously--></value></property></bean ><!--SecurityManager Security Manager--><bean id= "SecurityManager" class= " Org.apache.shiro.web.mgt.DefaultWebSecurityManager "><property name=" Realm "ref=" Customrealm "/><!-- Inject cache manager--><property name= "CacheManager" ref= "CacheManager"/><!--inject Session manager--><property Name= " SessionManager "ref=" SessionManager "/><!--Remember Me--><property name=" Remembermemanager "ref=" Remembermemanager "/></bean><!--realm--><bean id=" Customrealm "class=" custom class Realm Full name "><!-- Set the voucher match to realm, and realm hashes--><property name= "Credentialsmatcher" ref= "Credentialsmatcher" according to the requirements of the credential matching device </bean><! --Voucher match--><bean id= "Credentialsmatcher" class= "Org.apache.shiro.authc.credential.HashedCredentialsMatcher" ><property name= "Hashalgorithmname" value= "MD5"/><property name= "Hashiterations" value= "1"/></    bean><!--Cache manager--><bean id= "CacheManager" class= "Org.apache.shiro.cache.ehcache.EhCacheManager" > <property name= "Cachemanagerconfigfile" value= "Classpath:shiro-ehcache.xml"/> </bean><!--Session Manager-- > <bean id= "SessionManager" class= "Org.apache.shiro.web.session.mgt.DefaultWebSessionManager" > <!-- Session expiration time, in milliseconds-to <property name= "Globalsessiontimeout" value= "600000"/> <!--Delete invalid session- -<property name= "Deleteinvalidsessions" value= "true"/> </bean><!--Custom form authentication Filter--><!- -Based on Form form Authentication filter, do not configure will also register this filter, the user account, password and loginurl in the form will take the default value, it is recommended to configure--><bean id= "Formauthenticationfilter" class = "Custom class full Name" ><!--the input name of the account in the form--><property namE= "Usernameparam" value= "username"/><!--the input name of the password in the form--><property name= "Passwordparam" value= " Password "/><!--remember the name of my input--><property name=" Remembermeparam "value=" RememberMe "/> </bean> <!--Remembermemanager Manager, write cookies, take out cookies to generate user information--><bean id= "Remembermemanager" class= " Org.apache.shiro.web.mgt.CookieRememberMeManager "><property name=" Cookie "ref=" Remembermecookie "/></ bean><!--Remember me cookie--><bean id= "Remembermecookie" class= "Org.apache.shiro.web.servlet.SimpleCookie" ><!--RememberMe is the name of the cookie--><constructor-arg value= "RememberMe"/><!--remember my cookie effective time 30 days-- <property name= "MaxAge" value= "2592000"/></bean></beans>

4th step: Enable Shiro annotation support in spring MVC configuration

<!--open AOP,--><aop:config proxy-target-class= "true" ></aop:config><!--turn on Shiro annotation support for class proxies- <bean class= "Org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor" >< Property Name= "SecurityManager" ref= "SecurityManager"/></bean>

5th step: Customizing Realm and Formauthenticationfilter

public class Customrealm extends Authorizingrealm {//inject service@autowiredprivate sysservice sysservice;// Set Realm's name @overridepublic void SetName (String name) {super.setname ("Customrealm");} Realm authentication method, query user information from database @overrideprotected authenticationinfo dogetauthenticationinfo (Authenticationtoken token) Throws Authenticationexception {//token is user entered username and password//first step to remove user name from token String usercode = (string) Token.getprincipal () ;///Second step: Query from database according to user input usercode sysuser sysuser = null;try {sysuser = Sysservice.findsysuserbyusercode (Usercode);} catch ( Exception E1) {//TODO auto-generated catch Blocke1.printstacktrace ();} If the query does not return Nullif (sysuser==null) {//return null;} Query from database to password string password = Sysuser.getpassword ();//salt string salted = Sysuser.getsalt ();// If the query to return authentication information Authenticationinfo//activeuser is the user identity information activeuser activeuser = new Activeuser (); Activeuser.setuserid ( Sysuser.getid ()); Activeuser.setusercode (Sysuser.getusercode ()); Activeuser.setusername (SysUser.getUsername ()); /.. Remove menu based on user ID List<syspermission> menus = null;try {//Remove menu via service menus = Sysservice.findmenulistbyuserid (Sysuser.getid ());} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Set the User menu to Activeuseractiveuser.setmenus (menus);//Set the Activeuser setting Simpleauthenticationinfosimpleauthenticationinfo Simpleauthenticationinfo = new Simpleauthenticationinfo (Activeuser, password,bytesource.util.bytes (salt), This.getname ()); return simpleauthenticationinfo;} Used to authorize @overrideprotected Authorizationinfo Dogetauthorizationinfo (principalcollection principals) {//From Principals obtaining Master Identity information// Convert the Getprimaryprincipal method return value to the true identity type (Dogetauthenticationinfo authentication on the top by populating the identity type in simpleauthenticationinfo), Activeuser Activeuser = (activeuser) principals.getprimaryprincipal ();//get permission information based on identity information//get permission data from database list<syspermission> Permissionlist = null;try {permissionlist = Sysservice.findpermissionlistbyuserid (Activeuser.getuserid ());} catch ( Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Set a single Set object List<string> permissions = new arraylist<string> (); if (Permissionlist!=null) {for (Syspermission syspermission: Permissionlist) {//Put the permission tag in the database into the collection Permissions.add (Syspermission.getpercode ());}} Check the permission data, return the authorization information (to include the top of the permissions) Simpleauthorizationinfo Simpleauthorizationinfo = new Simpleauthorizationinfo () ;//Fill the top query to the authorization information into the Simpleauthorizationinfo object Simpleauthorizationinfo.addstringpermissions (permissions); return Simpleauthorizationinfo;} Clear cache public void clearcached () {PrincipalCollection principals = Securityutils.getsubject (). Getprincipals (); Super.clearcache (principals);}}

  

public class Customformauthenticationfilter extends Formauthenticationfilter {// The authentication method of the original Formauthenticationfilter @overrideprotected boolean onaccessdenied (ServletRequest request,servletresponse Response) throws Exception {//Verify the verification code here//Get the correct verification code from session HttpServletRequest HttpServletRequest = ( HttpServletRequest) Request; HttpSession session =httpservletrequest.getsession ();//Remove the session's verification code (correct verification code) String Validatecode = (string) Session.getattribute ("Validatecode");//Check out the verification code of the page//input verification and the validation in session comparison String Randomcode = Httpservletrequest.getparameter ("Randomcode"); if (randomcode!=null && validatecode!=null &&! Randomcode.equals (Validatecode)) {//If the checksum fails, the CAPTCHA error failure message is Httpservletrequest.setattribute ("Shirologinfailure", "Randomcodeerror") via Shirologinfailure settings to request,//Deny access, No longer verifies the account and password return true; }return super.onaccessdenied (request, Response);}}

Sixth step: User Login Control Layer code

@RequestMapping ("login") public String Login (HttpServletRequest request) throws exception{//if login fails to obtain authentication exception information from request Shirologinfailure is the fully qualified name of the Shiro exception class String Exceptionclassname = (string) request.getattribute ("Shirologinfailure");// Based on the exception classpath returned by Shiro, throws the specified exception information if (Exceptionclassname!=null) {if (UnknownAccountException.class.getName (). Equals ( Exceptionclassname) {//will eventually be thrown to the exception processor throw new Customexception ("account does not exist");} else if ( IncorrectCredentialsException.class.getName (). Equals (Exceptionclassname)) {throw new Customexception ("Username/password Error");} else if ("Randomcodeerror". Equals (Exceptionclassname)) {throw new Customexception ("Authenticode Error");} else {throw new Exception ();//end up with an unknown error in the exception processor}}//This method does not handle login success (authentication succeeded), Shiro authentication will automatically jump to the previous request path//Login failed to return to the login page " Login ";}

  

Web Engineering uses spring Mvc+shiro for permission control

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.