我正在调用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 +
'}';
}
}
1条答案
按热度按时间w9apscun1#
根据您的安全配置设置,您可以使用
authentication.getName()
,因为它通常Map到用户名字段。例如,formLogin()
就是这种情况,它使用了隐藏的DaoAuthenticationProvider
。