Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is Shiro authentication

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you about what is Shiro verification. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

Shiro authentication: users need to provide some proof of identity (password, certificate, etc.) that the system understands and trusts to prove that they can log in to the system.

There are several terms that need to be understood during the verification phase:

Subject-can be popularly understood as the user who accesses the application. It's just that this user can be a person, a third-party process, and so on.

Principals-the unique identification attribute of the principal. For example: ID card number, mobile phone number, mailbox and so on.

Credentials (credential)-A security value that only the principal knows. For example: password, digital certificate and so on.

Realms (domain)-data access object. Used to get Principals and Credentials. For example: user name and password are stored in .ini file, user name and password can be obtained through IniRealm, user name and password can be stored in database, user name and password can be obtained through JdbcRealm, and so on.

AuthenticationToken (authentication token)-A user identity token that can be obtained by combining Principals (identity) and Credentials (credentials).

Authenticator-an account that verifies that the user verifies that the token meets the requirements.

AuthenticationStrategy (authentication policy)-indicates which policy is used to authenticate the user.

The following is the verification architecture diagram obtained from the official website:

Step 1: collect the Principals and Credentials submitted by the topic to get the Token, and the application code calls the Subject.login method, passing in the Token for authentication.

Step 2:Subject instance, usually DelegatingSubject (or subclass), delegates the actual authentication work to SecurityManager by calling securityManager.login (token)

Step 3:SecurityManager, as the basic component, receives the Token and then delegates it to Authenticator by calling authenticate (token). Authenticator is almost always an instance ModularRealmAuthenticator, which supports the coordination of one or more Realm instances during authentication.

Step 4: if more than one Realm is configured for the application, the ModularRealmAuthenticator instance will use its configured AuthenticationStrategy to initiate a multirealm authentication attempt. Before, during, or after a call to Realms for authentication, AuthenticationStrategy is called to allow it to react to the results of each Realm.

Step 5: each realm will be consulted to see if the submitted AuthenticationToken is supported. If so, the getauthenticationfo method of realm is called with the submitted Token. The getauthenticationfo method effectively represents a single authentication attempt in that particular domain.

Then you start to use ShiroAPI to complete the validation operation.

Environmental preparation:

This article is built using Maven, so you need a little knowledge of Maven. First of all, prepare the environment dependency:

Junit junit 4.9 test commons-logging commons-logging 1.2 org.apache.shiro shiro-core 1.3.2

Just add junit and shiro-core dependencies.

First acquaintance: login / logout

1. First prepare some user identities / credentials (shiro.ini)

[users] zhangsan=123lisi=123

2. Test case (com.luther.shiro.authenticator.AuthenticateTest)

/ * * the underlying layer uses ModularRealmAuthenticator authentication module (multi-realm authentication) * AtLeastOneSuccessfulStrategy authentication policy by default (as long as one domain is successfully authenticated, * is considered successful. Or fail. All successful user identities will be returned) * @ author luther * @ time 9:58:39 on July 5, 2019 * / @ Testpublic void testHelloWorld () {/ / initialize SecurityManagerFactory factory = new IniSecurityManagerFactory ("classpath:shiro.ini") with the Ini configuration file; / / get the SecurityManager instance and bind to SecurityUtils SecurityManager securityManager = factory.getInstance (); SecurityUtils.setSecurityManager (securityManager) / / get Subject and create user name / password authentication Token (i.e. user identity / credential) Subject subject = SecurityUtils.getSubject (); UsernamePasswordToken token = new UsernamePasswordToken ("zhangsan", "123"); / / remember user token.setRememberMe (Boolean.TRUE) Try {/ / login subject.login (token); System.out.println ("login success");} catch (AuthenticationException e) {System.err.println ("login failed, reason for failure:"); e.printStackTrace () } assertTrue ("user verified successfully", subject.isAuthenticated ()); / / exit subject.logout ();}

Realm

The structure of the realm API is as follows, and the following methods are:

String getName (); / / returns a unique Realm name boolean supports (AuthenticationToken token); / / determines whether the Realm supports this TokenAuthenticationInfo getAuthenticationInfo (AuthenticationToken token) throws AuthenticationException; / / obtains authentication information according to Token

The main default implementations are as follows:

Org.apache.shiro.realm.text.IniRealm: get information such as user rights from the ini file.

Org.apache.shiro.realm.text.PropertiesRealm: get information such as user rights from the properties file.

Org.apache.shiro.realm.jdbc.JdbcRealm: get information such as user permissions from the database.

Later developers generally inherit the AuthorizingRealm (authorization) abstract class; it inherits AuthenticatingRealm (that is, authentication) and indirectly inherits CachingRealm (with caching implementation).

1. Single Realm configuration

1. Custom Realm implementation (com.luther.shiro.realm.MyRealm1):

