Oauth2密码模式登录增加验证码判断功能

198 阅读1分钟

在授权服务器的configure(AuthorizationServerEndpointsConfigurer endpoints)方法中作以下配置

 DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(this.myUserDetailsService);
        provider.setPasswordEncoder(this.passwordEncoder);
        
                AuthenticationManager authenticationManager = new AuthenticationManager(){

            @Override
            public Authentication authenticate(Authentication authentication) throws AuthenticationException {

                if (authentication.getDetails() != null && authentication.getDetails() instanceof Map) {
                //这里可以拿到/oauth/token请求中的参数
                    Map<String, String> parameters = (Map<String, String>) authentication.getDetails();
                    
                    String code = parameters.get("code");
                    String uuid = parameters.get("uuid");
                    if (code.equals(redisUtil.get(uuid))){
                        authentication = provider.authenticate(authentication);
                    }else{
                        throw new InvalidGrantException("验证码错误");
                    }

                }
                return authentication;
            }
        };
        
        
        endpoints.authenticationManager(authenticationManager)