Java 如何在Spring Security上从CustomUser获取用户ID
使用Sign Spring Security,我试图从CustomUserDetails服务上的loadUserByUsername方法返回的CustomUser实例中获取用户id,就像通过身份验证获取名称(get.Name())一样。谢谢你的提示 这是我获取已登录用户当前名称的方式:Java 如何在Spring Security上从CustomUser获取用户ID,java,spring,authentication,spring-security,Java,Spring,Authentication,Spring Security,使用Sign Spring Security,我试图从CustomUserDetails服务上的loadUserByUsername方法返回的CustomUser实例中获取用户id,就像通过身份验证获取名称(get.Name())一样。谢谢你的提示 这是我获取已登录用户当前名称的方式: Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String name = auth
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String name = authentication.getName();
这是CustomUser
public class CustomUser extends User {
private final int userID;
public CustomUser(String username, String password, boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired,
boolean accountNonLocked,
Collection<? extends GrantedAuthority> authorities, int userID) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
this.userID = userID;
}
}
如果尚未添加
getUserId()
getter方法,则必须添加该方法。您可以在控制器中获取userId,如下所示。从这里获取更多信息。请记住,您在创建JWT时已将所需的身份验证信息设置到JWT中,以便使用它们
@Controller
public class GetUserWithHTTPServletRequestController {
@RequestMapping(value = "/username", method = RequestMethod.GET)
@ResponseBody
public String currentUserNameSimple(HttpServletRequest request) {
Principal principal = request.getUserPrincipal();
return principal.getName();
}
}
或如下所示
@PostMapping(value = "/sample")
public String sample(@RequestBody SampleDto sampleDto, Principal principal) {
String username = principal.getName();
// You can get other Auth details from principal Object
return "success";
}
主体
可以注入。通过方法参数注入:@AuthenticationPrincipal CustomUser
@Controller
public class GetUserWithHTTPServletRequestController {
@RequestMapping(value = "/username", method = RequestMethod.GET)
@ResponseBody
public String currentUserNameSimple(HttpServletRequest request) {
Principal principal = request.getUserPrincipal();
return principal.getName();
}
}
@PostMapping(value = "/sample")
public String sample(@RequestBody SampleDto sampleDto, Principal principal) {
String username = principal.getName();
// You can get other Auth details from principal Object
return "success";
}