我看不懂springboot 3中的hasRole函数是怎么工作的

问题描述 投票:0回答:0

我应该做的是用springboot创建一个基于角色的授权

我这样配置安全性:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
            .cors().and().csrf().disable()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeHttpRequests()
            .requestMatchers("/auth").permitAll()
            .requestMatchers("/users").hasRole("USER")
            .requestMatchers("/users/**").permitAll().anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
            .logout()
            .permitAll()
            .and().httpBasic();

    return http.build();
}

我在用户和角色表之间创建了一个 OneToMany 关系,因为每个用户只能有一个角色

用户:

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "roleID")
private Role role;

和作用:

@OneToMany(mappedBy = "role")
private List<User> users = new ArrayList<>();

然后我在角色表中插入了一些值 like this

我也尝试用 ROLE_ 前缀添加它们。
然后我写了我的控制器,如下所示

@PostMapping(path="/auth")
public ResponseEntity<JwtResponse> signIn(@RequestBody AuthParams authParams) throws Exception {
    UserDetails userDetails=userService.loadUserByUsername(authParams.Mat_Pers);

    try {
        authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken( authParams.Mat_Pers,authParams.MDP));

    } catch (BadCredentialsException e) {
        throw new Exception("INVALID_CREDENTIALS",e);
    } catch (InternalAuthenticationServiceException e){
        throw new Exception("INVALID_CREDENTIALS" ,e);
    }
    SecurityContext context = SecurityContextHolder.getContext();
    Authentication authentication = context.getAuthentication();
    String username = authentication.getName();
    Object principal = authentication.getPrincipal();
    String token = tokenGeneration.generateToken(userDetails);
    JwtResponse jwtResponse=new JwtResponse(token);
    return new ResponseEntity<>(jwtResponse,HttpStatus.OK);
}

它在成功验证后创建 jwt 令牌,然后返回它

loaduserByUsername 方法看起来像这样

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    User user = getUser(username);
    if (user == null) {
        throw new UsernameNotFoundException("User not found");
    }

    return user;
}

现在的问题是,每当我向 /users 端点发出 POST 请求时,我都会收到 403 forbidden 错误,这意味着用户已通过身份验证,但 hasRole 函数返回 false

我真的把这里的每一个问题都找遍了,但是我并没有找到hasRole比较给定值的值是什么

我什至问了问题到chatGPT,但我没有得到我想要的答案

我希望有人能帮助解决这个问题,在此先感谢

spring-boot spring-security one-to-many basic-authentication roles
© www.soinside.com 2019 - 2024. All rights reserved.