SpringSecurity(二十三):authorizeRequests顺序


我们在使用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中获得角色信息!


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM