首页 > 解决方案 > Spring 配置 Principal.getname() 以返回 JWT 电子邮件声明

问题描述

我目前正在从以下地址收到用户的电子邮件SecurityContextHolder

Jwt jwt = (Jwt) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return jwt.getClaims().get("email").toString();

有没有办法配置Principal.getName()它直接返回电子邮件以避免控制器中 Jwt 的特定知识?例如:

  @PutMapping("/reserve")
  public Object reserveGame(Principal principal) {
    String email = principal.getName(); // need this to return email
    return dao.reserveGame(email);
  }

标签: springspring-bootspring-security

解决方案


覆盖您的 UserDetails 类方法getUsername()并返回email属性。或者您可以提供自定义UserAuthenticationConverter


推荐阅读