Can I access the current user in session statically in Quarkus?

1.2k views Asked by At

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?

1

There are 1 answers

5
ayyylmao On

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();