Spring Integrated Shiro

Source: Internet
Author: User

Spring Integrated Shiro

I. Configuring Web. XML

<!--Configure the Shiro filter to let the Shiro filter system receive the request first--
<!--here Filter-name must correspond to <bean id= "shirofilter" defined in applicationcontext.xml/>--
<!--use [/*] to match all requests to ensure that all controllable requests are Shiro filtered--
<!--will typically place this filter-mapping in front of the other filter-mapping to ensure it is the first in the filter chain to function--
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<!--this value defaults to False, indicating that the life cycle is managed by Springapplicationcontext and set to True indicates that Servletcontainer is managed by
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


Second, the configuration Applicationcontext.xml

<!--a custom realm that inherits from Authorizingrealm, that is, the class that specifies Shiro to verify that the user is logged on as a custom Shirodbrealm.java-
<bean id= "Myrealm" class= "Com.jadyer.realm.MyRealm"/>

<!--Shiro uses the session of the Servlet container by default, and the SessionMode property allows you to specify the use of Shiro native session--
<!--namely <property name= "SessionMode" value= "native"/&gt, detailed description See official documents--
<!--this is mainly about setting up a custom single realm app, and if you have more than one realm, you can use the ' Realms ' attribute instead of
<bean id= "SecurityManager" class= "Org.apache.shiro.web.mgt.DefaultWebSecurityManager" >
<property name= "Realm" ref= "Myrealm"/>
</bean>

<!--the Shiro main filter itself is powerful, and its strength is that it supports any custom filter execution based on URL path expressions--
<!--Web applications, Shiro-controlled Web requests must be intercepted by Shiro primary filters, Shiro provides the perfect support for spring-based Web applications-
<bean id= "Shirofilter" class= "Org.apache.shiro.spring.web.ShiroFilterFactoryBean" >
<!--Shiro's core security interface, this property is required--
<property name= "SecurityManager" ref= "SecurityManager"/>
<!--require a login link (can be replaced according to the URL of the project), non-required properties, by default automatically look for "/login.jsp" page under the Web project root directory--
<property name= "loginurl" value= "/"/>
<!--the connection to jump after successful login (this property is not used in this example, because the processing logic after the successful login is hardcoded in Logincontroller to main.jsp)--
<!--<property name= "Successurl" value= "/system/main"/>--
<!--users access resources that are not authorized, the connection that is displayed--
<!--If you want to test this property more clearly, you can modify its value, such as unauthor.jsp, and then use [Jade] login to access/admin/listuser.jsp and see the browser will show unauthor.jsp
<property name= "Unauthorizedurl" value= "/"/>
<!--Shiro Connection constraint configuration, which is the definition of the filter chain--
<!--here to work with this article to understand the effects of each filter connection http://blog.csdn.net/jadyer/article/details/12172839-
<!--the first '/' of the following value value represents the path relative to the value of Httpservletrequest.getcontextpath ()
<!--anon: it corresponds to the filter inside is empty, nothing to do, here. Do and. JSP behind the * represents parameters, such as Login.jsp?main
<!--authc: The page under the filter must be validated before it can be accessed, it is a Shiro built-in interceptor Org.apache.shiro.web.filter.authc.FormAuthenticationFilter
<property name= "Filterchaindefinitions" >
<value>
/mydemo/login=anon
/mydemo/getverifycodeimage=anon
/main**=authc
/user/info**=authc
/admin/listuser**=authc,perms[admin:manage]
</value>
</property>
</bean>

<!--guarantees that the bean that implements the Shiro internal lifecycle function is executed--
<bean id= "Lifecyclebeanpostprocessor" class= "Org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

<!--open Shiro annotations (such as @requiresroles, @RequiresPermissions), use SPRINGAOP to scan classes using Shiro annotations and, if necessary, verify the security logic--
<!--Configure the following two beans for this function--
<!--Enable Shiro Annotations for spring-configured beans. Only run after the Lifecyclebeanprocessor have run--
<!--because the Shiro annotations are not used in this example, comment out the two beans (individuals feel that the permissions are hardcoded in the program by way of annotations, it is not very convenient to view them, it is not necessary to use them)-
<!--
<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>
-

Three Automatic Realm classes


public class Myrealm extends Authorizingrealm {
/**
* Grant roles and permissions to the currently logged on subject
* @see tested: In this case, the call time for the method is required to authorize the resource to be accessed
* @see tested: The logic in the method is executed every time a resource is accessed, indicating that the Authorizationcache is not enabled by default in this example
* @see Personal feeling if you use the Concurrentmapcache support that Spring3.1 started with, you have the flexibility to decide whether to enable Authorizationcache
* @see For example, when obtaining permission information from a database, first access the cache provided by Spring3.1 instead of using the Authorizationcache provided by Shior
*/
@Override
Protected Authorizationinfo Dogetauthorizationinfo (principalcollection principals) {
Gets the user name of the currently logged on, equivalent to (String) Principals.fromrealm (This.getname ()). Iterator (). Next ()
String currentusername = (string) super.getavailableprincipal (principals);
list<string> rolelist = new arraylist<string> ();
list<string> permissionlist = new arraylist<string> ();
Get details of the currently logged in user from the database
User user = Userservice.getbyusername (currentusername);
if (null! = user) {
Entity class User contains entity class information for user roles
if (Null!=user.getroles () && user.getroles (). Size () >0) {
Get the role of the currently logged on user
For (Role role:user.getRoles ()) {
Rolelist.add (Role.getname ());
Entity class role contains entity class information with role permissions
if (Null!=role.getpermissions () && role.getpermissions (). Size () >0) {
Get Permissions
For (Permission pmss:role.getPermissions ()) {
if (! Stringutils.isempty (Pmss.getpermission ())) {
Permissionlist.add (Pmss.getpermission ());
// }
// }
// }
// }
// }
}else{
throw new Authorizationexception ();
// }
Set roles and permissions for the current user
Simpleauthorizationinfo simpleauthorinfo = new Simpleauthorizationinfo ();
Simpleauthorinfo.addroles (rolelist);
Simpleauthorinfo.addstringpermissions (permissionlist);
Simpleauthorizationinfo simpleauthorinfo = new Simpleauthorizationinfo ();
In practice, it may be obtained from the database as noted above
if (Null!=currentusername && "Mike". Equals (CurrentUserName)) {
Add a role, not an add in the configuration sense, but prove that the user has the Admin role
Simpleauthorinfo.addrole ("admin");
Add permissions
Simpleauthorinfo.addstringpermission ("Admin:manage");
System.out.println ("the [admin] role and [admin:manage] permissions have been given to the user [Mike]");
return simpleauthorinfo;
}
If the method does not do anything directly return NULL, it will cause any user access to/admin/listuser.jsp will automatically jump to unauthorizedurl specified address
See <bean id= "Shirofilter" > Configuration in Applicationcontext.xml
return null;
}


/**
* Verify the current login subject
* @see Tested: In this example, the method is called in the Logincontroller.login () method when the Subject.login () is executed
*/
@Override
Protected AuthenticationInfo Dogetauthenticationinfo (Authenticationtoken authctoken) throws Authenticationexception {
To obtain a token based on a user name and password
In fact, this authctoken was sent from the Logincontroller inside Currentuser.login (token).
All two tokens are quoted in the same way.
Usernamepasswordtoken token = (usernamepasswordtoken) Authctoken;
System.out.println ("Get to token when validating current subject" + reflectiontostringbuilder.tostring (token, Tostringstyle.multi_line_ STYLE));
User user = Userservice.getbyusername (token.getusername ());
if (null! = user) {
AuthenticationInfo authcinfo = new Simpleauthenticationinfo (User.getusername (), User.getpassword (), User.getnickname ());
This.setsession ("CurrentUser", user);
return authcinfo;
}else{
return null;
// }
There is no need for comparison, the logic of the Shiro will do, we just need to return a token-related validation information
White is the first parameter to fill in the login user name, the second parameter to fill in the legal login password (can be taken from the database, in this case, in order to demonstrate hard-coded)
This way, only the user and password specified here can be verified on the subsequent login page.
if ("Mike". Equals (Token.getusername ())) {
AuthenticationInfo authcinfo = new Simpleauthenticationinfo ("Mike", "Mike", This.getname ());
This.setsession ("CurrentUser", "Mike");
return authcinfo;
}
A Unknownaccountexception exception is thrown in Logincontroller when no Simpleauthenticationinfo object is returned for the login user name
return null;
}


/**
* Put some data into the shirosession for easy use in other places
* @see such as controller, the use of Httpsession.getattribute (key) can be taken to
*/
private void Setsession (object key, object value) {
Subject CurrentUser = Securityutils.getsubject ();
if (null! = CurrentUser) {
Session session = Currentuser.getsession ();
SYSTEM.OUT.PRINTLN ("Session default time-out is [" + session.gettimeout () + "] milliseconds");
if (null! = session) {
Session.setattribute (key, value);
}
}
}
}

Spring Integrated Shiro

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.