Oauth2 从令牌中获取用户名

RK3*_*RK3 6 rest spring oauth-2.0 spring-boot spring-security-oauth2

我已经实现了 Ouath2 作为我的 Spring boot rest 控制器的安全性。在调用我的任何资源之前,oauth2 会验证用户表中用户的令牌。我的问题是如何避免如果 user1 令牌在请求中并且请求正文具有用于 user2 修改的数据的情况?我需要进行检查,以便 User1 和他的令牌应该只能为他自己修改数据。如果 user1 和他的 toekn 在请求正文中有 user2 数据应该抛出 403。

我在想是否可以从服务层的令牌中获取用户名来进行此检查?任何帮助表示赞赏

MyT*_*nts 5

您正在使用 Spring Security 进行身份验证。

您可以从 SecurityContext 获取用户详细信息

Authentication authentication = SecurityContextHolder.getContext()
    .getAuthentication();

UserDetails userDetail = authentication.getPrincipal();
userDetail.getUsername();
Run Code Online (Sandbox Code Playgroud)

或在休息控制器中

@RequestMapping(value = "/username", method = RequestMethod.GET)
public String currentUserName(Principal principal) {
    return principal.getName();
}
Run Code Online (Sandbox Code Playgroud)

或者

@RequestMapping(value = "/username", method = RequestMethod.GET)
public String currentUserName(HttpServletRequest request) {
    Principal principal = request.getUserPrincipal();

    return principal.getName();
}
Run Code Online (Sandbox Code Playgroud)