电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術(shù)文章
文章詳情頁

Spring Security OAuth 自定義授權(quán)方式實現(xiàn)手機驗證碼

瀏覽:22日期:2023-07-24 09:55:23

Spring Security OAuth 默認(rèn)提供OAuth2.0 的四大基本授權(quán)方式(authorization_codeimplicitpasswordclient_credential),除此之外我們也能夠自定義授權(quán)方式。

先了解一下Spring Security OAuth提供的兩個默認(rèn) Endpoints,一個是AuthorizationEndpoint,這個是僅用于授權(quán)碼(authorization_code)和簡化(implicit)模式的。另外一個是TokenEndpoint,用于OAuth2授權(quán)時下發(fā)Token,根據(jù)授予類型(GrantType)的不同而執(zhí)行不同的驗證方式。

OAuth2協(xié)議這里就不做過多介紹了,比較重要的一點是理解認(rèn)證中各個角色的作用,以及認(rèn)證的目的(獲取用戶信息或是具備使用API的權(quán)限)。例如在authorization_code模式下,用戶(User)在認(rèn)證服務(wù)的網(wǎng)站上進(jìn)行登錄,網(wǎng)站跳轉(zhuǎn)回第三方應(yīng)用(Client),第三方應(yīng)用通過Secret和Code換取Token后向資源服務(wù)請求用戶信息;而在client_credential模式下,第三方應(yīng)用通過Secret直接獲得Token后可以直接利用其訪問資源API。所以我們應(yīng)該根據(jù)實際的情景選擇適合的認(rèn)證模式。

對于手機驗證碼的認(rèn)證模式,我們首先提出短信驗證的通常需求:

每發(fā)一次驗證碼只能嘗試驗證5次,防止暴力破解 限制驗證碼發(fā)送頻率,單個用戶(這里簡單使用手機號區(qū)分)1分鐘1條,24小時x條 限制驗證碼有效期,15分鐘

我們根據(jù)業(yè)務(wù)需求構(gòu)造出對應(yīng)的模型:

@Datapublic class SmsVerificationModel { /** * 手機號 */ private String phoneNumber; /** * 驗證碼 */ private String captcha; /** * 本次驗證碼驗證失敗次數(shù),防止暴力嘗試 */ private Integer failCount; /** * 該user當(dāng)日嘗試次數(shù),防止濫發(fā)短信 */ private Integer dailyCount; /** * 限制短信發(fā)送頻率和實現(xiàn)驗證碼有效期 */ private Date lastSentTime; /** * 是否驗證成功 */ private Boolean verified = false;}

我們預(yù)想的認(rèn)證流程:

Spring Security OAuth 自定義授權(quán)方式實現(xiàn)手機驗證碼

接下來要對Spring Security OAuth進(jìn)行定制,這里直接仿照一個比較相似的password模式,首先需要編寫一個新的TokenGranter,處理sms類型下的TokenRequest,這個SmsTokenGranter會生成SmsAuthenticationToken,并將AuthenticationToken交由SmsAuthenticationProvider進(jì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); }}

對應(yīng)的SmsAuthenticationToken,其中一個構(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編寫的,這里僅僅列出核心部分。

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)); // 判斷短信驗證次數(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)// 驗證碼發(fā)送15分鐘內(nèi)有效,等價于發(fā)送時間加上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); } ...

接下來要通過配置啟用我們定制的類,首先配置AuthorizationServerEndpointsConfigurer,添加上我們的TokenGranter,然后是AuthenticationManagerBuilder,添加我們的AuthenticationProvider。

