小白求教,关于 SpringSecurity 的 hasRole 方法进行角色鉴权

2021-05-14 12:04:57 +08:00
 KISAKA

我是希望根据 hasRole 来判断一个 url 是否能被当前用户访问,然后写了下面这些配置

protected void configure(HttpSecurity http) throws Exception {
        http.csrf()
                .disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/stu/**").hasAnyRole("stu")
                .antMatchers("/teacher/**").hasAnyRole("teacher")
                .antMatchers("/admin/**").hasAnyRole("admin")
                .anyRequest()
                .authenticated()
                .and()
                .headers()
                .cacheControl();
        //添加 jwt,登录授权过滤器
        http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
        //添加自定义未授权和未登陆结果返回
        http.exceptionHandling()
                .accessDeniedHandler(restfulAccessibleDeniedHandler)
                .authenticationEntryPoint(restAuthorizationEntryPoint);

    }

jwt 登录时获取到的 UserDetails 信息是这样的

SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=User(username=1704060101, password=$2a$10$zo5h5kj9bxORUrGaNW.zjuto1JrRAtPEZqOlQnXkZIfMfR.xAG/ai, role=ROLE_stu), Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=null], Granted Authorities=[]]]

按照我的理解是,用户表中的 role 设置成 ROLE_stu 的话,通过这个配置就能有访问 /stu/下所有方法的权限,可是设置完之后 role 为 ROLE_stu 的用户并没有访问 /stu/下方法的权限

1259 次点击
所在节点    Java
2 条回复
GM
2021-05-14 12:44:57 +08:00
把 ROLE_stu 加到 Granted Authorities 里就好了
KISAKA
2021-05-14 13:03:57 +08:00
@GM 嗯嗯,搞定了,谢谢大佬

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/776897

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX