V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
KISAKA
V2EX  ›  Java

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

  •  
  •   KISAKA · 2021-05-14 12:04:57 +08:00 · 1219 次点击
    这是一个创建于 1049 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我是希望根据 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/下方法的权限

    2 条回复    2021-05-14 13:03:57 +08:00
    GM
        1
    GM  
       2021-05-14 12:44:57 +08:00
    把 ROLE_stu 加到 Granted Authorities 里就好了
    KISAKA
        2
    KISAKA  
    OP
       2021-05-14 13:03:57 +08:00
    @GM 嗯嗯,搞定了,谢谢大佬
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1042 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 22:38 · PVG 06:38 · LAX 15:38 · JFK 18:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.