Spring Security OAuth 自定義授權(quán)方式實(shí)現(xiàn)手機(jī)驗(yàn)證碼
Spring Security OAuth 默認(rèn)提供OAuth2.0 的四大基本授權(quán)方式(authorization_code\implicit\password\client_credential),除此之外我們也能夠自定義授權(quán)方式。
先了解一下Spring Security OAuth提供的兩個(gè)默認(rèn) Endpoints,一個(gè)是AuthorizationEndpoint,這個(gè)是僅用于授權(quán)碼(authorization_code)和簡(jiǎn)化(implicit)模式的。另外一個(gè)是TokenEndpoint,用于OAuth2授權(quán)時(shí)下發(fā)Token,根據(jù)授予類(lèi)型(GrantType)的不同而執(zhí)行不同的驗(yàn)證方式。
OAuth2協(xié)議這里就不做過(guò)多介紹了,比較重要的一點(diǎn)是理解認(rèn)證中各個(gè)角色的作用,以及認(rèn)證的目的(獲取用戶(hù)信息或是具備使用API的權(quán)限)。例如在authorization_code模式下,用戶(hù)(User)在認(rèn)證服務(wù)的網(wǎng)站上進(jìn)行登錄,網(wǎng)站跳轉(zhuǎn)回第三方應(yīng)用(Client),第三方應(yīng)用通過(guò)Secret和Code換取Token后向資源服務(wù)請(qǐng)求用戶(hù)信息;而在client_credential模式下,第三方應(yīng)用通過(guò)Secret直接獲得Token后可以直接利用其訪(fǎng)問(wèn)資源API。所以我們應(yīng)該根據(jù)實(shí)際的情景選擇適合的認(rèn)證模式。
對(duì)于手機(jī)驗(yàn)證碼的認(rèn)證模式,我們首先提出短信驗(yàn)證的通常需求:
- 每發(fā)一次驗(yàn)證碼只能?chē)L試驗(yàn)證5次,防止暴力破解
- 限制驗(yàn)證碼發(fā)送頻率,單個(gè)用戶(hù)(這里簡(jiǎn)單使用手機(jī)號(hào)區(qū)分)1分鐘1條,24小時(shí)x條
- 限制驗(yàn)證碼有效期,15分鐘
我們根據(jù)業(yè)務(wù)需求構(gòu)造出對(duì)應(yīng)的模型:
@Data
public class SmsVerificationModel {
/**
* 手機(jī)號(hào)
*/
private String phoneNumber;
/**
* 驗(yàn)證碼
*/
private String captcha;
/**
* 本次驗(yàn)證碼驗(yàn)證失敗次數(shù),防止暴力嘗試
*/
private Integer failCount;
/**
* 該user當(dāng)日嘗試次數(shù),防止濫發(fā)短信
*/
private Integer dailyCount;
/**
* 限制短信發(fā)送頻率和實(shí)現(xiàn)驗(yàn)證碼有效期
*/
private Date lastSentTime;
/**
* 是否驗(yàn)證成功
*/
private Boolean verified = false;
}
我們預(yù)想的認(rèn)證流程:

