Spring Security OAuth 自定义授权方式实现手机验证码
作者:Nosa 发布时间:2021-10-03 23:30:27
Spring Security OAuth 默认提供OAuth2.0 的四大基本授权方式(authorization_code\implicit\password\client_credential),除此之外我们也能够自定义授权方式。
先了解一下Spring Security OAuth提供的两个默认 Endpoints,一个是AuthorizationEndpoint,这个是仅用于授权码(authorization_code)和简化(implicit)模式的。另外一个是TokenEndpoint,用于OAuth2授权时下发Token,根据授予类型(GrantType)的不同而执行不同的验证方式。
OAuth2协议这里就不做过多介绍了,比较重要的一点是理解认证中各个角色的作用,以及认证的目的(获取用户信息或是具备使用API的权限)。例如在authorization_code模式下,用户(User)在认证服务的网站上进行登录,网站跳转回第三方应用(Client),第三方应用通过Secret和Code换取Token后向资源服务请求用户信息;而在client_credential模式下,第三方应用通过Secret直接获得Token后可以直接利用其访问资源API。所以我们应该根据实际的情景选择适合的认证模式。
对于手机验证码的认证模式,我们首先提出短信验证的通常需求:
每发一次验证码只能尝试验证5次,防止暴力破解
限制验证码发送频率,单个用户(这里简单使用手机号区分)1分钟1条,24小时x条
限制验证码有效期,15分钟
我们根据业务需求构造出对应的模型:
@Data
public class SmsVerificationModel {
/**
* 手机号
*/
private String phoneNumber;
/**
* 验证码
*/
private String captcha;
/**
* 本次验证码验证失败次数,防止暴力尝试
*/
private Integer failCount;
/**
* 该user当日尝试次数,防止滥发短信
*/
private Integer dailyCount;
/**
* 限制短信发送频率和实现验证码有效期
*/
private Date lastSentTime;
/**
* 是否验证成功
*/
private Boolean verified = false;
}
我们预想的认证流程:
接下来要对Spring Security OAuth进行定制,这里直接仿照一个比较相似的password模式,首先需要编写一个新的TokenGranter,处理sms类型下的TokenRequest,这个SmsTokenGranter会生成SmsAuthenticationToken,并将AuthenticationToken交由SmsAuthenticationProvider进行验证,验证成功后生成通过验证的SmsAuthenticationToken,完成Token的颁发。
public class SmsTokenGranter extends AbstractTokenGranter {
private static final String GRANT_TYPE = "sms";
private final AuthenticationManager authenticationManager;
public SmsTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices,
ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory){
super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
this.authenticationManager = authenticationManager;
}
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
Map<String, String> parameters = new LinkedHashMap<>(tokenRequest.getRequestParameters());
String phone = parameters.get("phone");
String code = parameters.get("code");
Authentication userAuth = new SmsAuthenticationToken(phone, code);
try {
userAuth = authenticationManager.authenticate(userAuth);
}
catch (AccountStatusException ase) {
throw new InvalidGrantException(ase.getMessage());
}
catch (BadCredentialsException e) {
throw new InvalidGrantException(e.getMessage());
}
if (userAuth == null || !userAuth.isAuthenticated()) {
throw new InvalidGrantException("Could not authenticate user: " + username);
}
OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
return new OAuth2Authentication(storedOAuth2Request, userAuth);
}
}
对应的SmsAuthenticationToken,其中一个构造方法是认证后的。
public class SmsAuthenticationToken extends AbstractAuthenticationToken {
private final Object principal;
private Object credentials;
public SmsAuthenticationToken(Object principal, Object credentials) {
super(null);
this.credentials = credentials;
this.principal = principal;
}
public SmsAuthenticationToken(Object principal, Object credentials,
Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
this.credentials = credentials;
// 表示已经认证
super.setAuthenticated(true);
}
...
}
SmsAuthenticationProvider是仿照AbstractUserDetailsAuthenticationProvider编写的,这里仅仅列出核心部分。
public class SmsAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
String username = authentication.getName();
UserDetails user = retrieveUser(username);
preAuthenticationChecks.check(user);
String phoneNumber = authentication.getPrincipal().toString();
String code = authentication.getCredentials().toString();
// 尝试从Redis中取出Model
SmsVerificationModel verificationModel =
Optional.ofNullable(
redisService.get(SMS_REDIS_PREFIX + phoneNumber, SmsVerificationModel.class))
.orElseThrow(() -> new BusinessException(OAuthError.SMS_VERIFY_BEFORE_SEND));
// 判断短信验证次数
Optional.of(verificationModel).filter(x -> x.getFailCount() < SMS_VERIFY_FAIL_MAX_TIMES)
.orElseThrow(() -> new BusinessException(OAuthError.SMS_VERIFY_COUNT_EXCEED));
Optional.of(verificationModel).map(SmsVerificationModel::getLastSentTime)
// 验证码发送15分钟内有效,等价于发送时间加上15分钟晚于当下
.filter(x -> DateUtils.addMinutes(x,15).after(new Date()))
.orElseThrow(() -> new BusinessException(OAuthError.SMS_CODE_EXPIRED));
verificationModel.setVerified(Objects.equals(code, verificationModel.getCaptcha()));
verificationModel.setFailCount(verificationModel.getFailCount() + 1);
redisService.set(SMS_REDIS_PREFIX + phoneNumber, verificationModel, 1, TimeUnit.DAYS);
if(!verificationModel.getVerified()){
throw new BusinessException(OAuthError.SmsCodeWrong);
}
postAuthenticationChecks.check(user);
return createSuccessAuthentication(user, authentication, user);
}
...
接下来要通过配置启用我们定制的类,首先配置AuthorizationServerEndpointsConfigurer,添加上我们的TokenGranter,然后是AuthenticationManagerBuilder,添加我们的AuthenticationProvider。
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security
.passwordEncoder(passwordEncoder)
.checkTokenAccess("isAuthenticated()")
.tokenKeyAccess("permitAll()")
// 允许使用Query字段验证客户端,即client_id/client_secret 能够放在查询参数中
.allowFormAuthenticationForClients();
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService)
.tokenStore(tokenStore);
List<TokenGranter> tokenGranters = new ArrayList<>();
tokenGranters.add(new AuthorizationCodeTokenGranter(endpoints.getTokenServices(), endpoints.getAuthorizationCodeServices(), clientDetailsService,
endpoints.getOAuth2RequestFactory()));
...
tokenGranters.add(new SmsTokenGranter(authenticationManager, endpoints.getTokenServices(),
clientDetailsService, endpoints.getOAuth2RequestFactory()));
endpoints.tokenGranter(new CompositeTokenGranter(tokenGranters));
}
}
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
...
@Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(daoAuthenticationProvider());
}
@Bean
public AuthenticationProvider smsAuthenticationProvider(){
SmsAuthenticationProvider smsAuthenticationProvider = new SmsAuthenticationProvider();
smsAuthenticationProvider.setUserDetailsService(userDetailsService);
smsAuthenticationProvider.setSmsAuthService(smsAuthService);
return smsAuthenticationProvider;
}
}
那么短信验证码授权的部分就到这里了,最后还有一个发送短信的接口,这里就不展示了。
最后测试一下,curl --location --request POST 'http://localhost:8080/oauth/token?grant_type=sms&client_id=XXX&phone=手机号&code=验证码' ,成功。
{
"access_token": "39bafa9a-7e5b-4ba4-9eda-e307ac98aad1",
"token_type": "bearer",
"expires_in": 3599,
"scope": "ALL"
}
来源:https://juejin.cn/post/6923568301939359752


猜你喜欢
- 我们还是来讨论c++吧,这几年在c++里面玩代码自动生成技术,而预处理是不可避免,也是不可或缺的重要工具。虽然boost pp预处理库在宏的
- 在逆向一个Android程序时,如果只是盲目的分析需要阅读N多代码才能找到程序的关键点或Hook点,本文将分享一下如何快速的找到APP程序的
- SharedPreferences介绍:SharedPreferences是Android平台上一个轻量级的存储类,主要是保存一些常用的配置
- 使用了RecyclerView嵌套RecyclerView的方案。购物车的第一个界面为RecyclerView,每个Item里面包含一个店铺
- 1.稀疏数组引入1.1 使用场景笔者在课程设计中曾写过一个扫雷小游戏,为了便于讲解,我们来做个简化(实际比这个复杂),只考虑当前位置有雷与无
- 介绍线段树(又名区间树)也是一种二叉树,每个节点的值等于左右孩子节点值的和,线段树示例图如下以求和为例,根节点表示区间0-5的和,左孩子表示
- 本文简要介绍如何使用Spring Cloud Gateway 作为API 网关(不是使用zuul作为网关),关于Spring Cloud G
- 准备:wildfly/tomcat或者其他服务器你的数据库的Driver,(此处用的mysql-connecter-java-5.1.39-
- Pom依赖<parent> <groupId>org.springframework.bo
- 参考 java查找无向连通图中两点间所有路径的算法,对代码进行了部分修改,并编写了测试用例。算法要求:1. 在一个无向连通图中求出
- Linux下的五种I/O模型1)阻塞I/O(blocking I/O)2)非阻塞I/O (nonblocking I/O)3) I/O复用(
- Java * 分析及理解代理设计模式定义:为其他对象提供一种代理以控制对这个对象的访问。 * 使用java * 机制以巧妙的方式实现了
- 通常,在这个页面中会用到很多控件,控件会用到很多的资源。Android系统本身有很多的资源,包括各种各样的字符串、图片、动画、样式和布局等等
- 本文实例讲述了C#编程之事务用法。分享给大家供大家参考,具体如下:ado.net2.0的SqlTransaction使用方法/////ado
- 欲达此目的,可以采用下列两种作法: ◆使用XmlConvert类。 ◆将一个XSLT转换套用至DataSet数据的XML表示。 程序范例 本
- private void WorkflowConfigure_FormClosing(object sender, FormClosingE
- 一. this关键字1. 简介我们知道,this是”这个“的意思。在java中表示当前类的对象, 可
- 1.简介if判断语句是很多编程语言的重要组成部分。但是,若我们最终编写了大量嵌套的if语句,这将使得我们的代码更加复杂和难以维护。让我们看看
- 1 框架组成SpringSpringMVCMyBatis2 所需工具Mysql 8.0.15数据库管理系统,创建数据库Tomcat 8.5.
- 1、SpringBoot配置文件1.1 优先级关于SpringBoot配置文件可以是properties或者是yaml格式的文件,但是在Sp