In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
Today, the editor will share with you the relevant knowledge of what the Spring Security authentication method is, the content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article.
Preface
This article takes user name / password authentication as an example to explain the authentication process of Spring Security. Before that, you need to understand the basic configuration of Spring Security user name / password authentication.
Spring Security is filter-based, through a layer-by-layer filter to handle the authentication process and intercept illegal requests.
Persistence of authentication context
The first filter, called SecurityContextPersistenceFilter,Spring Security, stores authentication information through Session. The doFilter method of this filter is executed only once in each request. The purpose of this filter is to put the SecurityContext in Session into the thread of the current request (if any) at the time of request, and check whether there is SecurityContext in the county when responding, and if so, put it into Session. It can be understood as Session-wide persistence of SecurityContext.
Encapsulation of authentication information
Then go to UsernamePasswordAuthenticationFilter, which is one of the protagonists in the user name / password authentication process.
By default, this filter matches POST requests with the path / login, which is the request path for Spring Security's default username and password login.
The most critical code here is the attemptAuthentication method (called by the doFilter method). The source code is as follows:
@ Overridepublic Authentication attemptAuthentication (HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {if (this.postOnly & &! request.getMethod () .equals ("POST")) {throw new AuthenticationServiceException ("Authentication method not supported:" + request.getMethod ());} String username = obtainUsername (request); username = (username! = null)? Username: ""; username = username.trim (); String password = obtainPassword (request); password = (password! = null)? Password: ""; UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken (username, password); / / Allow subclasses to set the "details" property setDetails (request, authRequest); return this.getAuthenticationManager () .authenticate (authRequest);}
In line 12 of the attemptAuthentication method code, we build a UsernamePasswordAuthenticationToken object using the user name and password obtained from request. We can see the code for this constructor, which is very simple:
Public UsernamePasswordAuthenticationToken (Object principal, Object credentials) {super ((Collection) null); this.principal = principal; this.credentials = credentials; this.setAuthenticated (false);}
Only a reference to the user name and password is saved, and the authentication status is set to false, because the authentication information is only encapsulated and has not been authenticated yet.
Let's go back to the attemptAuthentication code and pass the created authentication information to an AuthenticationManager for authentication on the last line of the method. What is actually working here is the implementation class ProviderManager of AuthenticationManager.
Find the Provider class that handles authentication
Enter ProviderManager can find the authenticate method from the source code, the code is relatively long, I will not post here, you can find it yourself, I briefly describe the logic in the code.
ProviderManager itself does not perform authentication operations, it manages an AuthenticationProvider list, when it needs to authenticate a packaged authentication information, it will match the authentication information with its managers' Provider one by one to find the appropriate Provider to deal with the specific work of authentication.
It can be understood that ProviderManager is a manager who manages a variety of Provider. When there is work to be done, it never does it itself, but assigns different tasks to different Provider to do.
Finally, it returns the Provider's work (certified success information) or throws an exception.
So, how does it give an authentication information to the appropriate Provider?
In the previous section, we said that the authentication information is encapsulated into a UsernamePasswordAuthenticationToken, which is a subclass of Authentication. ProviderManager will pass the type of authentication information to the supports method of each Provider, and the Provider will tell ProviderManager whether it supports this type of authentication information.
Authentication logic
In Spring Security's built-in Provider, the Provider corresponding to UsernamePasswordAuthenticationToken is the DaoAuthenticationProvider,authenticate method in its parent class, AbstractUserDetailsAuthenticationProvider. Let's take a look at its authenticate method:
Overridepublic Authentication authenticate (Authentication authentication) throws AuthenticationException {Assert.isInstanceOf (UsernamePasswordAuthenticationToken.class, authentication, ()-> this.messages.getMessage ("AbstractUserDetailsAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported")); String username = determineUsername (authentication); boolean cacheWasUsed = true; UserDetails user = this.userCache.getUserFromCache (username); if (user = = null) {cacheWasUsed = false; try {user = retrieveUser (username, (UsernamePasswordAuthenticationToken) authentication) } catch (UsernameNotFoundException ex) {this.logger.debug ("Failed to find user'" + username + "'"); if (! this.hideUserNotFoundExceptions) {throw ex;} throw new BadCredentialsException (this.messages .getMessage ("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));} Assert.notNull (user, "retrieveUser returned null-a violation of the interface contract") } try {this.preAuthenticationChecks.check (user); additionalAuthenticationChecks (user, (UsernamePasswordAuthenticationToken) authentication);} catch (AuthenticationException ex) {if (! cacheWasUsed) {throw ex;} / / There was a problem, so try again after checking / / we're using latest data (i.e. Not from the cache) cacheWasUsed = false; user = retrieveUser (username, (UsernamePasswordAuthenticationToken) authentication); this.preAuthenticationChecks.check (user) AdditionalAuthenticationChecks (user, (UsernamePasswordAuthenticationToken) authentication);} this.postAuthenticationChecks.check (user); if (! cacheWasUsed) {this.userCache.putUserInCache (user);} Object principalToReturn = user; if (this.forcePrincipalAsString) {principalToReturn = user.getUsername ();} return createSuccessAuthentication (principalToReturn, authentication, user);}
The code is long, so let's say the main points:
Line 12 of the code, through the retrieveUser method to obtain UserDetails information, the specific implementation of this method can be found in DaoAuthenticationProvider, mainly through the loadUserByUsername method of UserDetailsService to find the user information in the system.
Line 25 of the code, through the preAuthenticationChecks.check method, makes some checks before authentication. The specific implementation of the verification can be found in the DefaultPreAuthenticationChecks internal class, mainly to determine whether the user is locked, available, and expired.
Line 26 of the code verifies the user name and password through the additionalAuthenticationChecks method. The implementation can be found in DaoAuthenticationProvider.
Line 39 of the code verifies that the password has expired through the postAuthenticationChecks.check method. The implementation can be found in the DefaultPostAuthenticationChecks inner class.
Finally, if there is no problem with the above checksum authentication, the successful authentication information is created through the createSuccessAuthentication method and returned. At this point, the authentication was successfully passed.
In the final createSuccessAuthentication method, a new UsernamePasswordAuthenticationToken authentication information is created with the authentication status of true. Indicates that this is a certificate that has been passed.
This authentication information is returned to UsernamePasswordAuthenticationFilter as a result of the attemptAuthentication method.
In the doFilter method, according to the result of successful or failed authentication, the corresponding Handler class is called for subsequent processing. Finally, the authentication information is also saved in SecurityContext for subsequent use.
These are all the contents of this article entitled "what is the method of Spring Security Certification?" Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.