Qnix_ 2021-04-10 23:37 采纳率: 50%
浏览 1462
已采纳

SpringSecurity 角色控制 antMatchers().hasRole无效

protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        http.authorizeRequests()
                .antMatchers("/auth/login").permitAll()
                .antMatchers("/auth/test").hasRole("ADMIN") // 这里的配置不起作用,其他角色一样可以访问
                .anyRequest().authenticated()
                .and().exceptionHandling()
                .accessDeniedHandler((req, resp, e)-> resultUtil.write(resp, ResultCode.UNAUTHORIZED, null))
                .authenticationEntryPoint((req, resp, e) -> resultUtil.write(resp, ResultCode.NO_LOGIN, null))
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .csrf().disable()
                .cors();
}

其他的hasAnyRole, hasAuthority, hasAnyAuthority同样也不起作用。

springboot 版本 2.3.7.RELEASE

  • 写回答

6条回答 默认 最新

  • cnkeysky 2021-04-11 18:38
    关注
    @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                    .withUser("admin")
                    .password(passwordEncoder().encode("admin"))
                    .roles("admin")
                    .and()
                    .withUser("tom")
                    .password(passwordEncoder().encode("root"))
                    .roles("user");
        }

    你用基于内存的方法去测试一下,可能是你 UserDetails 的实现类中的 getAuthorities 写的有问题

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器