Authentication of Shiro combat series (V)

It is recommended to learn Shiro to read the official documents. Although you may not understand it, it is recommended to browse roughly and have a general idea in mind. This is still helpful for learning

Official website address: https://shiro.apache.org/

Authentication refers to the process of authentication -- that is, proving whether a user is actually who they say they are. For a user to prove their identity, they need to provide some identification information and some identification that your system can understand and trust.

This is by submitting the user's identity and credentials to Shiro to determine whether they match what the application expects.

Principals (identity)

Principles is the 'identifying attributes' of the subject. Principals can be anything that can prove the subject, such as first name, last name, user name, Social insurance ID number (equivalent to our ID card number) and so on. Of course, surnames like this are not very good for identifying Subject, so the best Principals for identity authentication is the one and only application name for an application, usually user name or e-mail address.

Primary principal

Although Shiro can represent any number of principals, Shiro expects the application to have an exact 'primary' Principal -- a single value that uniquely identifies the subject within the application. This is usually a user name, email address, or globally unique user ID in most applications.

Credentials

It is usually a secret value known only by the subject. It is used as a supporting evidence. In fact, this evidence contains the so-called identity certificate. Some examples of common credentials are passwords, biometric data such as fingerprints and retinal scans, and X.509 certificates.

The most common examples of principal / credential pairing are user names and passwords. The user name is the claimed identity and the password is proof of matching the claimed identity. If the submitted password matches what the application expects, the application can largely assume that the user is really who they say they are, because others should not know the same password.

Authenticating subjects:

The process of verifying subjects can be effectively broken down into three different steps:

1. Collect principals and credentials submitted by subjects;

2. Submit principals and credentials for authentication;

3. If the submission is successful, access is allowed. Otherwise, re authenticate or block access.

Step 1: collect subject's principals and credentials

In this special case, we use usernamepasswordtoken to support the most common user name / password authentication method. This is Shiro's org apache. shiro. authc. The interface of authenticationtoken is an implementation of the basic interface used by Shiro's authentication system on behalf of the submitted principals and credentials. It's important to note that Shiro doesn't care how you get this information: perhaps the obtained data is an HTML form submitted by the user, or captured from the HTTP header, or it is from a swing or flex GUI password form, or through command-line parameters. The process of collecting information from end users is not linked to Shiro's authentication token concept. You can create and instantiate your favorite authentication token instance - it is protocol independent. This example also shows that we want Shiro to execute the "remember me" service for authentication attempts. This will ensure that Shiro can remember the user's identity in the future if the user returns to the application. We will discuss the member me service in later chapters.

Step 2: submit the principals and credentials of the subject

After the principals and credentials are collected and instantiated as an authenticationtoken instance, we need to submit this token to Shiro to perform a real authentication attempt:

After capturing the currently executing subject, we obtain a single login method call and pass the previously obtained authenticationtoken instance to it. By calling the login method, the authentication attempt is effectively reflected.

Step 3: handle success or failure. If the login method returns calmly, it's it - everything we've done! The subject has passed validation. The application thread can continue undisturbed, and all further security utils The call to getsubject () will return the authenticated subject instance, and any call to subject The call to isauthenticated() will return true. But what happens if the login attempt fails? For example, if end users provide incorrect passwords, or access the system too many times, or their accounts are locked? Shiro has a rich runtime authenticationexception hierarchy that can indicate the exact reason why the attempt failed. You can surround the login method with a try / catch block, then catch any exception you want and react accordingly. For example:

If the existing exception class does not meet your requirements, you can customize authenticationexceptions to represent specific exceptions.

Login Failure Tip

Although your code can respond to specific exceptions and execute the necessary logic, the safest way is to display only general failure messages to end users, such as "wrong user name or password.". This will ensure that specific information is provided to the media that hackers may attempt to attack.

Remembered vs. authenticated

