Apache Shiro Learning Note (ii) authentication

Source: Internet
Author: User

Ruchunli's work notes , a good memory is worse than a bad pen


authentication , that is, in the application who can prove that he is himself, the application system in general through the user name/password to prove.
In Shiro, the user needs to provide principals (identity) and credentials (proof) to Shiro so that the application can authenticate the user:
Principals: Identity, that is, the identity of the principal attribute, can be anything, such as user name, mailbox, etc., the only thing. A subject can have multiple principals, but only one primary principals, usually username/password/mobile number.
Credentials: proof/credential, that is, only the principal knows the security value, such as password/digital certificate.
The most common combination of principals and credentials is the username/password.


Authenticator: The authenticator, responsible for the main authentication, this is an extension point, if the user feels Shiro default is not good, can be customized implementation; It requires authentication policy (authentication strategy), That is, under what circumstances the user authentication passed;

Package Org.apache.shiro.authc;public interface Authenticator {/** * Authenticates a user based on the submitted {      @code Authenticationtoken}. */Public AuthenticationInfo Authenticate (Authenticationtoken Authenticationtoken) throws Authenticationexce ption;}

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/84/61/wKiom1ePCs3gnEnQAAO-8Rda_B8449.jpg "title=" Qq20160720132250.jpg "alt=" Wkiom1epcs3gnenqaao-8rda_b8449.jpg "/>


Realm: There can be 1 or more realms that can be considered a secure Entity data source, which is used to obtain a security entity, either a JDBC implementation or an LDAP implementation, or a memory implementation, etc., provided by the user;

package org.apache.shiro.realm;import org.apache.shiro.authc.authenticationexception;import  org.apache.shiro.authc.authenticationinfo;import org.apache.shiro.authc.authenticationtoken;/** *  A <tt>Realm</tt> is a security component that can  Access application-specific security entities * such as users, roles,  and permissions to determine authentication and authorization  operations. * *  @see  org.apache.shiro.realm.cachingrealm cachingrealm * @ see org.apache.shiro.realm.authenticatingrealm authenticatingrealm *  @see   org.apache.shiro.realm.authorizingrealm authorizingrealm *  @see   org.apache.shiro.authc.pam.modularrealmauthenticator modularrealmauthenticator *  @since   0.1 */public interface realm {    /**     * returns the  (Application-unique)  name  Assigned to this <code>realm</code>.      * all  realms configured for a single application must have a  unique name.     *  returns a unique realm name      * @ return the  (Application-unique)  name assigned to this <code>Realm< /code>.     */    string getname ();     /**     * Returns <tt>true</tt> if this  Realm wishes to authenticate the subject represented by the given      * {@link  org.apache.shiro.authc.AuthenticationToken  Authenticationtoken} instance, <tt>false</tt> otherwise.     *  determine if this realm supports this token      */    boolean supports (Authenticationtoken token);     /**     * returns an account ' s  Authentication-specific information for the specified <tt>token</tt>,      * or <tt>null</tt> if no account could  be found based on the <tt>token</tt>.      *  Obtaining certification information based on token      */    AuthenticationInfo  Getauthenticationinfo (Authenticationtoken token)  throws authenticationexception;}

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/84/61/wKioL1ePC56TKivUAAMmHzMZxzs119.jpg "title=" Qq20160720132602.jpg "alt=" Wkiol1epc56tkivuaammhzmzxzs119.jpg "/>

Note: Shiro does not know where your users/permissions are stored and in what format, so we generally need to implement our realm in the application.


Single Realm configuration

1. Custom Realm Implementation

package com.invicme.apps.shiro.realm.single;import org.apache.shiro.authc.authenticationexception; import org.apache.shiro.authc.authenticationinfo;import org.apache.shiro.authc.authenticationtoken; import org.apache.shiro.authc.incorrectcredentialsexception;import  org.apache.shiro.authc.simpleauthenticationinfo;import org.apache.shiro.authc.unknownaccountexception; import org.apache.shiro.authc.usernamepasswordtoken;import org.apache.shiro.realm.realm;/** *   *  @author  lucl *  */public class myrealmone implements  Realm {     @Override     public string getname ()  {        return this.getclass (). GetName ();     }     @Override     public boolean supports ( Authenticationtoken token)  {        //  only supports usernamepasswordtoken  types of token         return token instanceof UsernamePasswordToken;    }      @Override     public authenticationinfo getauthenticationinfo ( Authenticationtoken token)             throws  authenticationexception {        string principal  = string.valueof (Token.getprincipal ());             //  Get Identity (username)         string credentials =  new string ((char[]) token.getcredentials ());    //  Get authentication/voucher (password)                  if (! " Lucl ". Equals (principal)) &NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSp;       throw new unknownaccountexception ("Username/password Error");  //   If the user name is incorrect         }         if (! " 123 ". Equals (credentials))  {            throw  new incorrectcredentialsexception ("User credential Error"); //  if password is incorrect          }        //  If authentication is successful, return a AuthenticationInfo implementation ;         return new simpleauthenticationinfo (String.valueOf ( Principal),  string.valueof (credentials),  this.getname ());    }     }

2. ini configuration file specify custom realm implementation

[main]# Declaration of custom realmmyrealm=com.invicme.apps.shiro.realm.single.myrealmone# Specifies the realms implementation of the SecurityManager securitymanager.realms= $myRealm # variable name = Fully qualified class name automatically creates a class instance # variable name. property = value automatically calls the appropriate setter method to assign the value # $ Variable name refers to an object instance before

3. Test Cases

@Testpublic  void testAuthenticatorSingleRealm  ()  {    // 1, Gets the SecurityManager factory, where the INI configuration file is used to initialize the securitymanager    factory< Org.apache.shiro.mgt.securitymanager> factory = new inisecuritymanagerfactory (" Classpath:shiro/shiro-authenticator-single-realm.ini ");         //  2, get SecurityManager instance and bind to securityutils    org.apache.shiro.mgt.securitymanager  Securitymanager = factory.getinstance ();     securityutils.setsecuritymanager ( SecurityManager)         // 3, get subject and create username/password Authentication token (user identity/ Voucher)     subject subject = securityutils.getsubject ();     usernamepasswordtoken token = new usernamepasswordtoken ("Lucl",  "123");         try{   &nBsp;    // 4, Login, authentication         subject.login ( token);    } catch  (authenticationexception e)  {         // 5, authentication failed         logger.info (" User authentication failed ");         e.printstacktrace ();    }         if  (subject.isauthenticated ())  {         logger.info ("The user is logged on successfully. ");     } else {        logger.info (" User logon failed. ");     }    // 6, exit     subject.logout ();}


Multi-Realm configuration

1. Custom Realm Implementation


2. ini configuration file specify custom realm implementation


3. Test Cases

This article is from the "world of Stuffy Gourd" blog, please be sure to keep this source http://luchunli.blog.51cto.com/2368057/1828038

Apache Shiro Learning Note (ii) authentication

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.