Rest – authentication / authorization in jax-rs using interceptors and injection

I am using wildfly 8 to develop a new application in Java EE 7 I am using Jax - rs to provide a restful service interface for remote applications

You can use @ context annotation to inject something similar to httpheaders object into resource method parameters Since this object is based on request parameters (HTTP header, of course), I proposed the idea of creating my own injectable user object, which is created based on the valid token existing in the request (similar to OAuth access token)

Therefore, I hope to achieve this goal:

@Path("/resources")
public class MyResource {

    @Path("/{id}")
    @GET
    public Response getById(@Context User user,@PathParam("id") long id) {
        ...
    }

}

Where user is an injectable object created based on the request parameters, such as an object accessible through the httpheaders object Of course, if the user object cannot be created for any reason, the provider can also throw an exception and return an HTTP error response

Now, my question is:

>Is this a good design? If not, what better options do I have? > How can I do this? I don't care if my solution is jax-rs specific and uses wildfly / resteasy specific internal, but I definitely prefer portable solutions (if any)

thank you

Solution

In my opinion, this method is effective as long as you don't try to use this user object to build session like content

As answered here, you can use @ context and @ provider, but this is not exactly what you want Using resteasy dispatcher, you can directly inject a class for each @ context But here you must register the object that should be injected I don't think this makes sense for the parameters of the request scope What you can do is inject such a provider:

// Constructor of your JAX-RS Application
public RestApplication(@Context Dispatcher dispatcher) {
    dispatcher.getDefaultContextObjects().put(UserProvider.class,new UserProvider());
}

// a resource
public Response getById(@Context UserProvider userProvider) {
    User user = userProvider.get();
}

Other ways to solve the problem:

>Register webfilter, verify the user, wrap ServletRequest and overwrite getuserprincipal You can then access userprincipal. > Implement a Jax - RS interceptor that implements containerrequestfilter Set containerrequestcontext HTML #setsecuritycontext is used together with userprincipal, and the securitycontext is injected into resourcemethod parameter. > CDI interceptor for updating method parameters. > Implement a class which produces for your users and inject it through CDI

I pushed the example to GitHub

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>