新增验证码登录功能

This commit is contained in:
liaozetao
2023-07-11 11:35:56 +08:00
parent bc7a2804a3
commit 312dfd81dc
10 changed files with 221 additions and 64 deletions

View File

@@ -4,7 +4,8 @@ import com.accompany.oauth2.constant.GrantTypeEnum;
import com.accompany.oauth2.exception.CustomOAuth2WebResponseExceptionTranslator;
import com.accompany.oauth2.jwt.JwtTokenConverter;
import com.accompany.oauth2.service.account.SuperAdminGrantService;
import com.accompany.oauth2.support.PasswordTokenGranter;
import com.accompany.oauth2.support.password.PasswordTokenGranter;
import com.accompany.oauth2.support.verify.VerifyCodeTokenGranter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
@@ -56,16 +57,20 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
String finalSecret = "{bcrypt}"+new BCryptPasswordEncoder().encode(oAuthConfig.getClientSecret());
String finalSecret = "{bcrypt}" + new BCryptPasswordEncoder().encode(oAuthConfig.getClientSecret());
//配置两个客户端,一个用于password认证一个用于client认证
clients.inMemory().withClient(oAuthConfig.getClientId())
.authorizedGrantTypes(GrantTypeEnum.PASSWORD.getValue(), GrantTypeEnum.REFRESH_TOKEN.getValue(), GrantTypeEnum.OPENID.getValue(), GrantTypeEnum.APPLE.getValue())
.scopes("read", "write")
.authorizedGrantTypes(
GrantTypeEnum.PASSWORD.getValue(),
GrantTypeEnum.REFRESH_TOKEN.getValue(),
GrantTypeEnum.OPENID.getValue(),
GrantTypeEnum.APPLE.getValue(),
GrantTypeEnum.VERIFY_CODE.getValue()
).scopes("read", "write")
.authorities("oauth2")
.secret(finalSecret)
.accessTokenValiditySeconds(2592000)
.refreshTokenValiditySeconds(3196800)
.and();
.refreshTokenValiditySeconds(3196800);
}
@Bean
@@ -74,7 +79,7 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
}
@Bean
public JwtTokenConverter tokenEnhancer(){
public JwtTokenConverter tokenEnhancer() {
JwtTokenConverter jwtTokenConverter = new JwtTokenConverter();
jwtTokenConverter.setSigningKey(oAuthConfig.getJwtSignKey());
return jwtTokenConverter;
@@ -84,15 +89,14 @@ public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdap
AuthorizationServerTokenServices tokenServices,
ClientDetailsService clientDetails,
OAuth2RequestFactory requestFactory) {
List<TokenGranter> tokenGranters = new ArrayList();
List<TokenGranter> tokenGranters = new ArrayList<>();
tokenGranters.add(new AuthorizationCodeTokenGranter(tokenServices, new InMemoryAuthorizationCodeServices(), clientDetails, requestFactory));
tokenGranters.add(new RefreshTokenGranter(tokenServices, clientDetails, requestFactory));
tokenGranters.add(new ImplicitTokenGranter(tokenServices, clientDetails, requestFactory));
tokenGranters.add(new ClientCredentialsTokenGranter(tokenServices, clientDetails, requestFactory));
if (authenticationManager != null) {
PasswordTokenGranter passwordTokenGranter = new PasswordTokenGranter(authenticationManager, tokenServices, clientDetails, requestFactory);
tokenGranters.add(passwordTokenGranter);
tokenGranters.add(new PasswordTokenGranter(authenticationManager, tokenServices, clientDetails, requestFactory));
tokenGranters.add(new VerifyCodeTokenGranter(authenticationManager, tokenServices, clientDetails, requestFactory));
}
return new CompositeTokenGranter(tokenGranters);
}

View File

@@ -1,9 +1,11 @@
package com.accompany.oauth2.config;
import com.accompany.core.service.SysConfService;
import com.accompany.core.service.user.PhoneBlackService;
import com.accompany.oauth2.service.MyUserDetailsService;
import com.accompany.oauth2.service.MyUserDetailsServiceImpl;
import com.accompany.oauth2.support.PasswordAuthenticationProvider;
import com.accompany.oauth2.support.password.PasswordAuthenticationProvider;
import com.accompany.oauth2.support.verify.VerifyCodeAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@@ -24,9 +26,12 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private SysConfService sysConfService;
@Autowired
private PhoneBlackService phoneBlackService;
@Bean
@Override
protected UserDetailsService userDetailsService(){
protected UserDetailsService userDetailsService() {
return myUserDetailsService();
}
@@ -36,7 +41,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
}
@Bean
PasswordEncoder passwordEncoder(){
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@@ -49,19 +54,25 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.requestMatchers().anyRequest()
.and()
.authorizeRequests()
.antMatchers("/oauth/**", "/acc/**").permitAll();
.requestMatchers().anyRequest()
.and()
.authorizeRequests()
.antMatchers("/oauth/**", "/acc/**").permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(passwordAuthenticationProvider());
auth.authenticationProvider(passwordAuthenticationProvider())
.authenticationProvider(verifyCodeAuthenticationProvider());
}
@Bean
public AuthenticationProvider passwordAuthenticationProvider() {
return new PasswordAuthenticationProvider(myUserDetailsService(), sysConfService);
}
@Bean
public AuthenticationProvider verifyCodeAuthenticationProvider() {
return new VerifyCodeAuthenticationProvider(myUserDetailsService(), phoneBlackService);
}
}

