为了账号安全,请及时绑定邮箱和手机立即绑定

创建一个 URI 模式匹配器以允许/禁止解码 JWT

创建一个 URI 模式匹配器以允许/禁止解码 JWT

犯罪嫌疑人X 2022-12-28 14:17:23
我是 Spring Boot 和 Spring Security 的新手,我正在构建一个 RESTful API 服务,以允许用户在应用程序上注册、登录和执行其他操作。我正在使用 JWT 进行声明验证,每次我的用户使用除登录和注册以外的 API 时,我都会传递令牌。因此,我将允许在不传递 JWT 的情况下访问这些 API,但对于其余部分,如果未传递 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 版本。
查看完整描述

2 回答

?
qq_遁去的一_1

TA贡献1725条经验 获得超7个赞

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


@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()

    }


}

然后对 URL 的所有请求除外/sign-up并且/verify/**需要身份验证(在您的情况下这意味着 JWT)。


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


http.authorizeRequests()

  .antMatchers(HttpMethod.POST, "/sign-up").permitAll()

  .antMatchers(HttpMethod.GET, "/verify/**").permitAll()

  .anyRequest().authenticated()


查看完整回答
反对 回复 2022-12-28
?
守着星空守着你

TA贡献1799条经验 获得超8个赞

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


@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 过滤器链访问。这是昂贵的,因为会有其他请求也将进入此过滤器链,需要根据身份验证/授权允许或不允许


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


查看完整回答
反对 回复 2022-12-28
  • 2 回答
  • 0 关注
  • 75 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信