Spring 安全性 - permitAll() 不允许未经身份验证的访问



我只想允许未经身份验证的访问几个路径:/everyone1/something1、/everyone2/something2 和/everyone3/**。对于其余路径,我只希望允许经过身份验证的请求。

现在,我有"类WebSecurityConfig扩展WebSecurityConfigurerAdapter":

@Override
  protected void configure(HttpSecurity httpSecurity) throws Exception {
    JwtAuthenticationFilter jwtAuthenticationFilter = new JwtAuthenticationFilter(
      jwtUtils, this.accessCookie, this.selectedRoleScopeCookie);
    httpSecurity.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    httpSecurity.cors().and().csrf().disable();
    httpSecurity.authorizeRequests()
      .antMatchers("/everyone1/something1", "/everyone2/something2", "/everyone3/**")
      .permitAll()
      .anyRequest().authenticated()
      .and().httpBasic().disable();
  }

在"jwtAuthenticationFilter"中,我将身份验证设置为:

  private void setAuthentication2(String username, String someData, boolean authenticated) {
    User user = new User(username, "", new ArrayList<>());
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
    if (!authenticated) {
      authentication.setAuthenticated(false);
    }
    AuthenticationDetails authenticationDetails = new AuthenticationDetails(someData);
    authentication.setDetails(authenticationDetails);
    SecurityContextHolder.getContext().setAuthentication(authentication);
  }

遗憾的是,上述配置会阻止每个请求,包括经过身份验证和未经身份验证的请求。

任何帮助将不胜感激。

谢谢!

此方法为经过身份验证的请求授权某些路径。您需要的是:

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/everyone1/something1", "/everyone2/something2", "/everyone3/**");
}

然后,匿名请求可以访问此路径。

最新更新