Shiro Security Framework Entry (Login Verification example detailed and source code)

Source: Internet
Author: User
Tags aop md5 md5 encryption
A brief introduction of Shiro framework

The Apache Shiro is a Java security framework designed to simplify authentication and authorization. Shiro can be used in both Javase and Java EE projects. It is mainly used to deal with identity authentication, authorization, enterprise session management and encryption. The specific function points of Shiro are as follows:

(1) Identity authentication/login, verify that the user has the corresponding identity;
(2) Authorization, that is, permission validation, verify that an authenticated user has a certain permission, that is, to determine whether the user can do things, such as: Verify that a user has a role. or fine-grained to verify that a user has a permission on a resource;
(3) Session management, that is, the user login is a session, before exiting, all of its information in the session, the session can be a common javase environment, can also be like the web environment;
(4) encryption, protection of data security, such as password encryption stored in the database, rather than plaintext storage;
(5) Web support, which can be easily integrated into the web environment;
Caching: caching, such as user login, the user information, the role/permissions do not have to check every time, this can improve efficiency;
(6) Shiro supports concurrent verification of multi-threaded applications, such as opening another thread in one thread, which automatically propagates the past;
(7) Provide test support;
(8) Allow a user to pretend to be visited by another user (if they allow);
(9) Remember me, this is a very common function, that is, once logged in, the next time you do not have to log in.

Text descriptions may not allow apes to fully understand the meaning of specific functions. Here we take the login verification as an example, to the ape friends to introduce the use of Shiro. As for other function points, ape friends use the time to delve into its usage is not too late. Second, Shiro detailed description of the case

This instance environment: Eclipse + Maven
The main technology used in this example: Spring + SPRINGMVC + Shiro

2.1, the dependent package

Assuming that spring and SPRINGMVC are already configured, you will also need to introduce Shiro and Shiro integration into spring's packages, which Maven relies on as follows:

<!--Spring integration Shiro needs-->  
<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>  

2.2. Define Shiro Interceptor

Blocks URLs, if validation is not validated successfully, and then additional roles and permissions are given to the user.

Custom interceptors need to inherit Authorizingrealm and implement two methods for logon authentication and role granting permissions, as follows:

