【问题标题】:Spring Security - permitAll() not allowing unauthenticated accessSpring Security - permitAll() 不允许未经身份验证的访问
【发布时间】:2019-08-19 11:55:30
【问题描述】:

我只想允许未经身份验证的人访问以下几个路径:/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);
  }

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

任何帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: java spring spring-mvc websecurity


    【解决方案1】:

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

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

    那么匿名请求就可以访问这个路径了。

    【讨论】:

    • 感谢您的评论。据我了解,这将使我的自定义过滤器 JwtAuthenticationFilter 忽略对上述路径的所有请求。这不是我想要的行为——我需要所有的请求都被这个过滤器过滤掉。
    猜你喜欢
    • 2015-07-01
    • 2017-05-10
    • 2014-09-02
    • 2017-04-17
    • 2019-11-20
    • 2021-01-20
    • 2016-08-15
    • 2020-06-23
    • 2020-11-11
    相关资源
    最近更新 更多