Public class MyRealm1 implements Realm {@ Override public String getName () {return this.getClass () .getName ();} @ Override public boolean supports (AuthenticationToken token) {/ / only UsernamePasswordToken return token instanceof UsernamePasswordToken;} @ Override public AuthenticationInfo getAuthenticationInfo (AuthenticationToken token) throws AuthenticationException {UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token / / get the user name String username = usernamePasswordToken.getUsername (); / / get the password String password = new String (usernamePasswordToken.getPassword ()) / / account name error if (! "zhangsan" .equals (username)) {throw new UnknownAccountException ();} / password error if (! "123" .equals (password)) {throw new IncorrectCredentialsException () } System.out.println ("user" + username + "Verification successful"); / / return return new SimpleAccount (username, password, getName ());}}

2. The ini configuration file specifies a custom Realm implementation (shiro-realm.ini)

[main] # declares a realms implementation of realmmyRealm1=com.luther.shiro.realm.MyRealm1# specified securityManager, introducing the previous realm definition securityManager.realms=$myRealm1 through $name

3. For test cases, please refer to com.luther.shiro.authenticator.AuthenticateTest 's testSingleRealm test method, which is no different from testHelloWorld except for configuration files.

2. Multi-Realm configuration

1. Ini configuration file (shiro-multi-realm.ini)

[main] # declares a realmmyRealm1=com.luther.shiro.realm.MyRealm1# that declares a realms implementation of a realmmyRealm2=com.luther.shiro.realm.MyRealm2# specified securityManager, introducing the previous realm definition securityManager.realms=$myRealm2,$myRealm1# through $name, which in this example clearly specifies the order as myRealm2,myRealm1. (you can specify less, for example, if you specify only myRealm2, myRealm1 will be ignored) # if you do not specify securityManager.realms, it will be in the order of the declaration of realm (no need to set the realms attribute, which will be automatically discovered). Here is myRealm1,myRealm2.

2. For test cases, please refer to com.luther.shiro.authenticator.AuthenticateTest 's testMutiRealm test method.

Authenticator and AuthenticationStrategy

I. brief introduction of Authenticator and AuthenticationStrategy

Authenticator is responsible for verifying user accounts and is the entry point for the authentication core in Shiro API (the default implementation is ModularRealmAuthenticator). Its methods are defined as follows:

Public AuthenticationInfo authenticate (AuthenticationToken authenticationToken) throws AuthenticationException

If the authentication is successful, the AuthenticationInfo authentication information is returned; this information contains the identity and credentials; if the authentication fails, the corresponding AuthenticationException implementation is thrown.

AuthenticationStrategy is the verification policy used by Authenticator for verification (the default implementation is: AtLeastOneSuccessfulStrategy). Shiro API comes with the following three policies:

FirstSuccessfulStrategy: as long as one Realm authentication is successful, only the authentication information of the first Realm authentication is returned, and the rest is ignored.

AtLeastOneSuccessfulStrategy: as long as one Realm authentication is successful, unlike FirstSuccessfulStrategy, it returns all the authentication information of successful Realm authentication.

AllSuccessfulStrategy: all Realm authentication is considered successful, and all Realm authentication successful authentication information is returned. If there is one failure, it fails.

II. Authenticator and AuthenticationStrategy demonstration

Suppose we have three realm:

MyRealm1: successful if the username / password is zhangsan/123, and the identity / credential returned is zhangsan/123

MyRealm2: successful if the username / password is lisi/123, and the identity / credential returned is lisi/123

MyRealm3: successful if the username / password is zhangsan/123, and the identity / credential returned is zhangsan.qq/123

1. General login logic

Private void authentition (String iniConfigPath, String username, String password) {/ / initialize SecurityManagerFactory factory = new IniSecurityManagerFactory (iniConfigPath) with the Ini configuration file; / / get the SecurityManager instance and bind it to SecurityUtils SecurityManager securityManager = factory.getInstance (); SecurityUtils.setSecurityManager (securityManager) / / get Subject and create user name / password authentication Token (i.e. user identity / credential) Subject subject = SecurityUtils.getSubject (); UsernamePasswordToken token = new UsernamePasswordToken (username, password); / / remember user token.setRememberMe (Boolean.TRUE); try {/ / login subject.login (token) System.out.println ("user zhangsan login succeeded and its identity is" + subject.getPrincipals ());} catch (AuthenticationException e) {System.err.println ("login failed, failure reason:"); e.printStackTrace ();} assertTrue ("user authenticated successfully", subject.isAuthenticated ()) / / exit subject.logout ();}

2. Test AtLeastOneSuccessfulStrategy

2.1 ini profile (shiro-firstSuccessfulStrategy.ini)

[main] # specify the authenticator implementation of securityManager, which may not be specified, because the default implementation is the authenticationStrategy of ModularRealmAuthenticator#authenticator=org.apache.shiro.authc.pam.ModularRealmAuthenticator#securityManager.authenticator=$authenticator# specifying securityManager.authenticator, and may not be specified Because its default implementation is that AtLeastOneSuccessfulStrategy#authenticationStrategy=org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy#securityManager.authenticator.authenticationStrategy=$authenticationStrategy# declares a realmmyRealm1=com.luther.shiro.realm.MyRealm1# declaration, a realmmyRealm2=com.luther.shiro.realm.MyRealm2# declares a realms implementation of a realmmyRealm3=com.luther.shiro.realm.MyRealm3# specified securityManager, and introduces the previous realm definition securityManager.realms=$myRealm3,$myRealm2,$myRealm1 through $name

