Spring Security oauth2客户端-如何获取JWT令牌

时间:2018-08-02 00:22:58

标签: spring-security microsoft-graph

我正在尝试使用 spring-security-oauth2-client spring-security-oauth2-jose 对Azure AD进行身份验证并获取JWT令牌。 登录部分有效,但是我收到的令牌不是JWT。这是我的配置:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;


@Override
protected void configure(HttpSecurity http) throws Exception {
    http
    .authorizeRequests()
    .anyRequest()
    .authenticated()
    .and()
    .oauth2Login()
    .loginPage("/oauth2/authorization/azure")
    .userInfoEndpoint()
    .oidcUserService(oidcUserService);
}

}

经过身份验证后,我从安全上下文中检索令牌,如下所示:

OAuth2AuthenticationToken authentication = (OAuth2AuthenticationToken) 
SecurityContextHolder.getContext().getAuthentication();
OAuth2AccessToken accessToken = authorizedClientService.loadAuthorizedClient(
            authentication.getAuthorizedClientRegistrationId()
            ,authentication.getName()
            ).getAccessToken();

我得到了一个无记名令牌,看起来像:

“AQABAAAAAADXzZ3ifr-GRbDT45zNSEFElTInSJQ19I2zONWkrBPgoKf8MCYL_z_IzU2lmF_ZadgBMdCr337faL0bpqHAzmFhsxq8peWUX7iYeTLbmcHDIdCR617VSKKHISLn_AiXhNr9rF6AMSrQTzdV2mKhEVlycTXlHUsZkA-gMA4z4FQFQMYkFNcLKqr7b-NewnV07lbG55joRIkcCMDrM1s4X8mRcJpRF6ek1yNSpveFmlbkrt3cXPUqtDe5EWI_5gfuGEVIon57LFLos_JtcQWSL6CTrUlY8EuF8MVuwJpTNG3OR80ikK7ycH_dXFCYmYDRrtTbFkf3R61aDSnqEUe2IIl2T8QdqWqH65ykSVooG6uIi5KsRK9zXPRuRuC_XC5w6SCcGionQYIgSEp-kCtIzlfHIBRK2o_CpjYVMBdmbfIkCvFoTGGGAvpOP1_MkgVeBiQzYFg8m_dn_roXFF17oBhCdYrZ2Y41_-GngLU3VJj4ltFIxzRziH6CZ2aFl1N3MwzIUcTiN6Ci0oyODTsSNDPc2zvxg609SjEqrO-6Xp0LMEwiOgY5L5rrcLA5d4LN-Xq9NiG0KqybZPU7wW0AHNA2Nw7bSg1Cle0ReaBU4ANbkjHxYeQJf65-ONNMGdfkV8xlKtRXZoiOBFip87Z72cS4NjLjM3x9_Qk9MQ5eGQTNj4fHCzJp9ukcjQ1MSUol_VIgAA “

然后,Microsoft Graph API拒绝其中的哪个。任何帮助或建议,我们将不胜感激。

2 个答案:

答案 0 :(得分:1)

您还可以从Authentication对象获取ID令牌。您需要将authentication.principal强制转换为OidcUser。 OidcUser为您提供用户的完整详细信息。

            OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
        OAuth2AuthorizedClient client = 
                clientService.loadAuthorizedClient(
                        oauthToken.getAuthorizedClientRegistrationId(),
                        oauthToken.getName());


    if (authentication.getPrincipal() instanceof OidcUser) {
            OidcUser principal = ((OidcUser) authentication.getPrincipal());
            idToken = principal.getIdToken().getTokenValue();
        }

答案 1 :(得分:0)

我能够找到解决方案。您得到的是返回的授权码。要获取访问令牌,请使用以下命令:

public void getToken(OAuth2AuthenticationToken oAuth2AuthenticationToken, @AuthenticationPrincipal(expression = "idToken") OidcIdToken idToken) {

System.out.println(idToken);

}