简体   繁体   English

Httponly cookie 作为不记名令牌 - Laravel Passport

[英]Httponly cookie as bearer token - Laravel Passport

I have began building an application using React JS and Laravel 5.5.我已经开始使用 React JS 和 Laravel 5.5 构建应用程序。 I have installed the Laravel Passport and have successfully managed to log my user in and out in my React JS app - but I have been told to look into using httponly cookies for security purposes.我已经安装了 Laravel Passport 并成功地在我的 React JS 应用程序中登录和注销了我的用户 - 但我被告知为了安全目的考虑使用 httponly cookie。

In my working code, I have simply stored the access token in localStorage and sent it to the api using Authorization': 'Bearer ' + token in the axios headers, and this works perfectly.在我的工作代码中,我只是将访问令牌存储在 localStorage 中,并使用Authorization': 'Bearer ' + token axios 标头中的Authorization': 'Bearer ' + token将其发送到 api,这非常有效。 However, when I set a cookie using httponly I can't fetch the value of it (which I assume is exactly the point!) - using react-cookie (from npm), if I log cookie.loadAll() to the console then the only cookie I see is a new XSRF-TOKEN cookie, but not the accessToken cookie I set.但是,当我使用 httponly 设置 cookie 时,我无法获取它的值(我认为这正是重点!) - 使用 react-cookie(来自 npm),如果我将cookie.loadAll()到控制台然后我看到的唯一 cookie 是一个新的XSRF-TOKEN cookie,但不是我设置的accessToken cookie。 So how do I go about sending this token to the api?那么我该如何将这个令牌发送到 api 呢?

由于您无法从 JS 读取 httpOnly cookie,因此当从后端获取新令牌时,后端必须在响应正文中发送令牌。

Browser session cookie usage and bearer tokens are different strategies of authentication (cookie based and token based).浏览器会话 cookie 使用和承载令牌是不同的身份验证策略(基于 cookie 和基于令牌)。

In my opinion they should not be mixed.在我看来,它们不应该混在一起。

Lavavel passport supports authentication with bearer token or with cookie out of the box (see condition at TokenGuard user ) You have to use Passport::cookie for this. Lavavel 护照支持使用不记名令牌或开箱即用的 cookie 进行身份验证(请参阅TokenGuard 用户处的条件) 为此您必须使用Passport::cookie

In this case you will be able to set cookie and use HttpOnly flag with other attributes to secure them.在这种情况下,您将能够设置 cookie 并使用HttpOnly标志和其他属性来保护它们。

Httponly cookie as bearer token doesn't make much sense. Httponly cookie 作为不记名令牌没有多大意义。 Having cookies httponly helps to protect you and the user against XSS attack as their not readable by javascript.拥有 cookie httponly 有助于保护您和用户免受 XSS 攻击,因为它们无法被 javascript 读取。 They can be used eg for storing session information and are sent when the user do eg a page reload.它们可以用于例如存储会话信息并在用户执行例如页面重新加载时发送。

Setting Authorization header to 'Bearer ' + token is correct way how to sent token to the api.将 Authorization 标头设置为'Bearer ' + token是如何将令牌发送到 api 的正确方法。 Before using token on the api server you should always check if the token is still valid.在 api 服务器上使用令牌之前,您应该始终检查令牌是否仍然有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM