将 JWT 令牌存储在 cookie 中 [英] Store JWT token in cookie

查看:47
本文介绍了将 JWT 令牌存储在 cookie 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的设置:

  • 1 个认证服务器,它在成功时发出 JWT 令牌身份验证.
  • 提供信息的多个 API 资源服务器(当用户已通过身份验证).

现在我想构建我的 ASP.NET MVC 前端.是否可以将我在身份验证后收到的令牌放入 cookie 中,以便我可以在每次需要进行的安全调用时访问它?我使用 RestSharp DLL 进行 http 调用.如果它有安全漏洞,那么我应该在哪里存储我的令牌?

Now I want to build my ASP.NET MVC frontend. Is it ok to take the token, which I receive after authentication, and put it in a cookie so I can access it with every secured call I need to make? I use the RestSharp DLL for doing my http calls. If it has a security flaw, then where should I store my token?

我会将此代码用于 cookie:

I would use this code for the cookie:

            System.Web.HttpContext.Current.Response.Cookies.Add(new System.Web.HttpCookie("Token")
        {
            Value = token.access_token,
            HttpOnly = true
        });

推荐答案

您走在正确的道路上!cookie 应始终具有 HttpOnly 标志,设置此标志将阻止 JavaScript 环境(在 Web 浏览器中)访问 cookie.这是防止浏览器中 XSS 攻击的最好方法.

You’re on the right path! The cookie should always have the HttpOnly flag, setting this flag will prevent the JavaScript environment (in the web browser) from accessing the cookie. This is the best way to prevent XSS attacks in the browser.

您还应该在生产中使用 Secure 标志,以确保 cookie 仅通过 HTTPS 发送.

You should also use the Secure flag in production, to ensure that the cookie is only sent over HTTPS.

您还需要防止 CSRF 攻击.这通常是通过在另一个 cookie 中设置一个值来完成的,每个请求都必须提供该值.

You also need to prevent CSRF attacks. This is typically done by setting a value in another cookie, which must be supplied on every request.

我在 Stormpath 工作,我们撰写了大量有关前端安全的信息.这两个帖子可能有助于理解所有方面:

I work at Stormpath and we’ve written a lot of information about front-end security. These two posts may be useful for understanding all the facets:

单页应用程序 (SPA) 的基于令牌的身份验证

https://stormpath.com/blog/build-secure-user-interfaces-using-jwts/

这篇关于将 JWT 令牌存储在 cookie 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