First, what is Shiro?
Apache Shiro is a powerful and easy-to-use Java security framework that performs authentication, authorization, cryptography, and session management. Can be used not only in Web projects, but also in common projects
Second, what can Shiro do
Shiro can be fine-grained permission control, including the method, the link, the page Display permissions control.
Iii. using Shiro for Rights Management in Web projects
1. Add Shiro Interceptor in Web. xml
<filter> <filter-name>shiroFilter</filter-name> <filter-class> Org.springframework.web.filter.delegatingfilterproxy</filter-class> <async-supported>true</ async-supported> <init-param> <param-name>targetFilterLifecycle</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping > <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> </filter-mapping>
2. Add Shiro permission annotation support in Spring-mvc.xml
<aop:config proxy-target-class= "true" ></aop:config><bean class= " Org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor "> <property name=" SecurityManager "ref=" SecurityManager "/></bean>
3. Cache management of Ehcache using spring
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Cache= "Http://www.springframework.org/schema/cache" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd Http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/ Spring-cache.xsd "> <!--Support cache annotations--<cache:annotation-driven cache-manager=" Ehcachemanager "/> < ;! --ehcache--> <bean id= "cachemanagerfactory" class= " Org.springframework.cache.ehcache.EhCacheManagerFactoryBean "> <property name=" configlocation "value=" Classpath:ehcache.xml "/> </bean> <bean id=" Ehcachemanager "class=" org.springframework.cache.ehcache.Eh Cachecachemanager "> <property name=" CacheManager "ref=" Cachemanagerfactory "/> </bean></beanS>
4. Using Ehcache for cache management
Add the following cache block in Ehcache
<diskstore path= "Java.io.tmpdir"/> <cache name= "Authorizationcache" maxentrieslocalheap= "2000" eternal= "false" timetoidleseconds= "3600" timetoliveseconds= "0" overflowtodisk= "false" Statistics= "true" > </cache> <cache name= "Authenticationcache" maxentrieslocalheap= " " eternal=" false " timetoidleseconds=" 3600 " timetoliveseconds=" 0 " overflowtodisk=" false " statistics=" true "> </cache> <cache name=" Shiro-activesessioncache " maxentrieslocalheap= "eternal=" false " timetoidleseconds=" 3600 " timetoliveseconds=" 0 " Overflowtodisk= "false" statistics= "true" > </cache>
5. Implement CacheManager interface, use spring for Shiro permission to manage cache
public class Springcachemanagerwrapper implements CacheManager {private Org.springframework.cache.CacheManager Cachem Anager; /** * Set Spring cache Manager * * @param cachemanager */public void Setcachemanager (org.springframework . cache. CacheManager cachemanager) {this.cachemanager = CacheManager; } @Override public <k, v> cache<k, v> getcache (String name) throws Cacheexception {ORG.SPRINGFR Amework.cache.Cache Springcache = Cachemanager.getcache (name); return new Springcachewrapper (Springcache); } Static class Springcachewrapper implements Cache {private Org.springframework.cache.Cache springcache; Springcachewrapper (Org.springframework.cache.Cache springcache) {this.springcache = Springcache; } @Override public Object get (object key) throws Cacheexception {Object value = Springcache.get ( Key); if (value instanceof Simplevaluewrapper) { Return ((simplevaluewrapper) value). get (); } return value; } @Override public object put (object key, Object value) throws Cacheexception {Springcache.put (k EY, value); return value; } @Override public Object remove (object key) throws Cacheexception {springcache.evict (key); return null; } @Override public void Clear () throws Cacheexception {springcache.clear (); } @Override public int size () {if (Springcache.getnativecache () instanceof Ehcache) { Ehcache Ehcache = (Ehcache) springcache.getnativecache (); return Ehcache.getsize (); } throw new Unsupportedoperationexception ("Invoke Spring Cache abstract size method not supported"); } @Override public Set keys () {if (Springcache.getnativecache () instanceof Ehcache) { Ehcache Ehcache = (Ehcache) springcache.getnativecache (); return new HashSet (Ehcache.getkeys ()); } throw new Unsupportedoperationexception ("Invoke spring Cache abstract keys method not supported"); } @Override public Collection values () {if (Springcache.getnativecache () instanceof Ehcache) { Ehcache Ehcache = (Ehcache) springcache.getnativecache (); List keys = Ehcache.getkeys (); if (! Collectionutils.isempty (keys)) {List values = new ArrayList (Keys.size ()); For (object Key:keys) {Object value = Get (key); if (value = null) {Values.add (value); }} return Collections.unmodifiablelist (values); } else {return collections.emptylist (); } } throw new Unsupportedoperationexception ("Invoke Spring Cache abstract values method not supported"); } }}
6. Customize the entities that are placed in the session
public class CustomPrincipal implements Serializable { private Integer ID; Private String username; Public CustomPrincipal (String username) { this.username = username; } public customprincipal (int ID, String username) { this.id = ID; This.username = Username; } Public Integer getId () { return ID; } public void SetId (Integer id) { this.id = ID; } Public String GetUserName () { return username; } public void Setusername (String username) { this.username = username; } /** * This function output will be the default <shiro:principal/> output. * /@Override public String toString () { return username; }}
7. Rewrite Realm
public class Administratorrealm extends Authorizingrealm {private Administratorservice administratorservice; Public Administratorservice Getadministratorservice () {return administratorservice; } public void Setadministratorservice (Administratorservice administratorservice) {This.administratorservice = Administratorservice; } @Override protected Authorizationinfo dogetauthorizationinfo (principalcollection principals) {Customprinc Ipal CustomPrincipal = (customprincipal) principals.getprimaryprincipal (); String username = customprincipal.getusername (); Simpleauthorizationinfo authorizationinfo = new Simpleauthorizationinfo (); set<string> roles = Administratorservice.getroles (username); Roles.add (USERCONSTANTS.ADMINISTRATOR_STR); Authorizationinfo.setroles (roles); Authorizationinfo.setstringpermissions (administratorservice.getpermissions (username)); return authorizationinfo; } @OverRide protected AuthenticationInfo Dogetauthenticationinfo (Authenticationtoken token) throws Authenticationexception { Usernamepasswordtoken Usernamepasswordtoken = (usernamepasswordtoken) token; String username = (string) usernamepasswordtoken.getprincipal (); Administrator Administrator = administratorservice.getadministrator (username); if (Administrator = = null) {throw new unknownaccountexception ();//No Account found} if (Boolean.FALSE.equ ALS (Administrator.getadmistatus ())) {throw new lockedaccountexception ();//Account lockout} CUSTOMPRINCIP Al principal = new CustomPrincipal (Administrator.getadmiid (), Administrator.getadmiaccount ()); Give Authenticatingrealm to use Credentialsmatcher for password matching, if you feel people's bad can be customized implementation Simpleauthenticationinfo AuthenticationInfo = n EW Simpleauthenticationinfo (principal,//user name Administrator.getadmipassword (),//password ByteSource.Util.bytes (Administrator. Getcredentialssalt ()),//salt=username+salt getName ()//realm name); return authenticationinfo; } @Override public void Clearcachedauthorizationinfo (PrincipalCollection principals) {Super.clearcachedauth Orizationinfo (principals); } @Override public void Clearcachedauthenticationinfo (PrincipalCollection principals) {Super.clearcachedaut Henticationinfo (principals); } @Override public void ClearCache (PrincipalCollection principals) {Super.clearcache (principals); public void Clearallcachedauthorizationinfo () {Getauthorizationcache (). Clear (); public void Clearallcachedauthenticationinfo () {Getauthenticationcache (). Clear (); } public void Clearallcache () {clearallcachedauthenticationinfo (); Clearallcachedauthorizationinfo (); }}
8. Spring-shiro.xml Instantiation Class
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:util= "Http://www.springframework.org/schema/util" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://www.springframework.org/schema/bea NS http://www.springframework.org/schema/beans/spring-beans.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/http Www.springframework.org/schema/aop/spring-aop.xsd Http://www.springframework.org/schema/util/HTTP Www.springframework.org/schema/util/spring-util.xsd "> <aop:config proxy-target-class=" true "></AOP: Config> <!--cache Manager--<bean id= "CacheManager" class= "Com.misuosi.mshop.shiro.cache.SpringCacheMan Agerwrapper "> <property name=" CacheManager "ref=" Ehcachemanager "/> </bean> <!-- Voucher match-<bean id= "Credentialsmatcher"class= "Org.apache.shiro.authc.credential.HashedCredentialsMatcher" > <property name= "Hashalgorithmname" value= "MD5"/> <property name= "hashiterations" value= "2"/> <property name= "storedcred Entialshexencoded "value=" true "/> </bean> <!--Realms and <bean id=" Administratorreal M "class=" Com.misuosi.mshop.shiro.realm.AdministratorRealm "> <property name=" Administratorservice "ref= "Administratorservice"/> <property name= "Credentialsmatcher" ref= "Credentialsmatcher"/> <property name= "cachingenabled" value= "false"/> <property name= "authenticationcachingenabled" value = "true"/> <property name= "authenticationcachename" value= "Authenticationcache"/> <PR Operty name= "authorizationcachingenabled" value= "true"/> <property name= "Authorizationcachename" value= "Authorizationcache"/> </bean> <!--session ID Generator-<bean id= "Sessionidgenerator" class= "Org.apache.shiro.session.mgt.eis . Javauuidsessionidgenerator "/> <!--session cookie template--<bean id=" Sessionidcookie "class=" Org.apache.shi Ro.web.servlet.SimpleCookie "> <constructor-arg value=" Sid "/> <property name=" httponl Y "value=" true "/> <property name=" MaxAge "value="-1 "/> </bean> <!--session DAO--&G T <bean id= "Sessiondao" class= "Org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO" > <property Name= "Activesessionscachename" value= "Shiro-activesessioncache"/> <property name= "SessionIdGenerator" R ef= "Sessionidgenerator"/> </bean> <!--session Verification Scheduler-<bean id= "Sessionvalidationschedul Er "class=" Org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler "> <property name=" Sessi OnvaliDationinterval "value=" 1800000 "/> <property name=" SessionManager "ref=" SessionManager "/> </ Bean> <!--Session Manager--<bean id= "SessionManager" class= "Org.apache.shiro.web.session.mgt.DefaultWeb SessionManager "> <property name=" globalsessiontimeout "value=" 1800000 "/> <property N Ame= "Deleteinvalidsessions" value= "true"/> <property name= "sessionvalidationschedulerenabled" value= "tr UE "/> <property name=" Sessionvalidationscheduler "ref=" Sessionvalidationscheduler "/> &L T;property name= "Sessiondao" ref= "Sessiondao"/> <property name= "sessionidcookieenabled" value= "true"/&G T <property name= "Sessionidcookie" ref= "Sessionidcookie"/> </bean> <!--security Manager--<be An id= "SecurityManager" class= "Org.apache.shiro.web.mgt.DefaultWebSecurityManager" > <property name= "Rea LM "ref="Administratorrealm"/> <property name= "SessionManager" ref= "SessionManager"/> <prope Rty name= "CacheManager" ref= "CacheManager"/> </bean> <!--equivalent to calling Securityutils.setsecuritymanager (SE Curitymanager)--<bean class= "Org.springframework.beans.factory.config.MethodInvokingFactoryBean" > <property name= "Staticmethod" value= "Org.apache.shiro.SecurityUtils.setSecurityManager"/> <PR Operty name= "Arguments" ref= "SecurityManager"/> </bean> <!--form-based authentication Filters-<be An id= "Formauthenticationfilter" class= "Org.apache.shiro.web.filter.authc.FormAuthenticationFilter" > <p Roperty name= "Successurl" value= "/admin/index"/> <property name= "loginurl" value= "/admin/login"/> </bean> <bean id= "Adminlogoutfilter" class= "Org.apache.shiro.web.filter.authc.LogoutFilter" > <property Name= "RedirectURL" value= "/admin/login"/> </bean> <!--Shiro Web Filter--<bean id= "Shirofi Lter "class=" Org.apache.shiro.spring.web.ShiroFilterFactoryBean "> <property name=" SecurityManager "ref= "SecurityManager"/> <property name= "Filters" > <util:map> <entry key= "adminauthc" value-ref= "Formauthenticationfilter"/> <entry key= "a Dminlogout "value-ref=" Adminlogoutfilter "/> </util:map> </property> <property name= "Filterchaindefinitions" > <value>/admin/ Login = Adminauthc/admin/logout = adminlogout/admin/** = Adminauth C,roles[admin] </value> </property> </bean> <!--Shiro Life cycle Processor--<bEan id= "Lifecyclebeanpostprocessor" class= "Org.apache.shiro.spring.LifecycleBeanPostProcessor"/></beans >
9, Freemarker use the Shiro label
Paste the implementation of the label into the Freemarker.tag package and add the Freemarker tag to the Freemarker configuration.
public class Shirotagfreemarkerconfigurer extends Freemarkerconfigurer { @Override public Void Afterpropertiesset () throws IOException, templateexception { super.afterpropertiesset (); This.getconfiguration (). setsharedvariable ("Shiro", New Shirotags ());}
10. Complete
Shiro Using Tutorials