如何在Spring Security [UserDetails/String]中获取用户名(在我的情况下是电子邮件)



我想在我的应用程序中获取用户名的电子邮件,以设置发送消息的用户。我决定使用典型的方法,即 principal 和 getUsername((:

@PostMapping("/messages/{id}")
@ResponseStatus(HttpStatus.CREATED)
public MessageDTO addOneMessage(@RequestBody MessageRequest messageRequest, @PathVariable ("id") Long id) {
checkIfChannelExists(id);
String content = messageRequest.getContent();
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = ((UserDetails) principal).getUsername();
Employee author = employeeRepository.findByEmail(username).get();
Message message = new Message(content, author, id);
messageRepository.save(message);
return new MessageDTO(message);
}

和消息请求.java:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class MessageRequest {
@NonNull
private String content;
}

但是,通过这种方式,我仍然得到:

"message": "java.lang.String cannot be cast to org.springframework.security.core.userdetails.UserDetails"

我的实施中出了什么问题?更准确地说,我使用 Postman 来测试 POST 请求:

{
"content": "something"
}
If you only need to retrieve the username you can get it through Authentication ie.
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();

而不是类型转换到你的类 SpringContext 提供关于用户的几乎所有细节。 如果希望控制器获取要测试的用户名。 请使用此代码。

//using authentication
@RequestMapping(value = "/name", method = RequestMethod.GET)
@ResponseBody
public String currentUserName(Authentication authentication) {
return authentication.name();
}
//using principal   
@RequestMapping(value = "/name", method = RequestMethod.GET)
@ResponseBody
public String currentUserName(Principal principal) {
return principal.getName();
}

相关内容

最新更新