Rasmus Faber
Rasmus Faber

Reputation: 49647

Providing the SecurityIdentity directly to a Quarkus/RESTEasy web service method

I am using Quarkus with RESTEasy to make a web service and I need access to the SecurityIdentity in some of my methods.

It is possible to get it injected by making the service RequestScoped:

@RequestScoped
@Path("/foo")
public class FooResource {
    @Inject
    public SecurityIdentity securityIdentity;

    @GET
    public Foos getFoos() {
        // use securityIdentity
    }
}

But I would prefer to have the class ApplicationScoped and have the SecurityIdentity provided to the method instead. Something like this:

@ApplicationScoped
@Path("/foo")
public class FooResource {
    @GET
    // This does not work, Quarkus tries to convert the request body to a SecurityIdentity.
    public Foos getFoos(SecurityIdentity securityIdentity) { 
        // use securityIdentity
    }
}

Is this possible? Is there a magic annotation I can put on to make Quarkus inject the SecurityIdentity?

Upvotes: 2

Views: 1293

Answers (2)

robSE13
robSE13

Reputation: 1510

I'm not sure if this was the case in 2020 but adding the @Context annotation is working in 2023 for me. So the magic annotation you requested seems to be @Context

@ApplicationScoped
@Path("/foo")
public class FooResource {
    @GET
    // Add the @Context annotation
    public Foos getFoos(@Context SecurityIdentity securityIdentity) { 
        // use securityIdentity
    }
}

The examples in the documentation do not include injecting the @Context SecurityIdentity but do include injecting @Context SecurityContext. Maybe SecurityContext would be sufficient for your use case? If not, it seems SecurityIdentity can be used there too.

Upvotes: 2

Sergey Beryozkin
Sergey Beryozkin

Reputation: 863

Keeping it injected into a field will still work for ApplicationScoped beans and be thread safe

Upvotes: 6

Related Questions