2.2 Test code

/ * * demonstrate the effectiveness of AtLeastOneSuccessfulStrategy * each realm will verify and return all successful user identities * @ author luther * @ time 11:30:24 on July 5, 2019 * / @ Testpublic void testAtLeastOneSuccessfulStrategy () {authentition ("classpath:shiro-atLeastOneSuccessfulStrategy.ini", "zhangsan", "123");}

2.3 Test results

Start authentication com.luther.shiro.realm.MyRealm3com.luther.shiro.realm.MyRealm3-user zhangsan authentication success start authentication com.luther.shiro.realm.MyRealm2 start authentication com.luther.shiro.realm.MyRealm1com.luther.shiro.realm.MyRealm1-user zhangsan authentication successful user zhangsan login successful, his identity is zhangsan.qq,zhangsan

That is, PrincipalCollection contains zhangsan and zhangsan.qq identity information.

3. Test AllSuccessfulStrategy

3.1 ini profile (shiro-allSuccessfulStrategy.ini)

[main] # specify the authenticator implementation of securityManager, which may not be specified Because its default implementation is that ModularRealmAuthenticator#authenticator=org.apache.shiro.authc.pam.ModularRealmAuthenticator#securityManager.authenticator=$authenticator# specifies the authenticationStrategy of securityManager.authenticator to declare a realmmyRealm1=com.luther.shiro.realm.MyRealm1# for AllSuccessfulStrategyauthenticationStrategy=org.apache.shiro.authc.pam.AllSuccessfulStrategysecurityManager.authenticator.authenticationStrategy=$authenticationStrategy#, a realmmyRealm2=com.luther.shiro.realm.MyRealm2# to declare a realms implementation of realmmyRealm3=com.luther.shiro.realm.MyRealm3# to specify securityManager, and to introduce the previous realm definition securityManager.realms=$myRealm3,$myRealm2,$myRealm1 through $name

3.2 Test code

/ * * demonstrate the effect of AllSuccessfulStrategy * verify each realm in turn. If the verification fails, the reason for the failure will be returned directly, and all user identities will be returned only if all of them are successful * each realm will be verified. And return all successful user IDs * @ author luther * @ time 11:30:24 * / @ Testpublic void testAllSuccessfulStrategy () {authentition ("classpath:shiro-allSuccessfulStrategy.ini", "zhangsan", "123") }

3.3 Test results

Start authentication com.luther.shiro.realm.MyRealm3com.luther.shiro.realm.MyRealm3-user zhangsan authentication success start authentication com.luther.shiro.realm.MyRealm2 login failed, failure: org.apache.shiro.authc.UnknownAccountException at com.luther.shiro.realm.MyRealm2.getAuthenticationInfo (MyRealm2.java:42)

4. Test firstSuccessfulStrategy

4.1 ini profile (shiro-firstSuccessfulStrategy.ini)

[main] # specify the authenticator implementation of securityManager, which may not be specified Because its default implementation is that ModularRealmAuthenticator#authenticator=org.apache.shiro.authc.pam.ModularRealmAuthenticator#securityManager.authenticator=$authenticator# specifies the authenticationStrategy of securityManager.authenticator to declare a realmmyRealm1=com.luther.shiro.realm.MyRealm1# for FirstSuccessfulStrategyauthenticationStrategy=org.apache.shiro.authc.pam.FirstSuccessfulStrategysecurityManager.authenticator.authenticationStrategy=$authenticationStrategy#, a realmmyRealm2=com.luther.shiro.realm.MyRealm2# to declare a realms implementation of realmmyRealm3=com.luther.shiro.realm.MyRealm3# to specify securityManager, and to introduce the previous realm definition securityManager.realms=$myRealm3,$myRealm2,$myRealm1 through $name

4.2 Test code

/ * demonstrate the effect of FirstSuccessfulStrategy * each realm will be validated. After all verification, the first user ID of successful verification will be returned (note here, not immediately after verification. Instead, verify all and return) * @ author luther * @ time 11:30:24 on July 5, 2019 * / @ Testpublic void testFirstSuccessfulStrategy () {authentition ("classpath:shiro-firstSuccessfulStrategy.ini", "zhangsan", "123") }

4.3 Test results

Start authentication com.luther.shiro.realm.MyRealm3com.luther.shiro.realm.MyRealm3-user zhangsan authentication success start authentication com.luther.shiro.realm.MyRealm2 start authentication com.luther.shiro.realm.MyRealm1com.luther.shiro.realm.MyRealm1-user zhangsan authentication successful user zhangsan login successful, his identity is zhangsan.qq

The authentication policy that comes with API has been demonstrated above, and the custom authentication policy is shown below.

Before customizing the AuthenticationStrategy implementation, first take a brief look at its API:

/ / call AuthenticationInfo beforeAllAttempts (Collection) before all Realm verification

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report