最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - Generate JWT token and Cookie in one API call - Stack Overflow

programmeradmin3浏览0评论

in my Spring/Angular application I want ensure, whether I going to correct way in security.


Logic about generating tokens have already done, but is correct following logic ?

This POST create a cookie and set this cookie to the browser.Inside of this cookie is generated XSRF-TOKEN for secure CSRF attacks, there is aswell .httpOnly(true) for unpossible get this token by javascript. This cookie is set automatically by BE, so FE don't need get this token from body or header of response. In BE configuration have a @Bean , which mark me this cookie as 'Strict'.

At the end, return of this authenticate() method is JWT Authorization Bearer token in body, which will be manually stored into cookies via Angular. If user is not authenticated and doesn't exist throw error.

    @PostMapping("/authenticate")
public ResponseEntity<AuthenticationResponse> authenticate(@RequestBody UserClient user, HttpServletResponse response, HttpServletRequest request){
    CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
            .getName());
    if (csrf != null) {
        Cookie cookie = new Cookie("XSRF-TOKEN", csrf.getToken());
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        //cookie.setSecure(true); // if using https
        response.addCookie(cookie);
    }
    return ResponseEntity.ok().body(loginService.authenticate(user));
}

Additional questions:

Is better idea separate these Tokens to 2 different endpoints ?

发布评论

评论列表(0)

  1. 暂无评论