Spring Security OAuth 自定义授权方式实现手机验证码
Spring Security OAuth 默认提供OAuth2.0 的四大基本授权方式(authorization_codeimplicitpasswordclient_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分钟我们根据业务需求构造出对应的模型:
@Datapublic 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@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 能够放在查询参数中.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; }}
那么短信验证码授权的部分就到这里了,最后还有一个发送短信的接口,这里就不展示了。
最后测试一下,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'}
到此这篇关于Spring Security OAuth 自定义授权方式实现手机验证码的文章就介绍到这了,更多相关Spring Security OAuth手机验证码内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!
相关文章: