我是希望根据 hasRole 来判断一个 url 是否能被当前用户访问,然后写了下面这些配置
protected void configure(HttpSecurity http) throws Exception { http.csrf() .disble() .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/下方法的权限
1 GM 2021-05-14 12:44:57 +08:00 把 ROLE_stu 加到 Granted Authorities 里就好了 |