Spring Auth0 getting "401 unauthorized"

I started w/ the tutorial available here:

I was able to get it to run fine and login. However I wanted to get the user info as well. I was going to use:
https://abmi.auth0.com/api/v2/users/auth0|5a9daf64c437954dda64df5b” as this works fine in postman.

I added some code to “HomeController.java” for a simple test:

When I use the token from the “Principal” I get
**** Exception: 401 Unauthorized**
when I attempt to access the api.

However when I use the Token from “Auth0 Management API” on the website and just paste it in, I can use the API fine.
Result - status:200 getbody:
(Telling me its something with the token or my Auth0 config that is wrong).

I am trying to get user info using:
“https://” + appConfig.getDomain() + “/api/v2/users/” + principal.getName();

Any help about why my token isnt working would be appreciated.
The sample code tells me it is good:

Hello com.auth0.example.security.TokenAuthentication@62fcd873: Principal: auth0|5a9daf64c437954dda64df5b; Credentials: [PROTECTED]; Authenticated: true; Details: null; Not granted any authorities!

Thanks in advance

I was able to fix it w/ the following (Sorry for format I haven’t done 2 posts yet so can’t preview).

    	MultiValueMap<String, String> parametersMap = new LinkedMultiValueMap<String, String>();
    	parametersMap.add("grant_type", "client_credentials");
    	parametersMap.add("client_id", appConfig.getClientId());
    	parametersMap.add("client_secret", appConfig.getClientSecret());
    	parametersMap.add("audience", "https://abmi.auth0.com/api/v2/");
    	DefaultOAuth2AccessToken token = (new RestTemplate()).postForObject("https://abmi.auth0.com/oauth/token", parametersMap, DefaultOAuth2AccessToken.class);
      
    	HttpHeaders headers = new HttpHeaders();
  	headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
  	headers.add("Authorization", "Bearer "+token.getValue());
  	HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
  	ResponseEntity<String> response = (new RestTemplate()).exchange("https://abmi.auth0.com/api/v2/users/" + principal.getName(), HttpMethod.GET, entity, String.class);
  	System.out.println("Result - status:" + response.getStatusCode() + " getbody: " + response.getBody());

I think I was using a non-access token.

Thanks a lot for sharing it with the rest of community!

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.