我们在使用spring Security时,需要注意authorizeRequests的顺序

 @Override
    protected void configure(HttpSecurity http) throws Exception {
     http.authorizeRequests()
             .anyRequest().authenticated()
             .antMatchers("/hello").permitAll();
    }

由于是按照从上往下顺序依次执行,如上所示,当我们访问/hello时,会发现此时仍然需要登录!

所以我们往往会把.anyRequest().authenticated()放在最后

 @Override
    protected void configure(HttpSecurity http) throws Exception {
     http.authorizeRequests()
             .antMatchers("/hello").hasRole("USER")
             .antMatchers("/hi").hasRole("ADMIN")
             .anyRequest().authenticated();
    }

如上就表示。访问/hello接口需要USER角色,访问/hi需要ADMIN角色,访问其他接口需要认证。

那么访问/hello和/hi不需要认证吗?

也需要,毕竟只有认证了,我们才能从authentication中获得角色信息!

相关文章:

  • 2022-01-18
  • 2022-12-23
  • 2021-08-16
  • 2022-12-23
  • 2022-12-23
  • 2021-10-07
  • 2021-12-13
  • 2021-09-27
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-21
相关资源
相似解决方案