spring-security 在不调用findByUsername的情况下获取其他安全用户字段

monwx1rj  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(131)

我正在调用findUserByUsername()方法以获取User实体中的name字段,我想知道是否有更好的方法来完成此操作,而不必执行其他查询
AuthenticationController.java

@PostMapping("/login")
    public ResponseEntity<AuthenticationResponse> login (@RequestBody AuthenticationRequest userLogin) {
        try {
            Authentication authentication = authenticationManager
                    .authenticate(new UsernamePasswordAuthenticationToken(userLogin.username(), userLogin.password()));
            String token = tokenService.generateToken(authentication);

            Optional<User> user = userRepository.findByUsername(authentication.getName());

            AuthenticationResponse response = new AuthenticationResponse(user.get().getName(), token);

            return ResponseEntity.ok().body(response);

        } catch (BadCredentialsException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
    }

SecurityUser.java

public class SecurityUser implements UserDetails {

    private final User user;

    public SecurityUser (User user) {
        this.user = user;
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return user
                .getRoles()
                .stream()
                .map(role -> new SimpleGrantedAuthority(role.getName()))
                .collect(Collectors.toSet());
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    @Override
    public String toString() {
        return "SecurityUser{" +
                "user=" + user +
                '}';
    }
}
w9apscun

w9apscun1#

根据您的安全配置设置,您可以使用authentication.getName(),因为它通常Map到用户名字段。例如,formLogin()就是这种情况,它使用了隐藏的DaoAuthenticationProvider

相关问题