Package Com.luo.shiro.realm;
Import Java.util.HashSet;
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.SimpleAuthenticationInfo;
Import Org.apache.shiro.authc.UsernamePasswordToken;
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 Com.luo.util.DecriptUtil;  public class Myshirorealm extends Authorizingrealm {//here because there is no call backstage, there is only one user directly by default ("Luoguohui", "123456") private static  
    Final String user_name = "Luoguohui";  

    private static final String PASSWORD = "123456";  * * Authorized/* @Override protected Authorizationinfo dogetauthorizationinfo (principalcollection principals)  
{set<string> rolenames = new hashset<string> ();        set<string> permissions = new hashset<string> ();  Rolenames.add ("Administrator");//Add Role Permissions.add ("newpage.jhtml");  
        Add permissions Simpleauthorizationinfo info = new Simpleauthorizationinfo (rolenames);  
        Info.setstringpermissions (permissions);  
    return info; } * * Login verification/@Override protected AuthenticationInfo dogetauthenticationinfo (authent Icationtoken Authctoken) throws Authenticationexception {Usernamepasswordtoken token = (usernamepasswordtoken) au
        Thctoken; if (Token.getusername (). Equals (user_name)) {Return to New Simpleauthenticationinfo (user_name, DECRIPTUTIL.MD5 (pass  
        WORD), GetName ());  
        }else{throw new Authenticationexception ();
 }
    }

}

2.3, Shiro configuration file

The contents of the Spring-shiro.xml file are as follows:

<?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:x   
                        Si= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://www.springframework.org/schema/beans   

    Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd "default-lazy-init=" True > <description>shiro configuration</description> <!--Shiro ' s main business-tier object for we b-enabled applications--> <bean id= "SecurityManager" class= Er "> <property name=" Realm "ref=" Myshirorealm "/> <property name=" CacheManager "ref=" cache Manager "/> </bean> <!--project Customized realm--> <bean id=" Myshirorealm "class=" Com.luo.shiro . Realm. Myshirorealm "> <property name=" CacheManager "ref=" CacheManager "/> </bean> <!--S Hiro Filter-->  
    <bean id= "Shirofilter" class= "Org.apache.shiro.spring.web.ShiroFilterFactoryBean" > <property nam  
        E= "SecurityManager" ref= "SecurityManager"/> <property name= "loginurl" value= "/login.jhtml"/> <property name= "Successurl" value= "/loginsuccess.jhtml"/> <property name= "unauthorizedurl" value= "/e" Rror.jhtml "/> <property name=" filterchaindefinitions "> <value>/ index.jhtml = authc/login.jhtml = Anon/checklogin.json = Anon/login  
        success.jhtml = Anon/logout.json = Anon/** = authc </value> </property> </bean> <!--user authorization information cache--> <bean id= "CacheManager" class= org. Apache.shiro.cache.MemoryConstrainedCacheManager "/> <!--guarantee the implementation of the Shiro internal lifecycle function of the bean execution--> <bea n id= "LIFECYCLEBEANPOSTPRocessor "class=" Org.apache.shiro.spring.LifecycleBeanPostProcessor/> <!--AOP method level permission checks--> n class= "Org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on= "Lifecyclebeanpo Stprocessor "> <property name=" Proxytargetclass "value=" true "/> </bean> <bean CLA ss= "Org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor" > <property name= "sec   Uritymanager "ref=" SecurityManager "/> </bean> </beans>

It is necessary to be clear about the meaning of the various property properties in the Bean "Shirofilter":

(1) SecurityManager: This attribute is necessary, there is nothing to say, so the configuration is good.
(2) Loginurl: The user who does not log in requests the page that needs to be logged in, automatically jumps to the login page and can be configured or not configured.
(3) Successurl: Login Successfully default jump page, not configured to jump to "/", generally can not configure, directly through the code to deal with.
(4) Unauthorizedurl: No permissions to the default jump page.
(5) Filterchaindefinitions, it is necessary to explain the filter in detail:

1) Shiro authentication URL, url matching success will no longer continue to match lookup (so pay attention to the URL in the configuration file order, especially in the use of characters), so filterchaindefinitions configuration sequence for the Top-down, to the top of whichever

2 when running a Web application, Shiro will create some useful default filter instances and automatically place them in the [main] item as the default filter instance that can be automatically available is defined by the Defaultfilter enumeration class, The name field of the enumeration is the name that is available for configuration

3 These filters can usually be divided into two groups:

Anon,authc,authcbasic,user is the first group of certified filters

Perms,port,rest,roles,ssl is the second set of authorization filters

Note that the user and the authc are different: When the application is turned on RememberMe, the next time users visit can be a username, but will not be authc, because AUTHC is required to re-authenticate the
User means that users may not have passed the authentication, as long as the user who has been Shiro to remember the login status can initiate the request normally, such as RememberMe

To be blunt, a previous user logged on RememberMe, and then he closed the browser, and the next time he visited, he was a user, not authc

4) Give a few examples
/admin=authc,roles[admin] to indicate that the user must have passed authentication and have the admin role to initiate a normal '/admin ' request
/edit=authc,perms[admin:edit ] indicates that the user must have passed the authentication and has the Admin:edit permission to initiate the '/edit ' request
/home=user indicates that the user does not necessarily have to pass the authentication, only need to be Shiro remember the login status can initiate the '/home ' request normally

5) Each default filter is commonly used as follows (note that the URL pattern is used for two stars, so as to achieve a full match at any level)
/admins/**=anon, indicating that it can be used anonymously, can be understood as anonymous users or visitors
/admins/user /**=AUTHC, which means that authentication is required to use
/admins/user/**=authcbasic without parameters, indicating httpbasic authentication
/admins/user/**=user without parameters, indicating that a user must exist. When the login operation does not check
/admins/user/**=ssl, which represents a secure URL request, the protocol is HTTPS
/admins/user/*=perms[user:add:]
The argument can be written more than one, and the arguments must be quoted , and the arguments are separated by commas, such as the/admins/user/*=perms["user:add:,user:modify:*"
when there are multiple arguments, each parameter must pass to pass, equivalent to the Ispermitedall () method
/ ADMINS/USER/**=PORT[8081]
jumps to schemal://servername:8081?querystring
when the requested URL port is not 8081 Where Schmal is the protocol http or HTTPS, ServerName is your access to the host,8081 port, querystring is the URL you visited? The following argument
/admins/user/**=rest[ User]
According to the requested method, equivalent to/admins/user/**=perms[user:method], where methods are Post,get,delete, etc.
/admins/user/**=roles[ Admin]
The argument can be written multiple times and must be enclosed in quotation marks, and the arguments are separated by commas, such as/admins/user/**=roles["Admin,guest"]
when there are multiple arguments, each parameter must pass. Equivalent to the Hasallroles () method

For more information, please visit the http://www.cppblog.com/guojingjia2006/archive/2014/05/14/206956.html for more details.

2.4, Web.xml configuration to introduce the corresponding configuration files and filters

<!--read Spring and Shiro configuration files-->
<context-param>
    <param-name>contextconfiglocation</ Param-name>
    <param-value>classpath:application.xml,classpath:shiro/spring-shiro.xml</ param-value>
</context-param>

<!--Shiro filter-->
<filter>  
    <filter-name >shiroFilter</filter-name>  
    <filter-class> org.springframework.web.filter.delegatingfilterproxy</filter-class>  
    <init-param>  
        < param-name>targetfilterlifecycle</param-name>  
        <param-value>true</param-value>  
    </init-param>  
</filter>  
<filter-mapping>  
    <filter-name>shirofilter</ filter-name>  
    <url-pattern>*.jhtml</url-pattern>  
    <url-pattern>*.json</ Url-pattern>  

2.5, controller code

Package Com.luo.controller;
Import Java.util.HashMap;

Import Java.util.Map;

Import Javax.servlet.http.HttpServletRequest;
Import Org.apache.shiro.SecurityUtils;
Import Org.apache.shiro.authc.UsernamePasswordToken;
Import Org.apache.shiro.subject.Subject;
Import Org.springframework.stereotype.Controller;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.bind.annotation.RequestMethod;
Import Org.springframework.web.bind.annotation.ResponseBody;

Import Org.springframework.web.servlet.ModelAndView;
Import Com.alibaba.druid.support.json.JSONUtils;
Import Com.luo.errorcode.LuoErrorCode;
Import com.luo.exception.BusinessException;

Import Com.luo.util.DecriptUtil; @Controller public class Usercontroller {@RequestMapping ("/index.jhtml") public Modelandview GetIndex (httpservle
        Trequest request) throws Exception {Modelandview Mav = new Modelandview ("index");
    return MAV; } @RequestMapping ("/exceptionforpagejumps.jhTml ") Public Modelandview Exceptionforpagejumps (HttpServletRequest request) throws Exception {throw new Busin
    Essexception (Luoerrorcode.null_obj); @RequestMapping (value= "/businessexception.json", Method=requestmethod.post) @ResponseBody public String b
    Usinessexception (HttpServletRequest request) {throw new businessexception (luoerrorcode.null_obj); @RequestMapping (value= "/otherexception.json", Method=requestmethod.post) @ResponseBody public String othe
    Rexception (HttpServletRequest request) throws Exception {throw new Exception (); //Jump to login page @RequestMapping ("/login.jhtml") public Modelandview Login () throws Exception {Modelandvi
        EW Mav = new Modelandview ("login");
    return MAV;
        //Jump to login Success page @RequestMapping ("/loginsuccess.jhtml") public Modelandview loginsuccess () throws Exception {
        Modelandview Mav = new Modelandview ("loginsuccess");
    return MAV;
}
    @RequestMapping ("/newpage.jhtml") public Modelandview newpage () throws Exception {Modelandview = new
        Modelandview ("NewPage");
    return MAV; @RequestMapping ("/newpagenotadd.jhtml") public Modelandview Newpagenotadd () throws Exception {Modeland
        View Mav = new Modelandview ("Newpagenotadd");
    return MAV; /** * Verify username and password * @param String username,string Password * @return */@RequestMapping (v Alue= "/checklogin.json", Method=requestmethod.post) @ResponseBody public string Checklogin (string Username,stri
        ng password) {map<string, object> result = new hashmap<string, object> ();  
            try{Usernamepasswordtoken token = new Usernamepasswordtoken (username, decriptutil.md5 (password));  
            Subject CurrentUser = Securityutils.getsubject (); if (!currentuser.isauthenticated ()) {//Use Shiro to verify Token.setrememBerme (TRUE); Currentuser.login (token)//Verify roles and Permissions}}catch (Exception ex) {throw new Businessexception (
        Luoerrorcode.login_verify_failure);
        } result.put ("Success", true);  
    return jsonutils.tojsonstring (Result); /** * Exit Login/@RequestMapping (value= "/logout.json", Method=requestmethod.post) @ResponseB
        Ody public String Logout () {map<string, object> result = new hashmap<string, object> ();
        Result.put ("Success", true);       
        Subject CurrentUser = Securityutils.getsubject ();    
        Currentuser.logout ();
    return jsonutils.tojsonstring (Result);
 }  
}

The code above, we just need to pay more attention to login verification and exit login code.
which decriptutil.md5 (password), the password MD5 encryption and decryption is my own writing tool class Decriptutil, corresponding to the Myshirorealm inside the login verification has corresponding method.
In addition, Businessexception is the exception class that I encapsulate myself.
Finally, it will provide the whole project source code for the ape friend to download, which contains all the codes.

2.6, login.jsp code

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%>  

2.7, the effect demonstration

(1) If not logged in before, enter Http://localhost:8080/web_

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.