View File

@@ -2,17 +2,24 @@ package com.accompany.oauth2.constant;
/**
* 授权类型
*
* @author anonym
* @date 2019/7/30 16:02
*/
public enum GrantTypeEnum {
PASSWORD("password"),
REFRESH_TOKEN("refresh_token"),
OPENID("openid"),
APPLE("apple");
private String value;
REFRESH_TOKEN("refresh_token"),
OPENID("openid"),
APPLE("apple"),
VERIFY_CODE("verify_code"),
;
private final String value;
GrantTypeEnum(String value) {
this.value = value;

View File

@@ -9,12 +9,13 @@ import org.springframework.security.core.userdetails.UserDetailsService;
public interface MyUserDetailsService extends UserDetailsService {
UserDetails loadUserByPhone(String phone,String phoneAreaCode, String smsCode, DeviceInfo deviceInfo, String ipAddress) throws Exception;
UserDetails loadUserByPhone(String phone, String phoneAreaCode, String smsCode, DeviceInfo deviceInfo, String ipAddress) throws Exception;
UserDetails loadUserByOpenId(String openid, Byte type, DeviceInfo deviceInfo, String ipAddress, String unionId) throws Exception;
void login(String reqUserName, UserDetails userDetails, LoginTypeEnum loginTypeEnum, DeviceInfo deviceInfo,
String ip, String openId, String unionId, String smsCode) throws Exception;
void login(String reqUserName, UserDetails userDetails, LoginTypeEnum loginTypeEnum, DeviceInfo deviceInfo, String smsCode) throws Exception;
void login(String reqUserName, UserDetails userDetails, LoginTypeEnum loginTypeEnum, DeviceInfo deviceInfo, String ip, String openId, String unionId, String smsCode) throws Exception;
Boolean logout(String accessToken);

View File

@@ -1,5 +1,6 @@
package com.accompany.oauth2.service;
import cn.hutool.core.util.StrUtil;
import com.accompany.common.constant.AppEnum;
import com.accompany.common.constant.Constant;
import com.accompany.common.device.DeviceInfo;
@@ -23,6 +24,7 @@ import com.accompany.oauth2.exception.CustomOAuth2Exception;
import com.accompany.oauth2.model.AccountDetails;
import com.accompany.oauth2.service.account.AccountBlockCheckService;
import com.accompany.oauth2.service.account.AccountManageService;
import com.accompany.oauth2.util.RequestContextHolderUtils;
import com.accompany.sms.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
@@ -80,7 +82,7 @@ public class MyUserDetailsServiceImpl implements MyUserDetailsService {
} else if (CommonUtil.checkNumberOnly(username)) {
account = accountService.getAccountByErBanNo(Long.valueOf(username));
}
if(account == null){
if (account == null) {
throw new CustomOAuth2Exception(CustomOAuth2Exception.USER_NOT_EXISTED,
OAuthStatus.USER_NOT_EXISTED.getReasonPhrase());
}
@@ -88,12 +90,12 @@ public class MyUserDetailsServiceImpl implements MyUserDetailsService {
}
@Override
public UserDetails loadUserByPhone(String phone,String phoneAreaCode, String smsCode, DeviceInfo deviceInfo, String ipAddress)
public UserDetails loadUserByPhone(String phone, String phoneAreaCode, String smsCode, DeviceInfo deviceInfo, String ipAddress)
throws Exception {
Account account = null;
log.info("phone:{}, phoneAreaCode:{}, smsCode:{}, deviceInfo:{}, ipAddress:{}",phone,phoneAreaCode,smsCode,deviceInfo,ipAddress);
if (CommonUtil.checkPhoneFormat(phoneAreaCode,phone)) {
account = accountManageService.getOrGenAccountByPhone(phone,phoneAreaCode,smsCode,deviceInfo,ipAddress);
log.info("phone:{}, phoneAreaCode:{}, smsCode:{}, deviceInfo:{}, ipAddress:{}", phone, phoneAreaCode, smsCode, deviceInfo, ipAddress);
if (CommonUtil.checkPhoneFormat(phoneAreaCode, phone)) {
account = accountManageService.getOrGenAccountByPhone(phone, phoneAreaCode, smsCode, deviceInfo, ipAddress);
} else if (CommonUtil.checkNumberOnly(phone)) {
account = accountService.getAccountByErBanNo(Long.valueOf(phone));
}
@@ -107,28 +109,31 @@ public class MyUserDetailsServiceImpl implements MyUserDetailsService {
@Override
public UserDetails loadUserByOpenId(String openid, Byte type, DeviceInfo deviceInfo, String ipAddress, String unionId) throws Exception {
Account account = accountManageService.getOrGenAccountByOpenid(openid, type, deviceInfo, ipAddress, unionId);
if(account == null) {
if (account == null) {
throw new CustomOAuth2Exception(CustomOAuth2Exception.USER_NOT_EXISTED,
OAuthStatus.USER_NOT_EXISTED.getReasonPhrase());
}
return new AccountDetails(account);
}
@Override
public void login(String reqUserName, UserDetails userDetails, LoginTypeEnum loginTypeEnum, DeviceInfo deviceInfo, String smsCode) throws Exception {
login(reqUserName, userDetails, loginTypeEnum, deviceInfo, RequestContextHolderUtils.getRemoteAddr(), StrUtil.EMPTY, StrUtil.EMPTY, smsCode);
}
@Override
public void login(String reqUserName, UserDetails userDetails, LoginTypeEnum loginType, DeviceInfo deviceInfo,
String ip, String openId, String unionId, String smsCode) throws Exception {
AccountDetails details = (AccountDetails)userDetails;
AccountDetails details = (AccountDetails) userDetails;
Account account = details.getAccount();
String deviceId = deviceInfo.getDeviceId();
Long uid = account.getUid();
Date date = new Date();
// 拦截指定账号登录
Users users = usersBaseService.getUsersByUid(account.getUid());
if (users != null && NEED_INTERCEPT_USER_TYPE.contains(users.getDefUser())) {
throw new ServiceException(BusiStatus.ILLEGAL_OPERATE);
}
//检查账号是否封禁
accountBlockCheckService.checkBlockedAccount(account);
//检查设备是否封禁
@@ -139,13 +144,9 @@ public class MyUserDetailsServiceImpl implements MyUserDetailsService {
if (phoneBlackService.checkIsNeedIntercept(account.getPhone())) {
throw new ServiceException(BusiStatus.PHONE_BE_INTERCEPTED);
}
//检查账号
// checkoutAccountType(account, reqUserName, loginType);
//校验验证码
checkSmsCodeByUserType(account,smsCode,loginType, deviceInfo.getApp());
checkSmsCodeByUserType(account, smsCode, loginType, deviceInfo.getApp());
accountManageService.checkAccountCancel(uid);
//更新account信息
String newToken = accountService.refreshAndGetNetEaseToken(account);
account.setNeteaseToken(newToken);
@@ -165,7 +166,6 @@ public class MyUserDetailsServiceImpl implements MyUserDetailsService {
accountService.updateById(account);
//更新用户正在使用的app字段
userAppService.updateCurrentApp(uid, deviceInfo.getApp());
//将用户信息登记
AccountLoginRecord accountLoginRecord = buildAccountLoginRecord(ip, account, loginType.getValue(), deviceInfo, openId);
loginRecordService.addAccountLoginRecordAsync(accountLoginRecord);
@@ -187,13 +187,13 @@ public class MyUserDetailsServiceImpl implements MyUserDetailsService {
accountLoginRecord.setOsversion(deviceInfo.getOsVersion());
accountLoginRecord.setCreateTime(new Date());
if(loginType == LoginTypeEnum.WECHAT.getValue()){
if (loginType == LoginTypeEnum.WECHAT.getValue()) {
accountLoginRecord.setWeixinOpenid(openId);
}
if(loginType == LoginTypeEnum.QQ.getValue()){
if (loginType == LoginTypeEnum.QQ.getValue()) {
accountLoginRecord.setQqOpenid(openId);
}
if (loginType == LoginTypeEnum.APPLE.getValue()){
if (loginType == LoginTypeEnum.APPLE.getValue()) {
accountLoginRecord.setAppleUid(openId);
}
return accountLoginRecord;
@@ -207,48 +207,49 @@ public class MyUserDetailsServiceImpl implements MyUserDetailsService {
}
OAuth2Authentication authentication = tokenStore.readAuthentication(accessToken);
UserDetails userDetails = loadUserByUsername(authentication.getName());
AccountDetails accountDetails = userDetails instanceof AccountDetails ? (AccountDetails)userDetails : null;
if(accountDetails == null){
AccountDetails accountDetails = userDetails instanceof AccountDetails ? (AccountDetails) userDetails : null;
if (accountDetails == null) {
return Boolean.FALSE;
}
Long uid = accountDetails.getAccount().getUid();
if(uid == null){
if (uid == null) {
return Boolean.FALSE;
}
log.info("user logout. uid: {}", uid);
tokenServices.revokeToken(tokenValue);
jedisService.hwrite(RedisKey.uid_access_token.getKey(),uid.toString(),"");
jedisService.hwrite(RedisKey.uid_ticket.getKey(),uid.toString(),"");
jedisService.hwrite(RedisKey.uid_access_token.getKey(), uid.toString(), "");
jedisService.hwrite(RedisKey.uid_ticket.getKey(), uid.toString(), "");
return Boolean.TRUE;
}
/**
* 普通用户需要用手机验证码登录,官方账号和公会账号不校验验证码
*
* @param account
* @param smsCode
* @param appName
*/
private void checkSmsCodeByUserType(Account account, String smsCode, LoginTypeEnum loginType, String appName){
private void checkSmsCodeByUserType(Account account, String smsCode, LoginTypeEnum loginType, String appName) {
//是否手机号登录
Boolean isPhone = LoginTypeEnum.ID.getValue() == loginType.getValue();
if(!isPhone){
if (!isPhone) {
return;
}
if(StringUtils.isEmpty(smsCode)){
if (StringUtils.isEmpty(smsCode)) {
throw new CustomOAuth2Exception(CustomOAuth2Exception.VERIFY_CODE_ERROR,
BusiStatus.VERIFY_CODE_ERROR.getReasonPhrase());
}
Users users = usersBaseService.getUsersByUid(account.getUid());
if(users != null && users.getDefUser().byteValue() == Constant.DefUser.LABOR_UNION
if (users != null && users.getDefUser().byteValue() == Constant.DefUser.LABOR_UNION
&& (AppEnum.yinyou.getValue().equals(appName) || AppEnum.yinyouEnterprise.getValue().equals(appName))) {
String checkCode = sysConfService.getSysConfValueById(Constant.SysConfId.LABOR_USER_CHECK_CODE);
if(!smsCode.equalsIgnoreCase(checkCode)){
if (!smsCode.equalsIgnoreCase(checkCode)) {
throw new CustomOAuth2Exception(CustomOAuth2Exception.VERIFY_CODE_ERROR,
BusiStatus.VERIFY_CODE_ERROR.getReasonPhrase());
}
}else if(!smsService.verifySmsCode(account.getPhone(), smsCode)){
} else if (!smsService.verifySmsCode(account.getPhone(), smsCode)) {
throw new CustomOAuth2Exception(CustomOAuth2Exception.VERIFY_CODE_ERROR,
BusiStatus.VERIFY_CODE_ERROR.getReasonPhrase());
}

View File

@@ -1,4 +1,4 @@
package com.accompany.oauth2.support;
package com.accompany.oauth2.support.password;
import com.accompany.common.constant.Constant;
import com.accompany.common.device.DeviceInfo;
@@ -35,7 +35,7 @@ import java.util.Map;
* Created by PaperCut on 2018/8/6.
* 账号密码校验规则
*/
public class PasswordAuthenticationProvider implements AuthenticationProvider{
public class PasswordAuthenticationProvider implements AuthenticationProvider {
private static final Logger logger = LoggerFactory.getLogger(PasswordAuthenticationProvider.class);
@@ -54,7 +54,7 @@ public class PasswordAuthenticationProvider implements AuthenticationProvider{
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Map params = (Map) authentication.getDetails();
Map<?, ?> params = (Map<?, ?>) authentication.getDetails();
String smsCode = (String) params.get("code");
String phoneAreaCode = (String) params.get("phoneAreaCode");
String ipAddress = RequestContextHolderUtils.getRemoteAddr();
@@ -73,7 +73,7 @@ public class PasswordAuthenticationProvider implements AuthenticationProvider{
}
}
} catch (Exception e) {
throw new CustomOAuth2Exception(CustomOAuth2Exception.ACCOUNT_ERROR,
throw new CustomOAuth2Exception(CustomOAuth2Exception.ACCOUNT_ERROR,
OAuthStatus.ACCOUNT_ERROR.getReasonPhrase());
}
String password = (String) authentication.getCredentials();
@@ -83,12 +83,10 @@ public class PasswordAuthenticationProvider implements AuthenticationProvider{
} else if (StringUtils.isNotBlank(password)) {
loginTypeEnum = LoginTypeEnum.PASSWORD;
}
// 低于1.5版本不能进行登录
String limitAppVersion = sysConfService.getDefaultSysConfValueById(Constant.SysConfId.APP_VERSION_LIMIT, Constant.LOWEST_VERSION_FOR_USE);
if (deviceInfo.getAppVersion() == null || AppVersionUtil.compareVersion(deviceInfo.getAppVersion(), limitAppVersion) < 0) {
throw new CustomOAuth2Exception(CustomOAuth2Exception.APP_VERSION_TOO_OLD,
OAuthStatus.APP_VERSION_TOO_OLD.getReasonPhrase());
throw new CustomOAuth2Exception(CustomOAuth2Exception.APP_VERSION_TOO_OLD, OAuthStatus.APP_VERSION_TOO_OLD.getReasonPhrase());
}
if (phoneBlackService.checkIsNeedIntercept(username)) {
throw new CustomOAuth2Exception(CustomOAuth2Exception.PHONE_BE_INTERCEPTED,
@@ -96,7 +94,8 @@ public class PasswordAuthenticationProvider implements AuthenticationProvider{
}
UserDetails userDetails;
try {
userDetails = myUserDetailsService.loadUserByPhone(username,phoneAreaCode, smsCode, deviceInfo, ipAddress);
userDetails = myUserDetailsService.loadUserByPhone(username, phoneAreaCode, smsCode, deviceInfo, ipAddress);
assert loginTypeEnum != null;
if (LoginTypeEnum.PASSWORD.getValue() == loginTypeEnum.getValue()) {
try {
password = DESUtils.DESAndBase64Decrypt(password, KeyStore.DES_ENCRYPT_KEY);
@@ -124,6 +123,7 @@ public class PasswordAuthenticationProvider implements AuthenticationProvider{
/**
* 处理密码登录
*
* @param username 用户登录账号
* @return 错误提示
*/

View File

@@ -1,4 +1,4 @@
package com.accompany.oauth2.support;
package com.accompany.oauth2.support.password;
import com.accompany.oauth2.constant.GrantTypeEnum;
import com.accompany.oauth2.service.account.SuperAdminGrantService;

View File

@@ -0,0 +1,70 @@
package com.accompany.oauth2.support.verify;
import cn.hutool.core.util.StrUtil;
import com.accompany.common.device.DeviceInfo;
import com.accompany.core.service.user.PhoneBlackService;
import com.accompany.oauth2.constant.LoginTypeEnum;
import com.accompany.oauth2.constant.OAuthStatus;
import com.accompany.oauth2.exception.CustomOAuth2Exception;
import com.accompany.oauth2.service.MyUserDetailsService;
import com.accompany.oauth2.util.RequestContextHolderUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import java.util.Collections;
import java.util.Map;
/**
* @author: liaozetao
* @date: 2023/7/11 10:47
* @description:
*/
@Slf4j
public class VerifyCodeAuthenticationProvider implements AuthenticationProvider {
private static final String PHONE_AREA_CODE = "phoneAreaCode";
private final MyUserDetailsService userDetailsService;
private final PhoneBlackService phoneBlackService;
public VerifyCodeAuthenticationProvider(MyUserDetailsService userDetailsService, PhoneBlackService phoneBlackService) {
this.userDetailsService = userDetailsService;
this.phoneBlackService = phoneBlackService;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Map<?, ?> params = (Map<?, ?>) authentication.getDetails();
String phone = authentication.getName();
String code = (String) authentication.getCredentials();
String phoneAreaCode = (String) params.get(PHONE_AREA_CODE);
DeviceInfo deviceInfo = new DeviceInfo();
try {
BeanUtils.populate(deviceInfo, params);
} catch (Exception e) {
log.error("populate deviceInfo fail", e);
}
if (phoneBlackService.checkIsNeedIntercept(phone)) {
throw new CustomOAuth2Exception(CustomOAuth2Exception.PHONE_BE_INTERCEPTED, OAuthStatus.PHONE_BE_INTERCEPTED.getReasonPhrase());
}
UserDetails userDetails = null;
try {
userDetails = userDetailsService.loadUserByPhone(phone, phoneAreaCode, code, deviceInfo, RequestContextHolderUtils.getRemoteAddr());
userDetailsService.login(phone, userDetails, LoginTypeEnum.ID, deviceInfo, code);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return new VerifyCodeAuthenticationToken(userDetails, Collections.emptyList());
}
@Override
public boolean supports(Class<?> aClass) {
return VerifyCodeAuthenticationToken.class.isAssignableFrom(aClass);
}
}

View File

@@ -0,0 +1,19 @@
package com.accompany.oauth2.support.verify;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
/**
* @author: liaozetao
* @date: 2023/7/11 10:45
* @description:
*/
public class VerifyCodeAuthenticationToken extends UsernamePasswordAuthenticationToken {
protected static final String PHONE = "phone";
protected static final String CODE = "code";
public VerifyCodeAuthenticationToken(Object principal, Object credentials) {
super(principal, credentials);
}
}

View File

@@ -0,0 +1,44 @@
package com.accompany.oauth2.support.verify;
import com.accompany.oauth2.constant.GrantTypeEnum;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import java.util.Map;
/**
* @author: liaozetao
* @date: 2023/7/11 10:48
* @description:
*/
public class VerifyCodeTokenGranter extends AbstractTokenGranter {
private final AuthenticationManager authenticationManager;
public VerifyCodeTokenGranter(AuthenticationManager authenticationManager,
AuthorizationServerTokenServices tokenServices,
ClientDetailsService clientDetailsService,
OAuth2RequestFactory requestFactory) {
super(tokenServices, clientDetailsService, requestFactory, GrantTypeEnum.VERIFY_CODE.getValue());
this.authenticationManager = authenticationManager;
}
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
Map<String, String> parameters = tokenRequest.getRequestParameters();
String phone = parameters.get(VerifyCodeAuthenticationToken.PHONE);
String code = parameters.get(VerifyCodeAuthenticationToken.CODE);
VerifyCodeAuthenticationToken token = new VerifyCodeAuthenticationToken(phone, code);
token.setDetails(parameters);
Authentication authentication = authenticationManager.authenticate(token);
if (authentication == null || !authentication.isAuthenticated()) {
throw new InvalidGrantException("Could not authenticate user: " + phone);
}
OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
return new OAuth2Authentication(storedOAuth2Request, authentication);
}
}