CaptchaAuthenticationProvider.java 9.3 KB
Newer Older
1
package com.youlai.auth.authentication.captcha;
2 3

import cn.hutool.core.lang.Assert;
4
import cn.hutool.core.util.ReflectUtil;
5
import cn.hutool.core.util.StrUtil;
6
import com.youlai.auth.util.OAuth2AuthenticationProviderUtils;
7
import com.youlai.common.constant.SecurityConstants;
8
import lombok.extern.slf4j.Slf4j;
9
import org.springframework.data.redis.core.StringRedisTemplate;
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.core.*;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.OAuth2Authorization;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2AccessTokenAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.authentication.OAuth2ClientAuthenticationToken;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.context.AuthorizationServerContextHolder;
import org.springframework.security.oauth2.server.authorization.token.DefaultOAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;

import java.security.Principal;
29 30
import java.util.Collections;
import java.util.Map;
31 32

/**
33
 * 验证码模式身份验证提供者
34 35 36 37 38 39
 * <p>
 * 处理基于用户名和密码的身份验证
 *
 * @author haoxr
 * @see org.springframework.security.oauth2.server.authorization.authentication.OAuth2AuthorizationCodeAuthenticationProvider
 * @since 3.0.0
40 41
 */
@Slf4j
42
public class CaptchaAuthenticationProvider implements AuthenticationProvider {
43 44 45 46 47

    private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-5.2";
    private final AuthenticationManager authenticationManager;
    private final OAuth2AuthorizationService authorizationService;
    private final OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator;
48
    private final StringRedisTemplate redisTemplate;
49 50 51 52 53 54 55 56 57

    /**
     * Constructs an {@code OAuth2ResourceOwnerPasswordAuthenticationProviderNew} using the provided parameters.
     *
     * @param authenticationManager the authentication manager
     * @param authorizationService  the authorization service
     * @param tokenGenerator        the token generator
     * @since 0.2.3
     */
58 59 60
    public CaptchaAuthenticationProvider(AuthenticationManager authenticationManager,
                                         OAuth2AuthorizationService authorizationService,
                                         OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator,
61
                                         StringRedisTemplate redisTemplate
62 63 64 65 66 67
    ) {
        Assert.notNull(authorizationService, "authorizationService cannot be null");
        Assert.notNull(tokenGenerator, "tokenGenerator cannot be null");
        this.authenticationManager = authenticationManager;
        this.authorizationService = authorizationService;
        this.tokenGenerator = tokenGenerator;
68
        this.redisTemplate = redisTemplate;
69 70 71 72 73
    }

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

74
        CaptchaAuthenticationToken captchaAuthenticationToken = (CaptchaAuthenticationToken) authentication;
75
        OAuth2ClientAuthenticationToken clientPrincipal = OAuth2AuthenticationProviderUtils
76
                .getAuthenticatedClientElseThrowInvalidClient(captchaAuthenticationToken);
77 78
        RegisteredClient registeredClient = clientPrincipal.getRegisteredClient();

79
        // 验证客户端是否支持授权类型(grant_type=password)
80
        if (!registeredClient.getAuthorizationGrantTypes().contains(CaptchaAuthenticationToken.CAPTCHA)) {
81 82 83
            throw new OAuth2AuthenticationException(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT);
        }

84 85 86 87 88
        // 证码校验
        Map<String, Object> additionalParameters = captchaAuthenticationToken.getAdditionalParameters();
        String verifyCode = (String) additionalParameters.get(CaptchaParameterNames.VERIFY_CODE);
        String verifyCodeKey = (String) additionalParameters.get(CaptchaParameterNames.VERIFY_CODE_KEY);

89
        String cacheCode = redisTemplate.opsForValue().get(SecurityConstants.VERIFY_CODE_KEY_PREFIX + verifyCodeKey);
90 91 92 93
        if (!StrUtil.equals(verifyCode, cacheCode)) {
            throw new OAuth2AuthenticationException("验证码错误");
        }

94
        // 生成用户名密码身份验证令牌
95 96
        String username = (String) additionalParameters.get(OAuth2ParameterNames.USERNAME);
        String password = (String) additionalParameters.get(OAuth2ParameterNames.PASSWORD);
97
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password);
98
        // 用户名密码身份验证,成功后返回 带有权限的认证信息
