Shiro Getting started with authentication authorization

Source: Internet
Author: User
First, Introduction:

Shiro is a powerful and flexible open source security framework provided by Apache that handles identity authentication, authorization, enterprise session management, and encryption.
Shiro Features: User authentication, user execution access control, use of Session API in any environment, such as CS program. You can use multiple data sources, such as using both Oracle and MySQL. Single Sign-On (SSO) support. Remember me service. Detailed introduction also please crossing Network manual: Http://shiro.apache.org/reference.html

Unlike spring security, the main difference between the two is that:
1, Shiro flexibility, easy to learn and easy to expand. At the same time, not only can be used in the web, can work in the task environment.
2, Acegi flexibility is poor, more difficult to understand, at the same time with the spring integration of good.
If you require a higher-level item, your personal recommendation is to use Shiro, mainly because you can easily scale to your business needs.
The attachment is a jar integration and source code integrated with Shiro. second, Shiro and spring integration

Shiro default configuration, mainly loading INI file for initialization work, specific configuration, also please crossing Web Manual (http://shiro.apache.org/web.html) init file does not support integration with spring. Here's how to integrate with spring and SPRINGMVC. 1. config Shiro filter in Web. XML,

The configuration class in Web. XML is done using the Spring filter proxy class.

<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>  
2. Add the Shiro configuration to the Application.xml file in spring:
<!--SecurityManager is the core of Shiro and coordinates each module at initialization--<bean id= "SecurityManager" class= " Org.apache.shiro.web.mgt.DefaultWebSecurityManager "> <!--single realm using realm, if you have more than one realm, use the Realms attribute instead of--&lt ;p roperty name= "Realm" ref= "Leopardrealm"/> <property name= "CacheManager" ref= "Shiroehcachemanager"/> &L T;/bean> <!--realm configuration, Realm is Shiro Bridge, it is mainly used to determine whether subject can login and permissions, etc.--<bean id= "Leopardrealm" class= "Co M.leopard.shiro.realm.leopardrealm "/> <!--Shiro Filter configuration, the Bean ID value must be the same as the value of Filter-name in the Web--<bean id=" Shirofilter "class=" Org.apache.shiro.spring.web.ShiroFilterFactoryBean "> <property name=" SecurityManager " ref= "SecurityManager"/> <!--do not have permission or jump after failure page--<property name= "loginurl" value= "/login/log in.jsp "/> <property name=" Successurl "value="/main/index.jsp "/> <property name=" UnauthorizedU RL "value="/login/unauthorized "/> <property Name= "Filterchaindefinitions" > <value>/login/logoutlogout=logout /login/**=anon/**=authc,rest </value> </property> </be An> <!--user authorization/authentication information cache with Ehcache Cache--<bean id= "Shiroehcachemanager" class= "org.apache.shiro.c Ache.ehcache.EhCacheManager "> <property name=" cachemanagerconfigfile "value=" Classpath:ehcache-shiro.xml "/   > </bean>

Configuration Description:
SecurityManager is the core of Shiro, which coordinates the operation of each module during initialization.
Realm is a Shiro bridge for data source configuration, Shrio provides a common realm data source configuration, such as the Inirealm of LDAP jndildaprealm,jdbc jdbcrealm,ini files, Properties file Propertiesrealm, etc., can also insert their own realm implementation to represent a custom data source. A custom Leopardrealm is used here to configure the Java code as follows:

public class Leopardrealm extends Authorizingrealm {/** * authorization method, in the case of a cache, load only once. */protected Authorizationinfo Dogetauthorizationinfo (principalcollection principals) {Simpleauthoriza  
                 Tioninfo info = new Simpleauthorizationinfo ();  
                 Get all the information about the user information, such as permission roles.  
        Info.setstringpermissions (permission set);  
        Info.setroles (role set);  
    return info; }/** * Login authentication */@Override protected authenticationinfo dogetauthenticationinfo (authenticatio Ntoken token) throws Authenticationexception {Usernamepasswordtoken Usernamepasswordtoke = (Us  
        Ernamepasswordtoken) token;  
        String username = usernamepasswordtoke.getusername (); return simpleauthenticationinfo new Shirouser ("admin", "admin"), "admin", ByteSource.Util.by  

    TES ("admin"), GetName ()); }  
}  

