用于访问资源服务器的Spring OAuth2RestTemplate给出401未经授权

时间:2019-07-17 06:39:54

标签: spring-security oauth-2.0 spring-security-oauth2 azure-ad-graph-api

我试图使用authorization_code授予类型的O​​Auth2Client,我可以授权用户并重定向url,但是当我尝试使用OAuth2RestTemplate访问资源时,我得到401 UnAuthorized 我需要为OAuth2RestTemplate做些什么来添加Authorization标头吗?我以为Spring-oauth2会自行将标头添加到OAuthRestTemplate

也已通过TRACE日志验证

@GetMapping("/")
    public OAuth2User hello(@AuthenticationPrincipal OAuth2User oAuth2User){
        logger.info("User="+oAuth2User.getAttributes().get("unique_name"));
        String response = oAuth2RestTemplate.getForObject("https://localhost:8090/me", String.class);
        return oAuth2User;
    }


@Bean
    public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext) {
        return new OAuth2RestTemplate(azureDetails(),oauth2ClientContext);
    }

 @Bean
    public AuthorizationCodeResourceDetails azureDetails() {
        AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
        details.setClientId("myclientId");
        details.setClientSecret("myclientsecret");
        details.setAccessTokenUri("https://login.microsoftonline.com/common/oauth2/token");
        details.setUserAuthorizationUri("https://login.microsoftonline.com/common/oauth2/authorize");
details.setScope(Arrays.asList("openid","profile","User.Read","Calendars.Read","Chat.Read","Files.Read","Mail.Read","Notes.Read","Tasks.Read"));
        return details;
    }

OAuth2RestTemplate应该在MS Graph API上执行GET并获取响应

1 个答案:

答案 0 :(得分:1)

您需要更新AccessTokenUri和UserAuthorizationUri,AccessTokenUri应该为https://login.microsoftonline.com/common/oauth2/v2.0/token,而UserAuthorizationUri应该为https://login.microsoftonline.com/common/oauth2/v2.0/authorize。有关更多详细信息,请参阅https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow