【问题标题】:Laravel, Angular 7, JWT cookie storageLaravel、Angular 7、JWT cookie 存储
【发布时间】:2019-04-24 06:28:23
【问题描述】:

我需要在应用程序上实施 JWT 身份验证,我正在尝试通过使用 cookie 存储 (httpOnly) 而不是 localStorage 来尽可能多地降低风险。

Laravel 服务器设置为 API, 为 Angular 7 应用程序提供服务。登录控制器响应如下:

return response()->json($user)->cookie('access_token', $token, 15, '/', true, true);

在向登录 URL 发出 POST 请求后,我可以在响应中看到 cookie (token=blahblahblah)。我在登录后的所有请求中都设置了withCredentials: true。我可能会严重误解这一点,但我希望该 cookie 与每个后续请求一起发送,以验证我现在登录的用户。我在 Laravel 中的中间件正在寻找始终为空的 $request->cookie('access_token')

这甚至有可能实现吗?

【问题讨论】:

    标签: angular laravel cookies jwt angular7


    【解决方案1】:

    您可以使用 HttpInterceptor 并在“授权”标头中发送您的令牌,它将在每个请求中执行。

    https://angular.io/api/common/http/HttpInterceptor

    export class JwtInterceptor implements HttpInterceptor {
      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Clone the request to add the new header
    const clonedRequest = req.clone({ headers: req.headers.set('Authorization', 'YOUR_TOKEN') });
    
    // Pass the cloned request instead of the original request to the next handle
    return next.handle(clonedRequest);
    }}
    

    【讨论】:

      【解决方案2】:

      在 Laravel 中,您可以使用 Cookie 外观来“排队” cookie,以附加到应用程序的传出响应。

      queue 方法接受 Cookie 实例或创建 Cookie 实例所需的参数。这些 cookie 在发送到浏览器之前会附加到传出响应中

      Cookie::queue('name', 'value', $minutes, $path, $domain, $secure, $httpOnly);
      

      参考:Laravel doc for cookies

      【讨论】:

        猜你喜欢
        • 2016-04-30
        • 2020-10-06
        • 1970-01-01
        • 2020-11-22
        • 2019-02-18
        • 2021-11-16
        • 2015-09-15
        • 2016-09-13
        • 2021-04-04
        相关资源
        最近更新 更多