preface

In combination with the AuthenticationManager as the core module for authenticating entries that we introduced in the previous installment, this time we are talking about enabling SpringSecurity to support Spring Web projects as an authentication request entry.

Issue 3 Introduction to Authentication Core

This issue’s to-do list

  1. AbstractAuthenticationProcessingFilter dependent components;
  2. AbstractAuthenticationProcessingFilter depend on the component’s main duties and related design motives.

1. AbstractAuthenticationProcessingFilter processing Request and with the AuthenticationManager interaction process

AbstractAuthenticationProcessingFilter and rely on the primary responsibility of the component

Understand AbstractAuthenticationProcessingFilter is probably why the simplest method is to directly read the API doc.

Abstract processor of browser-based HTTP-based authentication requests.

The official documentation is clear: handle HTTP authentication requests based on browser interactions. So AbstractAuthenticationProcessingFilter responsibility is very clear – to handle all HTTP Request and Response objects, And encapsulate it as Authentication that AuthenticationMananger can handle. And translates the corresponding behavior into an HTTP Response after authentication succeeds or fails. It also deals with Web-specific resources such as sessions and cookies. In short, it covers all the AuthenticationMananger stuff that has nothing to do with Authentication.

Continue to read the JavaDoc that AbstractAuthenticationProcessingFilter metasomatism in order to complete the organization and the browser and HTTP request verification tasks. It breaks a large task into several sub-tasks and assigns them to the following components:

  1. AuthenticationManager is used to handle the core logic of authentication;
  2. AuthenticationSuccessHandler handles validation successful subsequent processes;
  3. AuthenticationFailureHandler follow-up processes for dealing with failure;
  4. Released after successful authentication, a InteractiveAuthenticationSuccessEvent event notification to the application context, is used to inform the authentication has been successfully;
  5. Because is based on the browser session management behavior of related to the SessionAuthenticationStrategy to implement.
  6. And there is no written document, if the user opens the similar “remember me” no password, AbstractAuthenticationProcessingFilter another called RememberMeServices for management.

AbstractAuthenticationProcessingFilter validation process

AbstractAuthenticationProcessingFilter essentially as a Filter, its core business entry method is the doFilter method:

  1. How do I determine if the current request needs to be authenticated?
  2. How do I authenticate?
  3. How do I perform session authentication? What is the motivation?
  4. What are the follow-up processes for success and failure?
  5. What is the implementation process of remember-Me function?
  6. How do I listen for successful validation events in other services?

Question 1. How do I determine whether the current request needs to be authenticated?

DoFilter is passed through Security before formal identification. Try to find if there is a match. Let’s review the access control code we wrote earlier:

@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() // The corresponding URL of inde.html allows the assigned person to access.antmatchers ("/".antmatchers ().permitall () // user.html"/user").hasRole("USER")
                .and()
                .formLogin();
    }
Copy the code

Matcher’s rules are pre-checked in the process and write a phase if authentication is required: the request is authenticated as necessary.

Question 2. How do I authenticate?

DoFilter calls its own attemptAuthentication method, but does not perform the logical processing of the authentication, instead delegating the AuthenticationManager to complete the related authentication process. AbstractAuthenticationProcessingFilter to pack it into Authentication object and the core of the AuthenticationManager to interact. Such a design can make AuthenticationManager unaware of the external Web environment, so that Security can support not only Web applications, It can also be used by all Java applications — as long as you customize external participation and encapsulate it as Authentication and AuthenticationManager.

It is also important to note here that the actual authentication task in the AuthenticationManager is not performed by the AuthenticationManager itself. Instead, the relevant tasks for each authentication protocol of the AuthenticationProvider to complete the relevant authentication work.

Question 3. How do I manage session authentication? What is the motivation?

First concept session validationA concept of what? We know that HTTP requests are stateless in fact. In order to enable the same session operation between HTTP requests, browsers usually write the JSESSIONID of the Web container (especially Tomcat) into the cookie of the request and send it together in Java Web.

Security also provides implementations for different session management policy scenarios, so there is an opportunity to write a separate article on related policies. Just so you know, after AuthenticationManager is authenticated, it also performs the necessary session authentication.

Q4. What is the follow-up process of success and failure?

After successful Authentication, the AuthenticationManager returns an Authentication object constructed from UserDetail with all the authorization information attached. If the validation fails, it will be thrownValidated, AbstractAuthenticationProcessingFilter after catch exceptions for failure. One of the most important successful subsequent operations is to insert the authenticated Authentication object into the current SecurityContext via SecurityContextHolder. If you need to use the Authentication identity information in subsequent operations, you can directly obtain it through the SecurityContextHolder.

. / / after a successful set context two SecurityContextHolder getContext () setAuthentication (authResult); / / the following operation can be obtained from the context identity information SecurityContextHolder. GetContext (). GetAuthentication ();Copy the code

Which is then sent via ApplicationEventPublisher verify the success of the event information for other relevant listener related operations.

Failure is simple. Since success is to re-insert the latest Authentication object into the SecurityContext, failure is to simply empty the context, leaving its Authentication object “empty”.

Other additional operations on the request can pass separatelywithTwo interfaces to set up related operations.

Q.5. What is the implementation process of remember-me function?

Remember-Me means that the website can Remember the identity of the login user during the Session. Specifically, after I successfully authenticate once, I can log in without entering the user name and password for a certain period of time, and the system will automatically log in for Me. Usually, the server sends a cookie to the client browser. When the browser accesses the server again, the server automatically detects the cookie and triggers automatic login based on the cookie value. There are many ways to achieve this. Generally speaking, the simplest implementation is to encode the user name and some other characters, and then extract the relevant user name after decoding by the server, and obtain the user authentication mode of relevant user information through the UserDetailsService. Spring Security offers two Remember – Me mechanism is used, if there is other way also can be extended through inheritance AbstractRememberMeServices class. Keep in mind that the reality of the remember-me mechanism is Cookie dependent, and by default SpringSecurity stores the encoded string in the remember-me key in the Cookie.

# Q6. How do I listen for successful validation events in other services

After complete the verification process, AbstractAuthenticationProcessingFilter will through the Spring containerThe event publisher fires one. If you need to handle relevant validation on other listeners successfully. We can through the Spring of @ EventListener to monitor InteractiveAuthenticationSuccessEvent events can achieve. Write an example if we want to print out the user name of the logged-in user on the console after each user logs in successfully.

@Component public class AuthenticationListener { @EventListener public void The register (InteractiveAuthenticationSuccessEvent event) {/ / get the login successful Authentication object Authentication Authentication = event.getAuthentication(); // Print the user name system.out.println ("@eventListener Registration information, username:"+authentication.getName()); }}Copy the code

At the end

Spent a lot of space in current introduced the whole Web AbstractAuthenticationProcessingFilter core components of the validation process. The next issue we will combine the most commonly used implementation class UsernamePasswordAuthenticationFilter do a lecture, Hope by explaining UsernamePasswordAuthenticationFilter make everyone understand the customization details need to be aware of a verification protocol. I’ll see you next time.