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

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 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败