2

I need to do access to the current user (previously set up by a ContainerRequestFilter) in a static way, to avoid the passage of the @Context SecurityContext in every method of every controller.

I want to achieve something that, in Spring, I would do with

SecurityContextHolder.getContext().getAuthentication();

Is there any way to do it, besides using Spring Security in Quarkus?

ayyylmao
  • 71
  • 1
  • 13

1 Answers1

3

The solution is to use this dependency

<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-oidc</artifactId>
</dependency>

Then you can manipulate the instance of SecurityIdentity to "make it static"

@Startup
@ApplicationScoped
public class UserUtilsService {

@Inject
private SecurityIdentity securityIdentity;

private static SecurityIdentity instance;

/**
 * Gets the custom user.
 *
 * @return the custom user
 */
public static CustomUser getCustomUser() {
    return (CustomUser) instance.getPrincipal();
}

@PostConstruct
private void setUp() {
    instance = this.securityIdentity;
}

}

@StartUp does instantiate the bean on application start (instead of lazily).

You can then access to the Principal statically using UserUtilsService.getCustomUser();

ayyylmao
  • 71
  • 1
  • 13
  • but doesn't it mean you still need to inject the service where you need to call this service? So in a simple POJO this won't be possible... or am I reading this wrong? – Deniss M. May 11 '22 at 14:12
  • You don't need to inject it, you can use the static method. "this.securityIdentity" is initialized on startup (@Startup) and assigned to the static field. It's basically a workaround to access it statically. – ayyylmao May 12 '22 at 17:05
  • but is it request scoped or ? – Deniss M. May 16 '22 at 07:51
  • It is request scoped – ayyylmao May 16 '22 at 15:08
  • interesting. I look at your implementation and without proper injection to me it seems as if it would not work, but you state otherwise. I will need to try this out myself I guess. – Deniss M. May 17 '22 at 06:31