简体   繁体   English

根据调用的方法,在 Spring REST API 中应用身份验证过滤器

[英]Apply an authentication filter in a Spring REST API depending on the method called

We have a REST API built on Spring boot, with some public methods and some private methods.我们有一个 REST API 建立在 Spring 引导上,有一些公共方法和一些私有方法。

We implemented an AbstractAuthenticationProcessingFilter to handle a JWT authentication, and everything works fine.我们实现了AbstractAuthenticationProcessingFilter来处理 JWT 身份验证,一切正常。

However, we would like to apply this filter only on the private methods, as the public ones do not need any authentication done.但是,我们只想将此过滤器应用于私有方法,因为公共方法不需要完成任何身份验证。 Problem is the urls can't be used to separate public and private methods (ie /account/get/{id} is public, but /account/personal/{id} is private, with no common pattern between all private or all public urls).问题是 url 不能用于分隔公共和私有方法(即 /account/get/{id} 是公共的,但 /account/personal/{id} 是私有的,所有私有或所有公共之间没有共同模式网址)。

It seems the HttpSecurity only allows us to use the urls to apply filters, when we would prefer to apply the authentication filter only when a method with @PreAuthorize is called.似乎HttpSecurity只允许我们使用 url 来应用过滤器,而我们希望仅在调用带有@PreAuthorize的方法时才应用身份验证过滤器。

The only way we imagine for doing it is to use reflections and, during the web security configuration, discover at runtime all methods with @PreAuthorize , find back their urls, and use those to build a RequestMatcher listing all their precise endpoints.我们想象的唯一方法是使用反射,并且在 web 安全配置期间,在运行时发现所有带有@PreAuthorize的方法,找到它们的 url,并使用它们构建一个 RequestMatcher 列出所有它们的精确端点。

Is there a simpler solution?有没有更简单的解决方案?

Your question is not clear to me, I guess you want to access private APIs with JWT and Public APIs without JWT.你的问题我不清楚,我猜你想访问带有 JWT 的私有 API 和没有 JWT 的公共 API。 if so, just mention the API path in Websurity to ignore JWT authentication.如果是这样,只需在 Websurity 中提及 API 路径即可忽略 JWT 身份验证。

Below code for manually update the API which does not sequence.下面的代码用于手动更新不排序的 API。

@Override
    public void configure(WebSecurity web) {
        web.ignoring()
            .antMatchers(HttpMethod.GET, "/api/url1", "/api/url2")
            .antMatchers(HttpMethod.POST, "/api/url3");
    }

Other than APIs which are mentioned in WebSecurity ignoring, will be an authorized access除了 WebSecurity 忽略中提到的 API 之外,将是授权访问

Below code for the APIs which starts with /api/public以下以/api/public开头的 API 代码

@Override
    public void configure(WebSecurity web) {
        web.ignoring()
            .antMatchers("/api/public/**");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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