99
        Authentication usernamePasswordAuthentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
100

101
        // 访问令牌(Access Token) 构造器
102 103
        DefaultOAuth2TokenContext.Builder tokenContextBuilder = DefaultOAuth2TokenContext.builder()
                .registeredClient(registeredClient)
104
                .principal(usernamePasswordAuthentication) // 身份验证成功的认证信息(用户名、权限等信息)
105
                .authorizationServerContext(AuthorizationServerContextHolder.getContext())
106 107
                .authorizationGrantType(CaptchaAuthenticationToken.CAPTCHA) // 授权方式
                .authorizationGrant(captchaAuthenticationToken) // 授权具体对象
108
                ;
109

110 111
        // 生成访问令牌(Access Token)
        OAuth2TokenContext tokenContext = tokenContextBuilder.tokenType((OAuth2TokenType.ACCESS_TOKEN)).build();
112 113 114 115 116 117 118 119 120 121 122
        OAuth2Token generatedAccessToken = this.tokenGenerator.generate(tokenContext);
        if (generatedAccessToken == null) {
            OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR,
                    "The token generator failed to generate the access token.", ERROR_URI);
            throw new OAuth2AuthenticationException(error);
        }

        OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER,
                generatedAccessToken.getTokenValue(), generatedAccessToken.getIssuedAt(),
                generatedAccessToken.getExpiresAt(), tokenContext.getAuthorizedScopes());

123

124 125 126
        // 权限数据比较多通过反射移除不持久化至数据库
        ReflectUtil.setFieldValue(usernamePasswordAuthentication.getPrincipal(), "perms", null);

127 128
        OAuth2Authorization.Builder authorizationBuilder = OAuth2Authorization.withRegisteredClient(registeredClient)
                .principalName(usernamePasswordAuthentication.getName())
129
                .authorizationGrantType(CaptchaAuthenticationToken.CAPTCHA)
130 131 132 133 134 135 136 137
                .attribute(Principal.class.getName(), usernamePasswordAuthentication);
        if (generatedAccessToken instanceof ClaimAccessor) {
            authorizationBuilder.token(accessToken, (metadata) ->
                    metadata.put(OAuth2Authorization.Token.CLAIMS_METADATA_NAME, ((ClaimAccessor) generatedAccessToken).getClaims()));
        } else {
            authorizationBuilder.accessToken(accessToken);
        }

138
        // 生成刷新令牌(Refresh Token)
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
        OAuth2RefreshToken refreshToken = null;
        if (registeredClient.getAuthorizationGrantTypes().contains(AuthorizationGrantType.REFRESH_TOKEN) &&
                // Do not issue refresh token to public client
                !clientPrincipal.getClientAuthenticationMethod().equals(ClientAuthenticationMethod.NONE)) {

            tokenContext = tokenContextBuilder.tokenType(OAuth2TokenType.REFRESH_TOKEN).build();
            OAuth2Token generatedRefreshToken = this.tokenGenerator.generate(tokenContext);
            if (!(generatedRefreshToken instanceof OAuth2RefreshToken)) {
                OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR,
                        "The token generator failed to generate the refresh token.", ERROR_URI);
                throw new OAuth2AuthenticationException(error);
            }

            refreshToken = (OAuth2RefreshToken) generatedRefreshToken;
            authorizationBuilder.refreshToken(refreshToken);
        }

        OAuth2Authorization authorization = authorizationBuilder.build();
157
        // 持久化令牌发放记录到数据库
158
        this.authorizationService.save(authorization);
159
        additionalParameters = Collections.EMPTY_MAP;
160 161 162 163 164
        return new OAuth2AccessTokenAuthenticationToken(registeredClient, clientPrincipal, accessToken, refreshToken, additionalParameters);
    }

    @Override
    public boolean supports(Class<?> authentication) {
165
        return CaptchaAuthenticationToken.class.isAssignableFrom(authentication);
166 167 168
    }

}