1

I'm using springboot security with Okta for authentication. I'm currently trying to create an abstract class implementing OidcUser to encapsulate some methods. For instance:

public abstract class OktaUser implements OidcUser {

    public UUID getUserId() {
        return UUID.fromString(Objects.requireNonNull(this.getAttribute("user_id")));
    }
}

I normaly inject OidcUser (Working)

@GetMapping
public User currentUser(@AuthenticationPrincipal OidcUser oidcUser) {
    UUID id = UUID.fromString(Objects.requireNonNull(oidcUser.getAttribute("user_id")));

    return userService.getUser(id);
}

But I want to do it like this (Not working)

@GetMapping
public User currentUser(@AuthenticationPrincipal OktaUser oktaUser) {
    return userService.getUser(oktaUser.getMicaUserId());
}

However, oktaUser is always null. Is there a way to register OktaUser as AuthenticationPrincipal?

Francis Robitaille
  • 575
  • 1
  • 5
  • 18

2 Answers2

1

I finally found a solution from this post

With the ControllerAdvice, I was able to build and return my custom OidcUser.

@ModelAttribute
public OktaUser oktaUser(@AuthenticationPrincipal OidcUser oidcUser) {
    return oidcUser == null
        ? null
        : new OktaUser(oidcUser.getAuthorities(), oidcUser.getIdToken(), oidcUser.getUserInfo());
}

And i can inject it like that

@GetMapping
public void getAll(@ModelAttribute OktaUser oktaUser) {

}
Francis Robitaille
  • 575
  • 1
  • 5
  • 18
0

Take a look at the Spring Security guide: https://docs.spring.io/spring-security/site/docs/5.2.0.RELEASE/reference/htmlsingle/#mvc-authentication-principal

It walks through exactly this. You can even define your annotation like @MicaUser which would resolve your custom implementation.

Brian Demers
  • 2,051
  • 1
  • 9
  • 12
  • I was not able to inject my custom type even by going through the guide. I solved my problem with the post https://stackoverflow.com/questions/17741787/injecting-custom-principal-to-controllers-by-spring-security. Maybe it's because of the OidsUser? – Francis Robitaille Mar 15 '20 at 13:35