Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring OAuth2RestTemplate for accessing resource server gives 401 Unauthorized

I m trying to have an OAuth2Client using authorization_code grant type, I can authorize the user and redirect the url, but when I try to access the resource using OAuth2RestTemplate, I get 401 UnAuthorized Is there something I need to do for the OAuth2RestTemplate to add the Authorization header ? I thought Spring-oauth2 will take care of adding the headers to OAuthRestTemplate by itself

Verified with TRACE logging as well

@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 should do a GET on MS Graph API and get the response

like image 352
Sudhakar Betha Avatar asked Jan 28 '26 22:01

Sudhakar Betha


1 Answers

You need to update your AccessTokenUri and UserAuthorizationUri, your AccessTokenUri should be https://login.microsoftonline.com/common/oauth2/v2.0/tokenand your UserAuthorizationUri should be https://login.microsoftonline.com/common/oauth2/v2.0/authorize. For more details, please refer to https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow.

like image 190
Md Farid Uddin Kiron Avatar answered Jan 31 '26 02:01

Md Farid Uddin Kiron