【问题标题】:Spring Security - Authenticate user with usernameSpring Security - 使用用户名验证用户
【发布时间】:2022-04-10 03:37:20
【问题描述】:

我只想用用户名验证用户。为此,我仍在使用UsernamePasswordAuthenticationToken,但也通过了额外的权限。
下面是代码:

List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
Authentication authentication = authenticationManager.authenticate(
    new UsernamePasswordAuthenticationToken(username,null,authorities)
);

不幸的是,这会引发错误的凭据异常。我在这里错过了什么?
当用正确的用户名密码替换上面的代码时,它可以完美地工作。

Authentication authentication = authenticationManager.authenticate(
    new UsernamePasswordAuthenticationToken(username,password,authorities)
);

【问题讨论】:

    标签: java spring-boot authentication spring-security jwt


    【解决方案1】:

    如果您已经知道 AuthenticationManager 已通过身份验证,则无需使用它们。 您可以直接设置Authentication,如下所示:

    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
    Authentication authentication = new UsernamePasswordAuthenticationToken(username, null, authorities);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    

    【讨论】:

      【解决方案2】:

      谢谢@ismail,我试过了,它成功了。

      refreshTokenService.validateRefreshToken(refreshTokenRequest.getRefreshToken());
      User user = userRepository.findByUsername(refreshTokenRequest.getUsername());
      List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
      user.getRoles().forEach(role -> grantedAuthorities.add(new SimpleGrantedAuthority(role.getRoleName())));
      Authentication authentication = new UsernamePasswordAuthenticationToken(user.getUsername(), null, grantedAuthorities);
      return AuthenticationResponse.builder()
               .authenticationToken(jwtUtil.generateToken(authentication))
               .refreshToken(refreshTokenRequest.getRefreshToken())
               .username(user.getUsername())
               .build();
      

      【讨论】:

        猜你喜欢
        • 2013-12-28
        • 2021-03-28
        • 2012-09-04
        • 2012-04-14
        • 1970-01-01
        • 2016-06-26
        • 1970-01-01
        • 2016-04-30
        • 2020-04-16
        相关资源
        最近更新 更多