当前位置:网站首页>Oauth2.0 authentication server adds verification code login method
Oauth2.0 authentication server adds verification code login method
2022-08-02 16:04:00 【zhangyu,】
发送验证码
@RestController
@AllArgsConstructor
@RequestMapping
public class LoginController {
private final RedisTemplate<String, String> redisTemplate;
@GetMapping(value = "captcha/{phone}")
public R captcha(@PathVariable String phone) {
String captcha = randomCode();
redisTemplate.opsForValue().set(phone, captcha, 600, TimeUnit.SECONDS);
return R.ok(captcha);
}
private static String randomCode() {
Random random = new Random();
int code = random.nextInt(10000);
DecimalFormat format = new DecimalFormat("0000");
return format.format(code);
}
}
Login verification code verification filter CaptchaFilter
@Slf4j
@Component
@RequiredArgsConstructor
public class CaptchaFilter extends OncePerRequestFilter {
private final RedisTemplate<String, String> redisTemplate;
private final UserService userService;
private RequestMatcher requestMatcher = new AntPathRequestMatcher("/oauth/token", HttpMethod.POST.name());
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (requestMatcher.matches(request)) {
String grantType = request.getParameter("grant_type");
if (StrUtil.equalsIgnoreCase(grantType, "captcha")) {
try {
verifyCaptcha(request);
} catch (BusinessException e) {
log.error("The verification code of the login verification code is abnormal: {}, {}", e.getCode(), e.getMsg());
R.failRender(e.getCode(), e.getMsg(), response, HttpStatus.INTERNAL_SERVER_ERROR.value());
return;
}
}
}
filterChain.doFilter(request, response);
}
private void verifyCaptcha(HttpServletRequest request) throws ServletRequestBindingException {
String phone = ServletRequestUtils.getStringParameter(request, "username");
String captcha = ServletRequestUtils.getStringParameter(request, "password");
String cache = redisTemplate.opsForValue().get(phone);
if (Objects.isNull(cache) || !captcha.equals(cache)) {
throw new BusinessException("验证码校验异常");
}
}
}
Customize an authorization mode CaptchaTokenGranter
- 自定义验证码授权模式
- 配置到 AuthorizationServerConfig.tokenGranter()
- Add the configured authorization list to AuthorizationServerEndpointsConfigurer 中
public class CaptchaTokenGranter extends AbstractTokenGranter {
private static final String GRANT_TYPE = "captcha";
private UserDetailsServiceImpl userDetailsServiceImpl;
public CaptchaTokenGranter(AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory, UserDetailsServiceImpl userDetailsServiceImpl) {
super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
this.userDetailsServiceImpl = userDetailsServiceImpl;
}
@Override
protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
Map<String, String> requestParameters = tokenRequest.getRequestParameters();
String username = requestParameters.getOrDefault("username", "");
UserDetails userDetails = userDetailsServiceImpl.loadUserByUsername(username);
if (Objects.isNull(userDetails)) {
throw new UsernameNotFoundException("Username Not Found Exception");
}
// Build user authorization information
Authentication user = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),
userDetails.getPassword(), userDetails.getAuthorities());
return new OAuth2Authentication(tokenRequest.createOAuth2Request(client), user);
}
}
Add the defined authorization mode to the authentication server core configuration AuthorizationServerConfig in the endpoint configuration
AuthorizationServerConfig 其他配置已省略,详细见 Oauth2.0 认证服务器搭建
@Configuration
@EnableAuthorizationServer
@AllArgsConstructor
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
......
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenGranter(tokenGranter(endpoints)); //Configure the authorization method
}
/** * First obtain a list of the five existing authorizations,Then put a custom authorization method into it * * @param endpoints AuthorizationServerEndpointsConfigurer * @return TokenGranter */
private TokenGranter tokenGranter(final AuthorizationServerEndpointsConfigurer endpoints) {
List<TokenGranter> granters = new ArrayList<>(Collections.singletonList(endpoints.getTokenGranter()));
granters.add(new CaptchaTokenGranter(endpoints.getTokenServices(), endpoints.getClientDetailsService(),
endpoints.getOAuth2RequestFactory(), userDetailsServiceImpl));
return new CompositeTokenGranter(granters);
}
......
}
Oauth2.0 系列文章
以下是同步到语雀的、可读性好一点,CSDN 继续看的点专栏就好.
Oauth2.0 核心篇
Oauth2.0 安全性(以微信授权登陆为例)
Oauth2.0 认证服务器搭建
Oauth2.0 添加验证码登陆方式
Oauth2.0 资源服务器搭建
Oauth2.0 自定义响应值以及异常处理
Oauth2.0 补充
边栏推荐
猜你喜欢
随机推荐
【进程间通信】消息队列
创建系统还原点及恢复
Apache ShardingSphere 5.1.1 正式发布
Feign Client 超时时间配置不生效
冷读123
OpenPose run command ([email protected])
【Solidity智能合约基础】-- 基础运算与底层位运算
Problems related to prime numbers - small notes
net start mysql 服务名无效。
【无标题】
PostgreSQL 协议数据样例
Vert.x web 接收请求时反序列化对象 Failed to decode 如何解决?
深入理解负载均衡
OpenPose 基本理念
Unity-PlayMaker
OpenPose 运行指令 ([email protected])
The relationship between base classes and derived classes [inheritance] / polymorphism and virtual functions / [inheritance and polymorphism] abstract classes and simple factories
CDH (computational Diffie-Hellman) problem and its differences with discrete logarithm and DDH problems
从FAST TCP到POWERTCP
2. Log out, log in state examination, verification code









