【问题标题】:Create a URI pattern matcher to allow/disallow for decoding JWT创建一个 URI 模式匹配器以允许/禁止解码 JWT
【发布时间】:2019-10-17 20:26:19
【问题描述】:

我是 Spring Boot 和 Spring Security 的新手,我正在构建一个 RESTful API 服务,以允许用户在应用程序上注册、登录和执行其他操作。

我正在使用 JWT 进行声明验证,并且每次我的用户使用除登录和注册之外的 API 时,我都会传递令牌。因此,我将允许访问这些 API 而无需传入 JWT,但对于其余部分,如果未通过 JWT,我想直接拒绝请求。

我只有一个控制器,它是 UserController,它映射到路径 /api/user。它将服务于以下 API -

/sign-up。这是一个 POST 方法。我希望它允许访问它而不需要传递 JWT。

/verify/{verificationCode} 这是一个 GET 方法。我希望它被允许访问它而不需要通过 JWT。

/set-password/ 这是一个 POST 方法,会返回一个 JWT。

/set-profile。这是一个 PUT 方法,将使用 JWT。

我尝试了一些使用 antMatchers 配置 WebSecurity 和 HttpSecurity 的示例,并且我还配置了一个 GenericFilterBean。

我不知道正确的方法和帮助将不胜感激。我正在使用 Spring 的 2.1.3.RELEASE 版本。

【问题讨论】:

    标签: java spring-boot spring-security


    【解决方案1】:

    您可以通过以下配置实现您的要求。这是使用不需要将身份验证/授权放置在WebSecurity using ignoring instead of HttpSecurity as WebScurity will bypass the Spring Security Filter Chain and reduce the execution time 中的 URL 的好方法

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
            .ignoring()
            .antMatchers("/sign-up")
            .antMatchers("/verify/**");
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/set-password/").hasRole("yourROLE")
            .antMatchers("/set-profile").hasRole("yourROLE") 
            .anyRequest().authenticated();
    }
    

    当你使用HttpSecurity 并尝试permitAll() 请求时。您的请求将被允许从 Spring Security Filter Chain 访问。这是昂贵的,因为会有其他请求也进入此过滤器链,需要根据身份验证/授权来允许或禁止

    但是当你使用WebSecurity 时,任何对sign-up or verify 的请求都将完全绕过Spring Security Filter Chain。这是安全的,因为您不需要任何身份验证/授权即可查看图像或读取 javascript 文件。

    【讨论】:

    • 感谢帕特尔·罗米尔的帮助!这对我来说效果很好!
    【解决方案2】:

    您可以通过配置HttpSecurity 来配置每个 URL 的安全性:

    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
    
            //Ignore other configuration stuff for simplicity 
            http.authorizeRequests()
                    .antMatchers("/sign-up" ,"/verify/**" ).permitAll()
                    .anyRequest().authenticated()
        }
    
    }
    

    那么除了 /sign-up/verify/** 之外的所有对 URL 的请求都需要身份验证(在你的情况下意味着 JWT)。

    如果您想进一步控制/sign-up/verify/**,您甚至可以执行以下操作,并且只能在没有验证的情况下访问正确的 HTTP 方法:

    http.authorizeRequests()
      .antMatchers(HttpMethod.POST, "/sign-up").permitAll()
      .antMatchers(HttpMethod.GET, "/verify/**").permitAll()
      .anyRequest().authenticated()
    

    【讨论】:

    • 感谢肯的回答。我会试试这个,让你知道它是怎么回事。
    • 谢谢陈健。您的解决方案也很有效!
    猜你喜欢
    • 1970-01-01
    • 2011-12-16
    • 2018-10-27
    • 1970-01-01
    • 2012-10-19
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    相关资源
    最近更新 更多