接下來(lái)要對(duì)Spring Security OAuth進(jìn)行定制,這里直接仿照一個(gè)比較相似的password模式,首先需要編寫(xiě)一個(gè)新的TokenGranter,處理sms類(lèi)型下的TokenRequest,這個(gè)SmsTokenGranter會(huì)生成SmsAuthenticationToken,并將AuthenticationToken交由SmsAuthenticationProvider進(jìn)行驗(yàn)證,驗(yàn)證成功后生成通過(guò)驗(yàn)證的SmsAuthenticationToken,完成Token的頒發(fā)。
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);
}
}
對(duì)應(yīng)的SmsAuthenticationToken,其中一個(gè)構(gòu)造方法是認(rèn)證后的。
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;
// 表示已經(jīng)認(rèn)證
super.setAuthenticated(true);
}
...
}
SmsAuthenticationProvider是仿照AbstractUserDetailsAuthenticationProvider編寫(xiě)的,這里僅僅列出核心部分。
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));
// 判斷短信驗(yàn)證次數(shù)
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)
// 驗(yàn)證碼發(fā)送15分鐘內(nèi)有效,等價(jià)于發(fā)送時(shí)間加上15分鐘晚于當(dāng)下
.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);
}
...
接下來(lái)要通過(guò)配置啟用我們定制的類(lèi),首先配置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字段驗(yàn)證客戶(hù)端,即client_id/client_secret 能夠放在查詢(xún)參數(shù)中
.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;
}
}
那么短信驗(yàn)證碼授權(quán)的部分就到這里了,最后還有一個(gè)發(fā)送短信的接口,這里就不展示了。
最后測(cè)試一下,curl --location --request POST 'http://localhost:8080/oauth/token?grant_type=sms&client_id=XXX&phone=手機(jī)號(hào)&code=驗(yàn)證碼' ,成功。
{
"access_token": "39bafa9a-7e5b-4ba4-9eda-e307ac98aad1",
"token_type": "bearer",
"expires_in": 3599,
"scope": "ALL"
}
到此這篇關(guān)于Spring Security OAuth 自定義授權(quán)方式實(shí)現(xiàn)手機(jī)驗(yàn)證碼的文章就介紹到這了,更多相關(guān)Spring Security OAuth手機(jī)驗(yàn)證碼內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 詳解使用Spring Security OAuth 實(shí)現(xiàn)OAuth 2.0 授權(quán)
- 基于Spring Security的Oauth2授權(quán)實(shí)現(xiàn)方法
- Spring Security OAuth2認(rèn)證授權(quán)示例詳解
- Spring Security 控制授權(quán)的方法
- Spring?Security使用數(shù)據(jù)庫(kù)登錄認(rèn)證授權(quán)
- Spring Security實(shí)現(xiàn)微信公眾號(hào)網(wǎng)頁(yè)授權(quán)功能
- SpringBoot Security前后端分離登錄驗(yàn)證的實(shí)現(xiàn)
- 解析SpringSecurity自定義登錄驗(yàn)證成功與失敗的結(jié)果處理問(wèn)題
- 詳解Spring Security中的HttpBasic登錄驗(yàn)證模式
- 淺析Spring Security登錄驗(yàn)證流程源碼
- 詳解使用Spring Security進(jìn)行自動(dòng)登錄驗(yàn)證
- SpringSecurity頁(yè)面授權(quán)與登錄驗(yàn)證實(shí)現(xiàn)(內(nèi)存取值與數(shù)據(jù)庫(kù)取值)
相關(guān)文章
解決javac不是內(nèi)部或外部命令,也不是可運(yùn)行程序的報(bào)錯(cuò)問(wèn)題
在學(xué)著使用Java的命令行來(lái)編譯java文件的時(shí)候,遇到了這個(gè)問(wèn)題,本文主要介紹了解決javac不是內(nèi)部或外部命令,也不是可運(yùn)行程序的報(bào)錯(cuò)問(wèn)題,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04
Spring使用@Conditional進(jìn)行條件裝配的實(shí)現(xiàn)
在spring中有些bean需要滿(mǎn)足某些環(huán)境條件才創(chuàng)建某個(gè)bean,這個(gè)時(shí)候可以在bean定義上使用@Conditional注解來(lái)修飾,所以本文給大家介紹了Spring使用@Conditional進(jìn)行條件裝配的實(shí)現(xiàn),文中通過(guò)代碼示例給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12
Java開(kāi)發(fā)之request對(duì)象常用方法整理
這篇文章主要介紹了 Java開(kāi)發(fā)之request對(duì)象常用方法整理的相關(guān)資料,需要的朋友可以參考下2017-02-02
SpringCloud的Gateway網(wǎng)關(guān)詳解
這篇文章主要介紹了SpringCloud的Gateway網(wǎng)關(guān)詳解,Gateway 是 Spring Cloud 官方推出的一個(gè)基于 Spring 5、Spring Boot 2 和 Project Reactor 的 API 網(wǎng)關(guān)實(shí)現(xiàn),本文將介紹 Spring Cloud Gateway 的基本概念、核心組件以及如何配置和使用它,需要的朋友可以參考下2023-09-09
MyBatis深入解讀動(dòng)態(tài)SQL的實(shí)現(xiàn)
動(dòng)態(tài) SQL 是 MyBatis 的強(qiáng)大特性之一。如果你使用過(guò) JDBC 或其它類(lèi)似的框架,你應(yīng)該能理解根據(jù)不同條件拼接 SQL 語(yǔ)句有多痛苦,例如拼接時(shí)要確保不能忘記添加必要的空格,還要注意去掉列表最后一個(gè)列名的逗號(hào)。利用動(dòng)態(tài) SQL,可以徹底擺脫這種痛苦2022-04-04
Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(34)
下面小編就為大家?guī)?lái)一篇Java基礎(chǔ)的幾道練習(xí)題(分享)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧,希望可以幫到你2021-07-07
Day14基礎(chǔ)不牢地動(dòng)山搖-Java基礎(chǔ)
這篇文章主要給大家介紹了關(guān)于Java中方法使用的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-08-08
Java隨機(jī)生成手機(jī)短信驗(yàn)證碼的方法
這篇文章主要介紹了Java隨機(jī)生成手機(jī)短信驗(yàn)證碼的方法,涉及Java數(shù)學(xué)運(yùn)算計(jì)算隨機(jī)數(shù)及字符串操作的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11

