Spring Security 在SpringBoot中授予的权限不与hasRole()/hasAuthority()一起使用

ljo96ir5  于 2023-08-05  发布在  Spring
关注(0)|答案(1)|浏览(159)

我有一个小的应用程序,有一个CustomUserDetailService类。它本质上是在使用JWT进行身份验证后,从数据库返回用户的角色。这是将角色从db转换为authority/role的函数。

@Service
@Slf4j
public class CustomUserDetailService implements UserDetailsService {

    ................

    private Collection<GrantedAuthority> mapRolesToAuthorities(List<Role> roles){
        log.info("in mapRolesToAuthorities method");
        log.info("user's role - "+roles.get(0).getName());
        return roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());

字符串
我知道这是工作,因为我可以从数据库中获得用户的角色与log.info()
现在我有一个SecurityConfig类,我想根据角色限制API。

@Slf4j
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception{

         httpSecurity
                .csrf().disable()
                ..........................

                .authorizeHttpRequests()
                .requestMatchers("/api/auth/**").permitAll()
                .requestMatchers(new AntPathRequestMatcher("/h2-console/**")).permitAll()
                .requestMatchers("/question/**").permitAll()
                .requestMatchers(new AntPathRequestMatcher("/quiz/**")).hasRole("USER")  //<< This is not working
                .anyRequest().authenticated()
                .and()
                .httpBasic();   //  to make it into http than https


我在/quiz调用时收到401 Unauthorized错误。但是我可以访问所有的permitAll()
这是/quiz调用的调试日志

2023-07-19T15:15:02.330+05:30  INFO 14024 --- [nio-8080-exec-7] c.l.q.security.CustomUserDetailService   : in mapRolesToAuthorities method
2023-07-19T15:15:02.331+05:30  INFO 14024 --- [nio-8080-exec-7] c.l.q.security.CustomUserDetailService   : user's role - USER
2023-07-19T15:15:02.331+05:30 DEBUG 14024 --- [nio-8080-exec-7] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.learn.quiz.controller.QuizController#getQuizQuestions(Integer)
2023-07-19T15:15:02.332+05:30 DEBUG 14024 --- [nio-8080-exec-7] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.learn.quiz.controller.QuizController#getQuizQuestions(Integer)
2023-07-19T15:15:02.333+05:30 DEBUG 14024 --- [nio-8080-exec-7] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
2023-07-19T15:15:02.333+05:30 DEBUG 14024 --- [nio-8080-exec-7] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)


我试过的东西。
1.将.permitAll()放到测验端点->它按预期工作
1.而不是.hasRole(),将.hasAuthority("USER")hasAuthority("ROLE_USER")hasAuthority("SCOPE_USER")-> Fails everytime。

wa7juj8i

wa7juj8i1#

您可以使用PreAuthorize注解在方法级别添加基于角色的安全性。

@GetMapping("/quiz/1")
@PreAuthorize("hasAuthority('USER')") 
public String quiz() {
   ....
   return "someView";
}

字符串
如果您的方法需要支持多个角色,那么使用类似@PreAuthorize("hasAnyAuthority('MOD', 'ADMIN')")的东西(本示例假设您的角色名称分别为MOD和ADMIN)

相关问题