【问题标题】:How does SpringBoot get current user from ReactJS?Spring Boot 如何从 React JS 获取当前用户?
【发布时间】:2019-03-23 19:04:20
【问题描述】:

我试图在https://github.com/callicoder/spring-security-react-ant-design-polls-app 了解全栈网络应用程序的代码 但我不明白 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(back-end) 代码

@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} 发送到后端?

【问题讨论】:

    标签: spring reactjs spring-boot login-control


    【解决方案1】:
    • 它是一个 Spring Boot oauth jwt 提供者 + 资源服务器 和 ReactJs 作为 消费者

    • ReactJs 可以通过发送 HTTP 请求 来消耗服务器资源(rest api),但它应该首先获得该(令牌)的授权
    • 登录成功后服务器会发送JWT token
    • 那么当 reacteJs 发送 HTTP 请求时,它实际上会向 HTTP 请求注入额外的信息,即 授权令牌
    • 当服务器收到这个请求并且在它到达控制器之前,请求通过抛出一个过滤器链(弹簧安全过滤器链),看看代码link中的这个过滤器类方法,在用户认证成功调用SecurityContextHolder填充安全上下文使用当前经过身份验证的用户(用户原则),最后当请求 到达控制器,我们的安全上下文填满
    • @CurrentUser UserPrincipal currentUser ,当你在 spring Controller 方法中添加 UserPrincipal currentUser 参数时,它会自动从上下文中填充对象,你可以自己做调用 SecurityContextHolder 类并获取当前的authenticated User

       ...
      
       // 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);
      
       ...
      

    【讨论】:

      猜你喜欢
      • 2018-10-25
      • 2020-09-05
      • 2012-04-22
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      • 1970-01-01
      • 2021-11-17
      相关资源
      最近更新 更多