当前位置: 正能量 » 代码编程 » Java » Spring OAuth2 Client通过code获取AccessToken

Spring OAuth2 Client通过code获取AccessToken

记录一下代码:
OAuth2ClientTest.java


@Slf4j
@Component
public class OAuth2ClientTest implements InitializingBean {

    @Autowired
    private ClientRegistrationRepository clientRegistrationRepository;
    @Autowired
    private OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient;

    public OAuth2AccessTokenResponse getAccessToken(String authorizationCode) {

        ClientRegistration renaultClient = clientRegistrationRepository.findByRegistrationId("demo");

        String code=PKCEUtil.generateCodeVerifier();

        Map<String,Object> params= Maps.newHashMap();
       //如果用了PKCE,则记得删除client_secret params.put(PkceParameterNames.CODE_CHALLENGE,PKCEUtil.generateCodeChallenge(code));
        params.put(PkceParameterNames.CODE_VERIFIER,code);
        params.put(PkceParameterNames.CODE_CHALLENGE_METHOD,"S256");

        OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
                .clientId(renaultClient.getClientId())
                .authorizationUri(renaultClient.getProviderDetails().getAuthorizationUri())
                .redirectUri(renaultClient.getRedirectUri())
                .attributes(params)
                .build();

        OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponse.success(authorizationCode)
                .redirectUri(renaultClient.getRedirectUri())
                .build();

        OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse);

        OAuth2AuthorizationCodeGrantRequest grantRequest = new OAuth2AuthorizationCodeGrantRequest(renaultClient, authorizationExchange);

        log.info(JSONUtil.toJsonStr(grantRequest));
        return accessTokenResponseClient.getTokenResponse(grantRequest);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        //示例code,实际应该是auth server返回的
        getAccessToken("abc");
    }
}

PKCEUtil.java

public class PKCEUtil {

    private static final SecureRandom SECURE_RANDOM = new SecureRandom();

    public static String generateCodeVerifier() {
        byte[] codeVerifier = new byte[32];
        SECURE_RANDOM.nextBytes(codeVerifier);
        return Base64.encodeBase64URLSafeString(codeVerifier);
    }

    public static String generateCodeChallenge(String codeVerifier) {
        byte[] digest = DigestUtils.sha256(codeVerifier);
        return Base64.encodeBase64URLSafeString(digest);
    }
}
未经允许不得转载:正能量 » Spring OAuth2 Client通过code获取AccessToken

相关文章

评论 (0)

7 + 2 =