As shown in the above example, Shiro supports all the "remember me" concepts except the normal login process. At this time, it is worth pointing out that Shiro makes a precise distinction between remembering my subject and the verified subject:  remembered:

Remember that my subject is not anonymous and has a known identity ID (that is, subject. Getprincipals () is non empty). However, the remembered identity ID is authenticated in the previous session. If subject If isremembed() returns true, the subject is considered to be remembered.  authenticated:

An authenticated subject means that it has been successfully verified in the current session (that is, the login method is called and no exception is thrown). If subject. Isauthenticated() returns true, it is considered that the subject has passed the verification.

Mutually exclusive: remembered and authenticated are mutually exclusive -- if one is true, the other is false, and vice versa.

Why is there such a difference?

The word "authentication" has a strong meaning of proof. That is, there is an expectation that subjects have proved who they are. When the user only remembers the previous interaction with the application, the authentication will no longer exist: the remembered identity ID makes the system understand who the user may be, but in reality, there is no way to absolutely ensure that the remembered subject represents the expected user. Once the subjects pass the verification, they will no longer be considered only to be remembered, because their identity has been confirmed in the current session. Although many parts of the application can still perform user specific logic based on the remembered identity ID, such as custom view, it should never perform highly sensitive operations unless the user legally verifies his identity by performing a successful authentication attempt. For example, a check to determine that a subject can access financial information should almost always depend on isauthenticated () rather than isremembed () to ensure an expected and verified identity.

As an illustrative example, the following is a fairly common case:

It helps to illustrate the importance of the difference between remembered and authenticated. For example, you are visiting Amazon com。 You have successfully logged in and added several books to your shopping cart. But you ran out of the meeting distracted and forgot to sign out. After the meeting, it was time to go home, so you left the office. When you work the next day, you realize that you haven't finished your purchase, so you go back to Amazon com。 This time, Amazon "remembers" who you are, gives your welcome page, and still provides you with some personalized suggestions. For Amazon, subject Isremembed() will return true. But what happens when you try to access your account to update your credit card information and pay for your books? Although Amazon "remembers" you (isremembed() = = true), it cannot guarantee that you are actually you (for example, maybe a colleague is using your computer).

So before you can perform sensitive actions such as updating credit card information, Amazon will force you to log in so that they can guarantee your identity. After logging in, your identity has been verified, and for Amazon, isauthenticated () now returns true. This happens so frequently in many types of applications, so these functions are built into Shiro so that you can use it to serve your application. Now, whether you use isremembed () or isauthenticated () to customize your view and workflow is up to you, but Shiro will maintain this basic situation in case you need it.

cancellation:

The opposite of authentication is to release all known identification states. When the subject has finished interacting with the application, you can call subject Logout() to release all identification information:

When you call logout, any existing session will be invalidated and any identity will be lost (for example, in a web application, the rememberme cookie will also be deleted). After the subject logs off, the instance of the subject is considered anonymous again. Of course, in addition to the web application, it can also be reused for login if necessary.

The web application notice often relies on cookies to remember the identity in the web application. However, cookies can only be deleted before the response is committed, so it is strongly recommended to call subject Logout () immediately redirects the end user to a new view or page. This ensures that any security related cookies can be deleted as expected. This is a functional limitation of HTTP cookies, not Shiro's.

Verification sequence

So far, we have only learned how to validate a subject from the application code. Now we'll talk about what happens inside Shiro when an authentication attempt occurs. We adopted the architecture diagram of the architecture chapter and only highlighted the components related to authentication. Each number represents a step in the authentication attempt:

Step 1: the application code calls subject The login method passes the created authenticationtoken instance containing the end user's principals and credentials.

Step 2: the subject instance, usually delegatingsubject (or subclass), delegates the securitymanager of the application to start the real verification by calling securitymanager.login (token).

