【问题标题】:Spring Security with JWT使用 JWT 的 Spring 安全性
【发布时间】:2017-07-04 14:21:31
【问题描述】:

我正在尝试使用 JWT 开发 Spring Security 项目。 我想在没有 Spring Security 的情况下访问 Login api(没有 JWT 令牌)。但是使用以下配置,每次(对于登录 api 也是如此)它正在检查 JWT 令牌给我 403 错误。

下面是我的 WebSecurityConfig。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private JwtAuthFilter jwtAuthFilter;

@Autowired
private TokenAuthenticationService jwtAuthenticationProvider;

@Override
public void configure(AuthenticationManagerBuilder auth)  throws Exception {
    auth.authenticationProvider(jwtAuthenticationProvider);
}



@Override
protected void configure(HttpSecurity http) throws Exception {

    http.csrf().ignoringAntMatchers("/api/v1/login");
    http.csrf().disable();

    http.authorizeRequests()
            .antMatchers("/api/v1/login")
            .permitAll()
            .and()
            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
}

}

提前致谢

【问题讨论】:

    标签: java spring spring-boot spring-security jwt


    【解决方案1】:

    对于登录路径配置,可以使用这样的东西:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/**").hasRole("USER").and().formLogin()
                .usernameParameter("username") // default is username
                .passwordParameter("password") // default is password
                .loginPage("/authentication/login") // default is /login with an HTTP get
                .failureUrl("/authentication/login?failed") // default is /login?error
                .loginProcessingUrl("/authentication/login/process"); // default is /login
                                                                        // with an HTTP
                                                                        // post
    }
    

    如果某些路径需要忽略configure(WebSecurity web)可以覆盖:

    @Override
    public void configure(WebSecurity web) throws Exception {
      web.ignoring().antMatchers("/api/v1/somepath").antMatchers("/static/**");
    }
    

    【讨论】:

    • 感谢您的回复。有没有像 (ignoringAntMatchers) 这样的干净方法,以便我可以在 configure(HttpSecurity http) 中检查它?
    • 不确定 ant marchers,但如果您只需要配置登录路径,我已经编辑了回复,并添加了文档中的示例。
    【解决方案2】:

    在您调用的每个服务之前都会执行一个名为 JwtAuthFilter 的过滤器类。

    .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class) 
    

    这段代码提供了在每次请求之前执行过滤器,但是没关系,你必须看到这个过滤器类必须检查是否令牌不存在过滤器类必须返回,请求将直接进入登录服务。如果你能展示那个 Filter 类,我会帮你的。

    【讨论】:

      猜你喜欢
      • 2021-07-14
      • 2020-07-18
      • 2020-07-19
      • 2023-04-04
      • 2019-02-05
      • 2020-11-29
      • 2020-05-27
      • 2017-12-27
      • 2017-10-28
      相关资源
      最近更新 更多