0

I am creating some sort of RESTful API with basic auth. To handle the auth information I added a custom ContainerRequestFilter. This works quite good, but I want to set global information like the "username" of the caller. How can I set global/request-specific information or properties and get them within a "Controller" method?

//some filter
public class AuthFilter implements ContainerRequestFilter{

    //...

    @Override
    public void filter( ContainerRequestContext requestContext ) throws IOException {
        requestContext.setProperty("username", "someusername");
    }


    //...

}

//example "route-handler"
@GET 
@Produces(MediaType.APPLICATION_JSON)
public List<Event> getEvents() {
    //HOW to get the username property?!
}
NaN
  • 3,501
  • 8
  • 44
  • 77

1 Answers1

1

You can inject HttpServletRequest into your controller and use HttpServletRequest.getAttribute to retrieve the values you set in ContainerRequestContext.setProperty.

@GET 
@Produces(MediaType.APPLICATION_JSON)
public List<Event> getEvents(@Context HttpServletRequest req) {
    String username = (String) req.getAttribute("username");  
    ...
}

I've used that on Glassfish/Jersey and it works fine so it should work in your environment.

Baldy
  • 2,002
  • 14
  • 14
  • I always receive an 'Caused by: java.lang.ClassNotFoundException: javax.servlet.http.HttpServletRequest' error message. I added servlet-api dependency to my pom, without change. – NaN Aug 16 '14 at 08:02
  • According to the documentation I've looked at the class is part of Jetty. What version are you using? Any chance you could post the log? – Baldy Aug 16 '14 at 11:09
  • I found the failure: http://stackoverflow.com/questions/25338377/java-ee-class-not-found-despite-valid-import/25338542#25338542 – NaN Aug 16 '14 at 11:50
  • Within my filter I call `requestContext.setProperty("username", phone_username);`, but within the Controller `(Long) request.getAttribute("username");` is null. What's wrong? – NaN Aug 17 '14 at 15:36