Skip to content

Jwt Principal customization #16231

@vaa25

Description

@vaa25

Expected Behavior
I want to use method authorization annotations and @AuthenticationPrincipal clean way with custom business fields using oauth2 authorization with spring-boot-starter-oauth2-resource-server supporting all spring.security.oauth2.resourceserver.jwt.* properties.

@PreAuthorize("principal.id==100")
@GetMapping
public MyPrincipal test(@AuthenticationPrincipal MyPrincipal principal) {
    return principal;
}

response:

{"id": 123, "name": "Alex"}

It can be achieved if Authentication object will have custom principal object:

public class JwtPrincipal implements MyPrincipal {
  private final Integer id;
  private final String name;
  public JwtPrincipal(Jwt jwt, String principalName) {
    this.id = Integer.parseInt(jwt.getClaim("id"));
    this.name=principalName;
  }
  @Override
  public Integer getId() {
    return id;
  }
  @Override
  public String getName() {
    return name;
  }
}

I'd like to add a principal converter as a bean or via OAuth2ResourceServerConfigurer for customization

public interface JwtPrincipalConverter {
    Object convert(Jwt jwt, String principalName);
}

Current Behavior

Current implementation sets org.springframework.security.oauth2.jwt.Jwt object as principal causing such implementation:

@PreAuthorize("principal.claims['id']=='100'")
@GetMapping
public Jwt test(@AuthenticationPrincipal Jwt principal) {
    return principal;
}

Here I have to write 'claims' in @PreAuthorize that is not business field, and receive Jwt principal as method parameter that is not business object.

Context
I believe having custom Principal object makes authorization control more readable and simple and can help to accept requests with different types of authorization into same controller method.

There is some workarounds, but they are not so simple as my proposition and may require third-party library.

  1. to use custom jwtAuthenticationConverter. In this case we have to write custom JwtAuthenticationToken and additional code to support spring.security.oauth2.resourceserver.jwt.* properties.
  2. to apply third-party library with its own properties and a little bit less additional code.

Based on stackoverflow question

P.S. I have implemented this feature locally, just waiting for your approve of this idea, guys.

Metadata

Metadata

Assignees

Labels

in: oauth2An issue in OAuth2 modules (oauth2-core, oauth2-client, oauth2-resource-server, oauth2-jose)type: enhancementA general enhancement

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions