简体   繁体   中英

Name Binding(Jersey) in DropWizard

I want to create custom annotation with NameBinding of Jersey for Auth via JWT, I used this tech in another plain-java project and everything works perfect, but it's not working in DropWizard project. As I know DW also use Jersey for REST. this is my test code, but it's not working.

Interface:

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Auth {}

Implementation:

@Auth
@Provider
public class AuthFilter implements ContainerRequestFilter {

    private static final String SECRET = "SOME_SECRET_STRING";

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        try {
            String userToken = requestContext.getHeaderString("token");
            Claims body = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(userToken).getBody();
            if(body.getExpiration().before(new Date())) {
                requestContext.abortWith(Response
                        .status(Response.Status.UNAUTHORIZED)
                        .entity("Token is expired")
                        .build());
            }
        } catch (Exception e) {
            requestContext.abortWith(Response
                    .status(Response.Status.UNAUTHORIZED)
                    .entity("Error")
                    .build());
        }
    }
}

Rest:

@GET
@Path("/test")
@Auth
public String test() {
    return "Hello, " + userName;
}

can anybody help with this issue?

I found the solution and post the answer it would be helpful for somebody. I had to register the AuthFilter class in run method:

environment.jersey().register(new AuthFilter());

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