In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "Spring Security how to achieve login authentication", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Spring Security how to achieve login authentication" bar!
I. theoretical knowledge
Let's think about what the process is like.
Fill in the email number and get the CAPTCHA
Enter the obtained CAPTCHA to log in (login API: / email/login, the default / login cannot be used here because we are an extension)
Obtain the email number and verification code sent in the custom filter EmailCodeAuthenticationFilter to determine whether the verification code is correct, whether the mail account is empty, etc.
Encapsulate it into an Authentication that needs authentication, and here we customize the implementation as EmailCodeAuthenticationToken.
Transfer Authentiction to authenticate method in AuthenticationManager interface for authentication processing
AuthenticationManager defaults to the implementation class ProviderManager, and ProviderManager entrusts AuthenticationProvider to handle it.
We customize an EmailCodeAuthenticationProvider implementation AuthenticationProvider to implement authentication.
The custom EmailCodeAuthenticationFilter inherits the AbstractAuthenticationProcessingFilter abstract class, AbstractAuthenticationProcessingFilter handles the login success in the successfulAuthentication method, and binds the Authentication authentication information object to the SecurityContext, the security context, through the SecurityContextHolder.getContext (). SetAuthentication () method.
In fact, there are two solutions for processing after authentication is passed, one is to rewrite successfulAuthentication directly in the filter, and the other is to implement AuthenticationSuccessHandler to handle authentication passing.
The same is true of authentication failures, either overriding the unsuccessfulAuthentication method or implementing AuthenticationFailureHandler to handle authentication failures.
That's the general process. From this process, we can see that there are several components that need to be rewritten:
EmailCodeAuthenticationFilter: message authentication login filter
EmailCodeAuthenticationToken: authentication token
EmailCodeAuthenticationProvider: email authentication processing
AuthenticationSuccessHandler: handles successful login operations
AuthenticationFailureHandler: handling failed login operations
Next, I imitate the source code to write my code. I suggest you take a look at it when you use it. I have removed some code that is not related to this.
Come on!
II. EmailCodeAuthenticationFilter
We need to rewrite the EmailCodeAuthenticationFilter, actually inherited the AbstractAuthenticationProcessingFilter abstract class, we will not write, we can first see how its default implementation UsernamePasswordAuthenticationFilter is like, copy homework this is everyone's strength, ha.
Public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {public static final String SPRING_SECURITY_FORM_USERNAME_KEY = "username"; public static final String SPRING_SECURITY_FORM_PASSWORD_KEY = "password"; private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher ("/ login", "POST"); / / Parameter private String usernameParameter = SPRING_SECURITY_FORM_USERNAME_KEY; private String passwordParameter = SPRING_SECURITY_FORM_PASSWORD_KEY passed from the foreground Private boolean postOnly = true; / / initialize a user password authentication filter the default login uri is / login request method is POST public UsernamePasswordAuthenticationFilter () {super (DEFAULT_ANT_PATH_REQUEST_MATCHER);} public UsernamePasswordAuthenticationFilter (AuthenticationManager authenticationManager) {super (DEFAULT_ANT_PATH_REQUEST_MATCHER, authenticationManager);} / * * perform actual authentication. The implementation should do one of the following: 1. Return the populated authentication token for the authenticated user, indicating that the authentication was successful. 2. Return null, indicating that the authentication process is still in progress. Before returning, the implementation should perform any additional work required to complete the process. 3. If the authentication process fails, throw AuthenticationException * / @ Override public 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: ""; / / generate UsernamePasswordAuthenticationToken and submit it to authenticate in AuthenticationManager for authentication later UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken (username, password); / / you can put some other information into setDetails (request, authRequest); return this.getAuthenticationManager (). Authenticate (authRequest);} @ Nullable protected String obtainPassword (HttpServletRequest request) {return request.getParameter (this.passwordParameter) } @ Nullable protected String obtainUsername (HttpServletRequest request) {return request.getParameter (this.usernameParameter);} protected void setDetails (HttpServletRequest request, UsernamePasswordAuthenticationToken authRequest) {authRequest.setDetails (this.authenticationDetailsSource.buildDetails (request));} / / set, get method}
Next, let's copy an assignment, ha:
Package com.crush.security.auth.email_code;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.authentication.AuthenticationServiceException;import org.springframework.security.core.Authentication;import org.springframework.security.core.AuthenticationException;import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;import org.springframework.security.web.util.matcher.AntPathRequestMatcher;import org.springframework.security.web.util.matcher.RequestMatcher;import javax.servlet.FilterChain;import javax.servlet.ServletException Import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import java.io.IOException;import java.util.ArrayList;/** * @ Author: crush * @ Date: 2021-09-08 21:13 * version 1.0 * / public class EmailCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {/ * the parameter name from the front end-used for request.getParameter to obtain * / private final String DEFAULT_EMAIL_NAME= "email" Private final String DEFAULT_EMAIL_CODE= "e_code"; @ Autowired @ Override public void setAuthenticationManager (AuthenticationManager authenticationManager) {super.setAuthenticationManager (authenticationManager);} / * * is it only in post mode * / private boolean postOnly = true / * create a matcher with the passed parameters * that is, url / public EmailCodeAuthenticationFilter () {super (new AntPathRequestMatcher ("/ email/login", "POST") of Filter filtering) } / * filter gets the username (mailbox) and password (CAPTCHA) to assemble to the token * then give the token to provider for authorization * / @ Override public Authentication attemptAuthentication (HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {if (postOnly & &! request.getMethod (). Equals ("POST")) {throw new AuthenticationServiceException ("Authentication method not supported:" + request.getMethod ()) } else {String email = getEmail (request); if (email = = null) {email = ";} email = email.trim (); / / if the verification code is not equal, deliberately let token make an error and then follow the process of springsecurity error boolean flag = checkCode (request) / / package token EmailCodeAuthenticationToken token = new EmailCodeAuthenticationToken (email,new ArrayList ()); this.setDetails (request,token); / / submit it to manager for certification return this.getAuthenticationManager () .authenticate (token) }} / * get the header information and let the appropriate provider verify him * / public void setDetails (HttpServletRequest request, EmailCodeAuthenticationToken token) {token.setDetails (this.authenticationDetailsSource.buildDetails (request));} / * get the incoming Email information * / public String getEmail (HttpServletRequest request) {String result= request.getParameter (DEFAULT_EMAIL_NAME) Return result;} / * judge the CAPTCHA information transmitted and the CAPTCHA information in session * / public boolean checkCode (HttpServletRequest request) {String code1 = request.getParameter (DEFAULT_EMAIL_CODE); System.out.println ("code1*" + code1) / / TODO write another link to generate the verification code. The verification code is stored in redis when it is generated / / TODO. The verification code here is written in Redis, and then you can delete the verification code if (code1.equals ("123456")) {return true;} return false after verification. } / / set, get method.} III. EmailCodeAuthenticationToken
We, EmailCodeAuthenticationToken, inherit from AbstractAuthenticationToken, and in the same way, let's go on to see what the default implementation of AbstractAuthenticationToken is.
/ * * / public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationToken {private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; / / if the account password referred to here is not authenticated, the initialization permission is empty and setAuthenticated (false) is set to an untrusted token * / public UsernamePasswordAuthenticationToken (Object principal, Object credentials) {super (null); this.principal = principal This.credentials = credentials; setAuthenticated (false);} / * * after authentication, put the permission in, and set setAuthenticated (true) to trusted token * / public UsernamePasswordAuthenticationToken (Object principal, Object credentials, Collection)
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.