【问题标题】:How can I apply ContainerRequestFilter without web.xml?如何在没有 web.xml 的情况下应用 ContainerRequestFilter?
【发布时间】:2020-03-27 11:52:01
【问题描述】:

我目前正在使用 jersey 2.27 和 jetty 9.4 制作 RESTapi。 在此服务器中,我正在尝试应用过滤器:

@AuthenticationEndpoint.Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    private static final String REALM = "example";
    private static final String AUTHENTICATION_SCHEME = "Bearer";

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        //Authentication code
    }

    private boolean isTokenBasedAuthentication(String authorizationHeader) {

    }

    private void abortWithUnauthorized(ContainerRequestContext requestContext) {


    }

    private void validateToken(String token) throws Exception {

    }
}

但是,这个过滤器没有被触发。

这是我的终点:

@Path("/authenticate")
public class AuthenticationEndpoint {

    Machine machine = Machine.getInstance();

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



    @POST
    @Path("/authenticate")
    @Secured
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response authenticateUser(
            AuthenticationRequest authenticationRequest){

    }

我没有 web.xml,也不知道如何真正触发此过滤器。有人对此有什么建议吗?我很难理解这个服务器过滤器配置。 PS:方法的内容我就省略了,因为我觉得太乱了,如果觉得有必要我当然会补充。

【问题讨论】:

    标签: java rest jersey jetty servlet-filters


    【解决方案1】:

    您必须在创建应用程序时注册过滤器,例如

    public class MyApplication extends ResourceConfig {
      register(AuthenticationFilter.class)
      // yada yada
    }
    

    【讨论】:

    • 我不确定我的情况是什么类。我在其中创建和运行服务器的那个?
    • 你在某处有一个类用于注册AuthenticationEndpoint 类?
    • 是 servletHolder.setInitParameter("jersey.config.server.provider.classnames", AuthenticationEndpoint.class.getCanonicalName());
    猜你喜欢
    • 2019-04-23
    • 1970-01-01
    • 2011-06-29
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 2015-06-26
    相关资源
    最近更新 更多