Skip to content

[REQ] [Java] [Spring] Security info without SecurityContextHolder #24391

Description

@juniorjrjl

Is your feature request related to a problem? Please describe.

No. This suggests is about include a modern alternative to get security info in Controllers, not replace SecurityContextHolder, but include a possibility to use this modern approach.

Describe the solution you'd like

Instead of use SecurityContextHolder to get security info in protected endpoints is include a one new param in methods:

@PostMapping("/orders")
public ResponseEntity<PedidoDTO> createOrder(@RequestBody final OrdrerRequest request, final Principal principal) { // using Principal from Java
    
    final var username = principal.getName();
    // ...
}

or for custom impl

@PostMapping("/orders")
public ResponseEntity<PedidoDTO> createOrder(@RequestBody final OrderRequest request,@Authentication final Principal CustomPrincipal principal) { // custom impl with annotation
    
    Long userId = principal.getId();
    // ...
}

the suggest is provide this alternative if want. This approach is helpfull for create unit tests for controller

Describe alternatives you've considered

could be created a config to enable this, something like

<InjectPrincipalInController>true</InjectPrincipalInController>//default false

for define custom principal:

<CustomPrincipalToUse>FULL_QUALIFIED_NAME_IN_CLASS</CustomPrincipalToUse>

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions