简体   繁体   中英

Jersey: Use Provider in Resource Filter

Using Jersey 1.14 and Spring 3.1.2

I want to create a filter like this: https://gist.github.com/3031495

but in that filter I want access to a provider I created.

I'm getting an IllegalStateException . I suspect something in my lifecycle is hosed up. I can access @Context private HttpServletRequest and pull the session info I need from there, but then two classes have to know about where/how to get my "AuthUser" object.

Any help is appreciated!

My Provider:

@Component
@Provider
public class AuthUserProvider extends AbstractHttpContextInjectable<AuthUser> implements
        InjectableProvider<Context, Type> {

    private static final Logger LOG = LoggerFactory.getLogger(AuthUserProvider.class);

    @Context
    HttpServletRequest req;

    public void init() {
        LOG.debug("created");
    }

    @Override
    // this may return a null AuthUser, which is what we want....remember, a
    // null AuthUser means the user hasn't authenticated yet
    public AuthUser getValue(HttpContext ctx) {
        return (AuthUser) req.getSession().getAttribute(AuthUser.KEY);
    }

    // InjectableProvider implementation:

    public ComponentScope getScope() {
        return ComponentScope.Singleton;
    }

    public Injectable<AuthUser> getInjectable(ComponentContext ic, Context ctx, Type c) {
        if (AuthUser.class.equals(c)) {
            return this;
        }
        return null;
    }
}

My Filter:

@Component
public class TodoFilter implements ResourceFilter {

    private static final Logger LOG = LoggerFactory.getLogger(TodoFilter.class);

    @Autowired
    private JdbcTemplate todoTemplate;

    // this works
    @Context
    private HttpServletRequest servletRequest;

    // this throws a java.lang.IllegalStateException
    // @Context
    // private AuthUser authUser;

    public void init() throws Exception {
        LOG.debug("created");
        LOG.debug(todoTemplate.getDataSource().getConnection().getMetaData()
                .getDatabaseProductName());
    }

    @Override
    public ContainerRequestFilter getRequestFilter() {
        return new ContainerRequestFilter() {
            @Override
            public ContainerRequest filter(ContainerRequest request) {
                LOG.debug("checking if {} is authorized to use {}", "my authenticated user",
                        request.getPath());
                // String name = request.getUserPrincipal().getName();
                // String[] admins = settings.getAdminUsers();
                // for (String adminName : admins) {
                // if (adminName.equals(name))
                // return request;
                // }
                // if (authUser.getUsername().equals("jberk")) {
                // return request;
                // }
                // return HTTP 403 if name is not found in admin users
                throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN)
                        .entity("You are not authorized!").build());
            }
        };
    }

    @Override
    public ContainerResponseFilter getResponseFilter() {
        return new ContainerResponseFilter() {
            @Override
            public ContainerResponse filter(ContainerRequest request,
                    ContainerResponse response) {
                // do nothing
                return response;
            }
        };
    }

}

My Service (aka Resource):

@Component
@Path("/rs/todo")
@Produces(MediaType.APPLICATION_JSON)
@ResourceFilters(TodoFilter.class)
public class TodoService {
    @GET / @POST methods
}

so I think I figured this out....

I added this to my ResourceFilter:

@Context
private HttpContext ctx;
@Autowired
private AuthUserProvider provider;

then I can do this in the filter method:

public ContainerRequest filter(ContainerRequest request) {
       AuthUser authUser = provider.getValue(ctx);
       // use authuser in some way
}

this might not be "correct"...but it's working and I don't have code duplication

public ComponentScope getScope() {
    return ComponentScope.Singleton;
}

It should be

public ComponentScope getScope() {
    return ComponentScope.PerRequest;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM