Now the verification code login has become the mainstream login method for many applications, but for OAuth2 authorization, the mobile phone number verification code processing user authentication is very cumbersome, and many students do not know how to access.
Anyone who has seriously studied the Spring Security OAuth2 column of Fat Brother will know one thing. In fact, OAuth2 does not matter how the resource owner is authenticated, as long as the resource owner authenticates in the authorization process. It doesn't matter what fingerprint iris is.
Id Server implementation
Therefore, the fat brother seems to have found a way to connect the verification code to the Id Server . The previous fat brother has open sourced a Spring Security login extension package spring-security-login-extension , which can access the verification code login and applet login with one click. This should work. So I remodeled and successfully implemented this function. Take a look at the effect:
Compared with before, users can choose to log in with account password or mobile phone verification code during the authorization process.
Here you can change it, is it compatible as long as you log in with the verification code?
general principle
This requires front-end and back-end collaboration.
rear end
The core is still the usage of the extension package, add LoginFilterSecurityConfigurer
configuration to HttpSecurity
2e7dd27fd6a84c2e12cc0919861a2858---, here I changed it and it is different from the original package. After the login is successful, you can no longer return JWT
. It needs to be consistent with the account and password login . The core code is as follows:
httpSecurity.apply(new LoginFilterSecurityConfigurer<>())
// 手机号验证码登录模拟
.captchaLogin(captchaLoginConfigurer ->
// 验证码校验 1 在此处配置 优先级最高 2 注册为Spring Bean 可以免配置
captchaLoginConfigurer.captchaService(this::verifyCaptchaMock)
// 根据手机号查询用户UserDetials 1 在此处配置 优先级最高 2 注册为Spring Bean 可以免配置
.captchaUserDetailsService(this::loadUserByPhoneMock)
// 两个登录保持一致
.successHandler(loginAuthenticationSuccessHandler)
// 两个登录保持一致
.failureHandler(authenticationFailureHandler);
Among them loadUserByPhoneMock
is the analog CaptchaUserDetailsService
interface, which is loaded according to the mobile phone number UserDetails
:
private UserDetails loadUserByPhoneMock(String phone) throws UsernameNotFoundException {
return // 用户名
User.withUsername(phone)
// 密码
.password("password") .passwordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder()::encode)
.roles("user", "mobile")
.build();
}
verifyCaptchaMock
is the simulation of the verification code verification logic interface CaptchaService
, here it is written as 1234
. Into the cache, call the cache interface in CaptchaService
to take out the verification code for verification:
private boolean verifyCaptchaMock(String phone, String code) {
//todo 自己实现缓存校验逻辑
return code.equals("1234");
}
The interface for sending the verification code is freely implemented. There is no need to define the specification here, just remember to access the cache.
front end
The front end only needs to access a login page that can switch the login method. Then put the verification code login interface and the verification code sending interface into it. The authorization login page is oauth2_login.html
. Through its controller, Fat Brother even added a switch enableCaptchaLogin
to decide whether to Use the verification code authentication method.
@GetMapping("/login")
public String oauth2LoginPage(Model model,
@CurrentSecurityContext(expression = "authentication")
Authentication authentication,
@Value("${spring.security.oauth2.server.login.captcha.enabled:true}")
boolean enableCaptchaLogin,
@RequestAttribute(name = "org.springframework.security.web.csrf.CsrfToken", required = false)
CsrfToken csrfToken) {
if (!(authentication instanceof AnonymousAuthenticationToken)){
return "redirect:/";
}
if (csrfToken != null) {
model.addAttribute("_csrfToken", csrfToken);
}
SystemSettings systemSettings = new SystemSettings();
model.addAttribute("enableCaptchaLogin",enableCaptchaLogin);
model.addAttribute("systemSettings", systemSettings);
return "oauth2_login";
}
Front-end and verification code related JS processing:
if ([[${enableCaptchaLogin}]]){
form.on('submit(mobile-login)', function (data) {
let loader = layer.load();
let btn = button.load({elem: '.login'});
$.ajax({
url: '/login/captcha',
data: data.field,
type: "post",
dataType: 'json',
success: function (result) {
layer.close(loader);
btn.stop(function () {
if (result.code === 200) {
popup.success(result.msg, function () {
location.href = result.data.targetUrl;
})
} else if (result.code === 401) {
popup.failure(result.msg);
}
})
}
});
return false;
});
$('#captcha-btn').click(function (){
//TODO 这里接入验证码接口
popup.success('验证码已发送');
})
}
About Id Server
Id Server is an open source authorization server based on Spring Authorization Server, which greatly reduces the difficulty of learning and using OAuth2 authorization server, provides UI console, dynamic permission control, and facilitates OAuth2 client management. It can generate Spring Security configuration with one click, out of the box It supports integration of Java ecological frameworks such as Spring Boot and Spring Cloud, and even supports other languages. It can be deployed with a small amount of configuration. The code is open source, which is convenient for secondary development. It supports four client authentication methods and three authorization modes of OAuth2, and supports account Password authentication and verification code authentication. Welcome to learn to use and participate in code contributions.
Summarize
OAuth2 authorization using verification code has been implemented and is applicable to all DEMOs provided by Id Server . If you are interested, you can get the latest verification code authorization code from the following warehouse address, remember to give a Star :
https://github.com/NotFound403/id-server
In addition, some people asked about the relationship between Id Server and Fat Brother Spring Security OAuth2 column . Id Server is an open source project. The underlying logical support comes from the analysis of Spring Authorization Server . Mastering the knowledge of the column can help you customize the Id Server . The goal of Id Server is to create a production-available OAuth2 authorization server and reduce the cost of learning and using OAuth2 . I hope you can support it.
关注公众号:Felordcn 获取更多资讯
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。