user996505
user996505

Reputation: 1239

Jersey HTTP authentication:How Can I Access and the HTTP authentication in jersey restful url?

I am Writting a Restful webservice with Jersey, this is the sample code:

@GET
@Produce(MediaType.APPLICATION_JSON)
public String findItems(){

...
}

and the url of findItem is localhost:8080/items the method should verify the http authentication info(digest or basic) of this url before excutes, how to access authentication from the a url request first?

Upvotes: 1

Views: 1036

Answers (2)

Martin Matula
Martin Matula

Reputation: 7979

Usually the authentication is handled by the container, you just have to add the corresponding constraint to web.xml to indicate what Uris should be protected and what kind of auth is required. Then in jersey you can get the roles and principal info from the SecurityContext you can inject to your resource.

Upvotes: 0

Ransom Briggs
Ransom Briggs

Reputation: 3085

I would not put this in the controller itself, but in a com.sun.jersey.spi.container.ContainerRequestFilter around the resource classes you wish to protect, but should give you the basic idea.

@Context
private HttpServletRequest request;

@GET
@Produce(MediaType.APPLICATION_JSON)
public String findItems(){
    String auth = request.getHeader("authorization");
    if (auth != null) {
        String basic_prefix = "Basic ";
        if (auth.startsWith(basic_prefix)) {
            String auth_data = new String(Base64.decode(auth.substring(basic_prefix.length())));
            String [] user_and_key = auth_data.split(":", 2);
            // user and password available here
        } else {
            // reject access
        }
    } else {
        // reject access
    }
}                   

Upvotes: 2

Related Questions