1

I want to secure a backend API written in Java/SpringBoot and using Auth0. I am following the Auth0 example.

Everything works fine and as expected, however, when I apply this to my application I want to detect the user who made the API call. In various examples I've come across it appears to be possible with Spring Security by injecting the OidcUser.

Some relevant links I've found are:

  1. Inject custom OidcUser wrapper with @AuthenticationPrincipal
  2. Spring Security and OIDC connect

In my application, my controller looks like this:

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/project")
public class ProjectController {

    @PostMapping("/add")
    @PreAuthorize("hasAuthority('write:project')")
    public ResponseEntity<DummySubmitResponseDto> createNewProject(@AuthenticationPrincipal OidcUser oidcUser,
                                                                   @RequestBody DummyDto dummyDto) {

        DummySubmitResponseDto projectSubmitResponseDto = new DummySubmitResponseDto("TheResponse");
        return new ResponseEntity<>(projectSubmitResponseDto, HttpStatus.CREATED);
    }
}

I'm using a React SPA to get an access-token. I save it manually and use Curl or POSTMAN to call the API. However, oidcUser is always null.

I'm not sure if I'm following the correct approach. Separate to this, I don't understand how the Backend (which is a resource server) is able to get the user information from the access token.

sdbol
  • 413
  • 4
  • 17
  • 1
    I realised I can call Object user = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); inside the method but I'd like to understand the above code better. – sdbol Mar 16 '22 at 01:49
  • Wich token are you using when calling backend from the frontend ? Id_token or access_token ? – Levijatanu Mar 31 '22 at 11:58
  • You should use the access token. The id_token is only for the front end – sdbol Mar 31 '22 at 19:33
  • We have a problem because we are getting opaque access tokens from auth0. When the backend is called they don't have a payload inside. – Levijatanu Apr 01 '22 at 08:11
  • Not sure how to solve your problem. My front end is React and I followed the guidance from the Auth0 SPA document. – sdbol Apr 02 '22 at 21:11

0 Answers0