SpringBoot如何从ReactJS获取当前用户?

时间:2019-03-23 19:04:21

标签: spring reactjs spring-boot login-control

我试图通过https://github.com/callicoder/spring-security-react-ant-design-polls-app了解Full-stack Web应用程序的代码 但是我不明白spring-boot如何知道当前的用户正在登录。

这是调用api的ReactJS(前端)代码。

export function getUserCreatedPolls(username, page, size) {
    page = page || 0;
    size = size || POLL_LIST_SIZE;

    return request({
        url: API_BASE_URL + "/users/" + username + "/polls?page=" + page + "&size=" + size,
        method: 'GET'
    });
}

而且,这是从前端接收变量的spring-boot(后端)代码

@GetMapping("/users/{username}/polls")
public PagedResponse<PollResponse> getPollsCreatedBy(@PathVariable(value = "username") String username,
                                                     @CurrentUser UserPrincipal currentUser,
                                                     @RequestParam(value = "page", defaultValue = AppConstants.DEFAULT_PAGE_NUMBER) int page,
                                                     @RequestParam(value = "size", defaultValue = AppConstants.DEFAULT_PAGE_SIZE) int size) {
    return pollService.getPollsCreatedBy(username, currentUser, page, size);
}
  1. spring-boot如何从前端获取{UserPrincipal currentUser}?
  2. ReactJs如何将{UserPrincipal currentUser}发送到后端?

1 个答案:

答案 0 :(得分:1)

  • 这是一个春季启动 oauth jwt provider +资源​​服务器,而ReactJs作为消费者

enter image description here

  • ReactJs可以通过发送和 HTTP请求来消耗服务器资源(rest api),但是它首先应该获得该(令牌)的授权
  • 成功登录后,服务器将发送 JWT令牌
  • 然后,当reacteJ发送HTTP请求时,它实际上会向HTTP请求注入额外的信息,即授权令牌
  • 当服务器收到此请求并在其到达控制器之前,请求传递会抛出一个过滤器链(春季安全过滤器链) ),请在成功的用户身份验证后,调用代码 SecurityContextHolder 类以填充安全上下文,然后在代码link中查看此过滤器类方法 strong>与当前已通过身份验证的用户(用户原则),最后,当请求 到达控制器时,我们的安全上下文填满
  • @CurrentUser UserPrincipal currentUser,将 UserPrincipal currentUser 参数添加到 Controller 方法中后,它将自动从上下文填充对象,您可以您可以通过调用 SecurityContextHolder 类自行获取它,并获取当前的已验证用户

     ...
    
     // Get The Jwt token from the HTTP Request
     String jwt = getJwtFromRequest(request);
     // Check The validation of JWT - if true the user is trusted
     if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
      Long userId = tokenProvider.getUserIdFromJWT(jwt);
    
      /*
          Note that you could also encode the user's username and roles inside JWT claims
          and create the UserDetails object by parsing those claims from the JWT.
          That would avoid the following database hit. It's completely up to you.
       */
      // Get the user object
      UserDetails userDetails = customUserDetailsService.loadUserById(userId);
      UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
      authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
      // Fill the security context with this user 
      SecurityContextHolder.getContext().setAuthentication(authentication);
    
     ...