The

Shirofilter:shiro's permission filter configuration allows you to customize the filter and associate it to filterchaindefinitions. Shiro Filter Description:
Shiro Filter Class:
Filter name corresponding Java class
anon Org.apache.shiro.web.filter.authc.AnonymousFilter
AUTHC Org.apache.shiro.web.filter.authc.FormAuthenticationFilter
Authcbasic Org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter
Logout Org.apache.shiro.web.filter.authc.LogoutFilter
Nosessioncreation Org.apache.shiro.web.filter.session.NoSessionCreationFilter
Perms Org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter
Port Org.apache.shiro.web.filter.authz.PortFilter
Rest Org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter
Roles Org.apache.shiro.web.filter.authz.RolesAuthorizationFilter
SSL Org.apache.shiro.web.filter.authz.SslFilter
User Org.apache.shiro.web.filter.authc.UserFilter

Anon: Example/admins/**=anon has no parameters, which means it can be used anonymously.
AUTHC: For example,/ADMINS/USER/**=AUTHC indicates that authentication (login) is required to use, without parameters.
Authcbasic: For example/admins/user/**=authcbasic no parameter represents httpbasic authentication.
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 only, equivalent to the Hasallroles () method.
Perms: Example/admins/user/ =perms[user:add:], arguments can be written multiple, multiple must be quoted, and the parameters are separated by commas, for example/admins/user/ = perms["user:add:,user:modify:*"], when there are multiple arguments, each parameter must pass before passing, 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, etc., servername is the host,8081 you access is the port in the URL configuration, querystring is the URL you visit. The following parameters.
SSL: Example/admins/user/**=ssl has 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

Note: These filters Anon,authcbasic,auchc,user is the authentication filter, Perms,roles,ssl,rest,port is the authorization filter
The configuration work is now complete. 3, simple login operation:

login.jsp Code

<%@ page language= "java" pageencoding= "UTF-8"%>  

SPRINGMVC Control Layer Code:

Import Javax.servlet.http.HttpServletRequest;  
Import Javax.servlet.http.HttpServletResponse;  
Import Org.apache.shiro.SecurityUtils;  
Import org.apache.shiro.authc.AuthenticationException;  
Import org.apache.shiro.authc.IncorrectCredentialsException;  
Import org.apache.shiro.authc.UnknownAccountException;  
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.servlet.ModelAndView; @Controller ("Loginaction") @RequestMapping ("/login") public class Loginaction {@RequestMapping ("")// Login Public Modelandview Execute (httpservletrequest request, HttpServletResponse response,string Usernam  
        e,string password) {Usernamepasswordtoken token = new Usernamepasswordtoken (Username,password);  
      Record this token token.setrememberme (false);  Subject Permission Object Subject Subject = Securityutils.getsubject ();  
        try {subject.login (token);  
        } catch (Unknownaccountexception ex) {//user name not found Ex.printstacktrace ();  
        } catch (Incorrectcredentialsexception ex) {//user name password does not match ex.printstacktrace ();  
        }catch (authenticationexception e) {//Other login error e.printstacktrace (); }//Verify the successful login method if (subject.isauthenticated ()) {return new Modelandview ("/MAIN/INDEX.J  
        SP ");  
    } return new Modelandview ("/login/login.jsp"); }//Exit @RequestMapping ("/logout") public void Logout () {Subject Subject = securityutils.  
        Getsubject ();  
    Subject.logout ();   }  
}

Finally started the service login, the experiment proves that the failure returned to the login page and successfully entered the home page.

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.