Step 3: as part of a basic "umbrella", the subjectmanager receives tokens and simply delegates them to an internal authenticator instance by calling authenticator authenticate(token)。 This is usually a modularrealmauthenticator instance that supports coordinating one or more realm instances in authentication. Modularrealmauthenticator essentially provides Apache Shiro with a PAM style paradigm (where each realm is a 'module' in PAM terminology).

Step 4: if more than one realm is configured in the application, the modularrealmauthenticator instance will use the configured authenticationstrategy to start the multi realm authentication attempt. Before, during, and after realms are invoked by authentication, the authenticationstrategy is invoked to enable it to respond to the results of each realm. We'll get to authentication strategies soon.

Single realm application if only a single realm is configured, it will be called directly - there is no need to use authentication strategy for a single realm application.

Step 5: each configured realm is used to help see whether it supports the submitted authenticationtoken. If yes, the getauthenticationinfo method that supports real will be called along with the submitted token. The getauthenticationinfo method effectively represents a single authentication attempt for a particular realm. We will cover the real validation behavior shortly.

Authenticator as mentioned earlier, the implementation of Shiro securitymanager uses a modularrealmauthenticator instance by default. Modularrealmauthenticator also supports single realms and applications with multiple realms. In a single realm application, the modularrealmauthenticator will directly call the single realm. If there are two or more realm configurations, it will use the authenticationstrategy instance to adjust how these attempts occur. Next, we will introduce authentication strategies. If you want to configure the securitymanager to be implemented through a custom authenticator, you can Ini, for example:

Although in practice, modular realauthenticator is likely to be suitable for most needs.

Authentication strategy when an application is configured with two or more realms, the modularrealmauthenticator relies on the internal authentication strategy component to determine the success or failure conditions of these authentication attempts.

For example, if only one realm validates one authenticationtoken successfully, but all others fail, is this considered a successful authentication attempt? Or must all realms be verified successfully to be considered successful? Or, if one realm is verified successfully, is it necessary to further consult other realms? Authentication strategy makes appropriate decisions based on program needs. Authenticationstrategy is a stateless component. It is queried four times in authentication attempts (any necessary state required for these four interactions will be used as a method parameter):

1. Being asked before any realm is called;

2. Be queried immediately before the getauthenticationinfo method of a separate real is called;

3. Be queried immediately after the getauthenticationinfo method of a separate real is called;

4. Ask after all realms are called.

In addition, the authentication strategy is responsible for summarizing the results from each successful realm and "binding" them to a single authentication info. The last summarized authenticationinfo instance is the value returned from the authenticator instance and the value used by Shiro to represent the final identity ID of the subject (i.e. principals).

Subject identity 'view' if you use multiple realms in your application to obtain account information from multiple data sources, the authenticationstrategy is the person in charge of the final view of "merging" the identity of the subject that can be understood by the application

Shiro has three specific implementations of authenticationstrategy:

The default implementation of modularrealmauthenticator is atleastonesuccessful strategy, because this is the most frequently required solution. However, if you like, you can configure a different scheme:

Verification sequence of realm

It is important to point out that the modularrealmauthenticator will interact with the real instance in an iterative order. The access of modularrealmauthenticator to the realm instance has been configured in the securitymanager. When an authentication attempt is executed, it will traverse the collection and call the getauthenticationinfo method of real for each real that supports submitting an authenticationtoken.

Implicit ordering

When using Shiro's ini configuration file format, you should configure the order in which realm processes authenticationtokens, the order you want. For example, in Shiro In ini, realms will be requested in the order they are defined in the INI file. That is, for the following Shiro Ini example:

Explicit real inclusion when you explicitly configure securitymanager The properties of realms are that only the referenced realms will be configured in the securitymanager. This means that you can define five realms in the INI file, but you can only use three if only these three are referenced to the property of the realm This is different from the order of implicit realms. All available implicit realms will be used.

This chapter covers Shiro's main workflow and explains how an authentication attempt is generated. Internal workflow refers to what happens when a single realm is accessed during the verification process (that is, above 'step 5'), which has been included in the realm authentication part of the realm

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>