Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 如何在@RestController中获取用户?_Spring_Rest_Spring Boot_Spring Security_Jwt - Fatal编程技术网

Spring 如何在@RestController中获取用户?

Spring 如何在@RestController中获取用户?,spring,rest,spring-boot,spring-security,jwt,Spring,Rest,Spring Boot,Spring Security,Jwt,我正在创建基于jwt的身份验证。这是一种魅力。 我已经通过帖子在@restcontroller中创建了注册和登录方法 现在,我需要创建updateuser方法。 用于更新已登录用户本身的信息 在JWT之前,我们通常从会话中获取已登录用户的id。如何使用JWT实现这一点 @PostMapping("/user/profile") public ResponseEntity<?> saveProfile(@Valid @RequestBody UserProfileDTO userPro

我正在创建基于jwt的身份验证。这是一种魅力。 我已经通过帖子在@restcontroller中创建了注册和登录方法

现在,我需要创建updateuser方法。 用于更新已登录用户本身的信息

在JWT之前,我们通常从会话中获取已登录用户的id。如何使用JWT实现这一点

@PostMapping("/user/profile")
public ResponseEntity<?> saveProfile(@Valid @RequestBody UserProfileDTO userProfile) {

    /*  Of course the userPofileForm does not contain a hidden field 
        with the ID of the user because it woud allow the user to mofify 
         it and update another user.
    */

    return null;
}
@PostMapping(“/user/profile”)
公共响应属性保存配置文件(@Valid@RequestBody UserProfileDTO userProfile){
/*当然,userPofileForm不包含隐藏字段
使用用户的ID,因为这将允许用户进行mofif
并更新另一个用户。
*/
返回null;
}

尝试将
用户id
添加到jwt的主体中,并为每个经过身份验证的请求接受头中的jwt令牌

  • 一旦您的控制器能够获取jwt令牌,请解密它并获取用户Id
  • 在对jwt令牌进行身份验证时,将身份验证添加到SecurityContextHolder,并在应用程序中的任何位置获取用户身份验证

  • 这是一个如何解决此问题的示例:

    @PostMapping("/user/profile")
    public ResponseEntity<?> saveProfile(@Valid @RequestBody UserProfileDTO userProfile,Principal userLogin) {
    String username=userLogin.getName();
    return username;
    }
    
    @PostMapping(“/user/profile”)
    公共响应属性保存配置文件(@Valid@RequestBody userprofiled到userProfile,主体userLogin){
    字符串username=userLogin.getName();
    返回用户名;
    }
    
    检查并确认