Spring security 返回 404 而不是 403

时间:2021-03-02 11:58:37

标签: java spring-boot spring-security jwt http-status-code-404

我浏览了很多帖子,但没有一个对我有帮助。 当我尝试在没有令牌的情况下到达端点时,一切正常,它会得到 403。但是如果我登录用户并尝试到达管理端点,它会得到 404 而不是 403。在 doFilter 中也不例外这是我的代码:

    @Override
  protected void doFilterInternal(
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      FilterChain filterChain)
      throws ServletException, IOException {
    String token = jwtTokenProvider.resolveToken(httpServletRequest);
    try {
      if (token != null && jwtTokenProvider.validateToken(token)) {
        Authentication authentication = jwtTokenProvider.getAuthenticationToken(token);
        SecurityContextHolder.getContext().setAuthentication(authentication);
      }
    } catch (TokenException exception) {
      SecurityContextHolder.clearContext();
      httpServletResponse.sendError(exception.getHttpStatus().value(), exception.getMessage());
      return;
    }
    filterChain.doFilter(httpServletRequest, httpServletResponse);
  }

和弹簧配置:

@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  private final JwtTokenProvider jwtTokenProvider;

  @Override
  public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/swagger-ui/**", "/v3/api-docs/**", "/api-docs");
  }

  @Override
  public void configure(HttpSecurity http) throws Exception {
    http.csrf()
        .disable()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authorizeRequests()
        .antMatchers("/login-admin")
        .permitAll()
        .antMatchers(
            "/api-docs",
            "/swagger-ui.html",
            "/swagger-ui/**",
            "/factures/**",
            )
        .permitAll()
        .antMatchers("/admin") // przykładowy endpoint
        .hasAuthority("Admin")
        .anyRequest()
        .authenticated()
        .and()
        .exceptionHandling()
        .accessDeniedPage("/login")
        .and()
        .apply(new JwtTokenFilterConfigurer(jwtTokenProvider));
  }

  @Override
  @Bean
  public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
  }

  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder(12);
  }
}

0 个答案:

没有答案