当前位置:网站首页>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 补充
边栏推荐
猜你喜欢
随机推荐
内存和硬盘、磁盘的区别
面试汇总
lua编程
OpenPose 命令行说明
Unity-编辑器扩展(Editor)
Oauth2.0 资源服务器搭建
Unity-Post Processing
【线程安全】用户级,内核级,组合级线程|线程同步的处理(条件变量)|strtok_r(可冲入函数)
tpproxy-tcp透明代理
深入理解负载均衡
MMD->Unity一站式解决方案
Unity-存档与读档
Manifest merger failed : Attribute [email protected] value=
泰伯效应的建模
5款最好用的免费3D建模软件(附下载链接)
Unity-PlayMaker
记一次 ThreadLocal 泄漏导致的 shardingsphere-jdbc-core 单元测试偶发失败的排查与修复
剑指offer:在O(1)时间删除链表结点
Class template/assignment operations and add operations
mininet multihomed topology









