Preface
In the previous article "Spring Security Implementation user name or mobile phone number login", through a custom implementation of the Userdetailsservice interface, the implementation of the support user name + password or mobile phone number + password login problem.
In a real-world scenario, it is common for a user to forget the password, except for the forgotten user name. Using mobile verification code to login to the website is becoming more and more popular. Principle Analysis
In spring security, password verification is part of the authentication, and is mainly implemented by the Authenticationprovider implementation class to achieve the user name and password matching check.
Through the debug source can be found that the project using spring Abstractuserdetailsauthenticationprovider implementation class, in Apublic authentication authenticate ( Authentication authentication) method to verify the work.
Since we need to support cell phone verification code login, then it is clear that we mainly write a own implementation class, and then rewrite the public authentication authenticate (authentication authentication) method. Main code
Authenticationprovider Implementation Class
@Component public class Custauthenticationprovider implements Authenticationprovider {@Autowired Userdetailsserv Ice Userdetailsservice; Mainly used to check the user name @Autowired Custbcryptpasswordencoder passwordencoder; Mainly used to compare the password @Autowired smssendrecordservice smssendrecordservice; SMS Verification Code Service @Override public authentication authenticate (authentication authentication) throws Authenticationexcept
Ion {String username = authentication.getname ();
String password = (string) authentication.getcredentials ();
Userdetails userdetails;
Check the user name validity try {userdetails = Userdetailsservice.loaduserbyusername (username);
} catch (Usernamenotfoundexception e) {throw new badcredentialsexception (Messageconstant.username_not_found); }//Priority match password if (passwordencoder.matches (password, Userdetails.getpassword ())) {Collec tion<? Extends grantedauthority> authorities = Userdetails.Getauthorities ();
return new Usernamepasswordauthenticationtoken (userdetails, password, authorities); } else {//here will password try as a mobile phone verification code, and then the verification code sent to verify, need to pay attention to the validity of the code, whether the verification code and other judgment return new usernamepasswordauthe
Nticationtoken (userdetails, password, authorities); }} @Override public Boolean supports (class<?> authentication) {return (Usernamepasswordauthen
TicationToken.class.isAssignableFrom (authentication));
}
}