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

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

我想在我的应用程序中收到用户名的电子邮件,以设置发送邮件的用户。我决定使用典型的方法,即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);
}

和MessageRequest.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"
}
spring spring-boot post spring-security authorization
1个回答
0
投票
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();
        }
© www.soinside.com 2019 - 2024. All rights reserved.