@Configuration@EnableAuthorizationServerpublic class OAuth2Config extends AuthorizationServerConfigurerAdapter { @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { security.passwordEncoder(passwordEncoder).checkTokenAccess('isAuthenticated()').tokenKeyAccess('permitAll()')// 允許使用Query字段驗證客戶端,即client_id/client_secret 能夠放在查詢參數(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@Configurationpublic 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; }}

那么短信驗證碼授權(quán)的部分就到這里了,最后還有一個發(fā)送短信的接口,這里就不展示了。

最后測試一下,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'}

到此這篇關(guān)于Spring Security OAuth 自定義授權(quán)方式實現(xiàn)手機驗證碼的文章就介紹到這了,更多相關(guān)Spring Security OAuth手機驗證碼內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 合金耐磨锤头_破碎机锤头_郑州市德勤建材有限公司 | 全国冰箱|空调|洗衣机|热水器|燃气灶维修服务平台-百修家电 | 紫外可见光分光度计-紫外分光度计-分光光度仪-屹谱仪器制造(上海)有限公司 | 美名宝起名网-在线宝宝、公司、起名平台| 工程管道/塑料管材/pvc排水管/ppr给水管/pe双壁波纹管等品牌管材批发厂家-河南洁尔康建材 | 无负压供水设备,消防稳压供水设备-淄博创辉供水设备有限公司 | 欧美日韩国产一区二区三区不_久久久久国产精品无码不卡_亚洲欧洲美洲无码精品AV_精品一区美女视频_日韩黄色性爱一级视频_日本五十路人妻斩_国产99视频免费精品是看4_亚洲中文字幕无码一二三四区_国产小萍萍挤奶喷奶水_亚洲另类精品无码在线一区 | 济南保安公司加盟挂靠-亮剑国际安保服务集团总部-山东保安公司|济南保安培训学校 | 智能监控-安防监控-监控系统安装-弱电工程公司_成都万全电子 | 东莞市天进机械有限公司-钉箱机-粘箱机-糊箱机-打钉机认准东莞天进机械-厂家直供更放心! | 锂电混合机-新能源混合机-正极材料混料机-高镍,三元材料混料机-负极,包覆混合机-贝尔专业混合混料搅拌机械系统设备厂家 | 全自动过滤器_反冲洗过滤器_自清洗过滤器_量子除垢环_量子环除垢_量子除垢 - 安士睿(北京)过滤设备有限公司 | 中式装修设计_全屋定制家具_实木仿古门窗花格厂家-喜迎门 | 南京欧陆电气股份有限公司-风力发电机官网 | 医用空气消毒机-医用管路消毒机-工作服消毒柜-成都三康王 | 水平垂直燃烧试验仪-灼热丝试验仪-漏电起痕试验仪-针焰试验仪-塑料材料燃烧检测设备-IP防水试验机 | 合肥白癜风医院_[治疗白癜风]哪家好_合肥北大白癜风医院 | 立式矫直机_卧式矫直机-无锡金矫机械制造有限公司 | 新疆十佳旅行社_新疆旅游报价_新疆自驾跟团游-新疆中西部国际旅行社 | 陕西华春网络科技股份有限公司| 青岛侦探_青岛侦探事务所_青岛劝退小三_青岛调查出轨取证公司_青岛婚外情取证-青岛探真调查事务所 | RTO换向阀_VOC高温阀门_加热炉切断阀_双偏心软密封蝶阀_煤气蝶阀_提升阀-湖北霍科德阀门有限公司 | 实木家具_实木家具定制_全屋定制_美式家具_圣蒂斯堡官网 | jrs高清nba(无插件)直播-jrs直播低调看直播-jrs直播nba-jrs直播 上海地磅秤|电子地上衡|防爆地磅_上海地磅秤厂家–越衡称重 | 双菱电缆-广州电缆厂_广州电缆厂有限公司 | 江苏南京多语种翻译-专业翻译公司报价-正规商务翻译机构-南京华彦翻译服务有限公司 | 国产频谱分析仪-国产网络分析仪-上海坚融实业有限公司 | 钢骨架轻型板_膨石轻型板_钢骨架轻型板价格_恒道新材料 | CE认证_产品欧盟ROHS-REACH检测机构-商通检测 | 云南外加剂,云南速凝剂,云南外加剂代加工-普洱澜湄新材料科技有限公司 | 精密模具-双色注塑模具加工-深圳铭洋宇通 | 工业冷却塔维修厂家_方形不锈钢工业凉水塔维修改造方案-广东康明节能空调有限公司 | 工业洗衣机_工业洗涤设备_上海力净工业洗衣机厂家-洗涤设备首页 bkzzy在职研究生网 - 在职研究生招生信息咨询平台 | 东亚液氮罐-液氮生物容器-乐山市东亚机电工贸有限公司 | PE一体化污水处理设备_地埋式生活污水净化槽定制厂家-岩康塑业 | 新型游乐设备,360大摆锤游乐设备「诚信厂家」-山东方鑫游乐设备 新能源汽车电池软连接,铜铝复合膜柔性连接,电力母排-容发智能科技(无锡)有限公司 | 上海洗地机-洗地机厂家-全自动洗地机-手推式洗地机-上海滢皓洗地机 | 全自动实验室洗瓶机,移液管|培养皿|进样瓶清洗机,清洗剂-广州摩特伟希尔机械设备有限责任公司 | 工业制氮机_psa制氮机厂家-宏骁智能装备科技江苏有限公司 | 蓝米云-专注于高性价比香港/美国VPS云服务器及海外公益型免费虚拟主机 | VOC检测仪-甲醛检测仪-气体报警器-气体检测仪厂家-深恒安科技有限公司 |