原文地址:https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage

Update 5/12/2016: Building a Java application? JJWT is a Java library providing end-to-end JWT creation and verification, developed by our very own Les Hazlewood. Forever free and open-source (Apache License, Version 2.0), JJWT is simple to use and understand. It was designed with a builder-focused fluent interface hiding most of its complexity. We’d love to have you try it out, and let us know what you think! (And, if you’re a Node developer, check out NJWT!)

Stormpath has recently worked on token authentication features using JSON Web Tokens (JWT), and we have had many conversations about the security of these tokens and where to store them.

If you are curious about your options, this post is for you. We will cover the basics of JSON Web Tokens (JWT) vs. OAuth, token storage in cookies vs. HTML5 web storage (localStorage or sessionStorage), and basic security information about cross-site scripting (XSS) and cross-site request forgery (CSRF).

Let’s get started…

JSON Web Tokens (JWT): A Crash Course

The most implemented solutions for API authentication and authorization are the OAuth 2.0 and JWT specifications, which are fairly dense. Cliff’s Notes Time! Here’s what you need to know about JWT vs OAuth:

  • JWTs are a great authentication mechanism. They give you a structured and stateless way to declare a user and what they can access. They can be cryptographically signed and encrypted to prevent tampering on the client side.
  • JWTs are a great way to declare information about the token and authentication. You have a ton of freedom to decide what makes sense for your application because you are working with JSON.
  • The concept behind scopes is powerful yet incredibly simple: you have the freedom to design your own access control language because, again, you are working with JSON.

If you encounter a token in the wild, it looks like this:

This is a Base64 encoded string. If you break it apart you’ll actually find three separate sections:

The first section is a header that describes the token. The second section is a payload which contains the juicy bits, and the third section is a signature hash that can be used to verify the integrity of the token (if you have the secret key that was used to sign it).

When we magically decode the second section, the payload, we get this nice JSON object:

This is the payload of your token. It allows you to know the following:

  • Who this person is (sub, short for subject)
  • What this person can access with this token (scope)
  • When the token expires (exp)
  • Who issued the token (iss, short for issuer)

These declarations are called ‘claims’ because the token creator claims a set of assertions that can be used to ‘know’ things about the subject. Because the token is signed with a secret key, you can verify its signature and implicitly trust what is claimed.

Tokens are given to your users after they present some credentials, typically a username and password, but they can also provide API keys, or even tokens from another service. This is important because it is better to pass a token (that can expire, and have limited scope) to your API than a username and password. If the username and password are compromised in a man-in-the-middle attack, it is like giving an attacker keys to the castle.

Stormpath’s API Key Authentication Feature is an example of this. The idea is that you present your hard credentials once, and then get a token to use in place of the hard credentials.

The JSON Web Token (JWT) specification is quickly gaining traction. Recommended highly by Stormpath, it provides structure and security, but with the flexibility to modify it for your application. Here is a longer article on it: Use JWT the Right Way!

Where to Store Your JWTs

So now that you have a good understanding of what a JWT is, the next step is to figure out how to store these tokens. If you are building a web application, you have a couple of options:

  • HTML5 Web Storage (localStorage or sessionStorage)
  • Cookies

To compare these two, let’s say we have a fictitious AngularJS or single page app (SPA) called galaxies.com with a login route (/token) to authenticate users to return a JWT. To access the other APIs endpoints that serve your SPA, the client needs to pass a valid JWT.

The request that the single page app makes would resemble:

Your server’s response will vary based on whether you are using cookies or Web Storage. For comparison, let’s take a look at how you would do both.

JWT localStorage or sessionStorage (Web Storage)

Exchanging a username and password for a JWT to store it in browser storage (sessionStorage or localStorage) is rather simple. The response body would contain the JWT as an access token:

On the client side, you would store the token in HTML5 Web Storage (assuming that we have a success callback):

To pass the access token back to your protected APIs, you would use the HTTP Authorization Header and the Bearer scheme. The request that your SPA would make would resemble:

Exchanging a username and password for a JWT to store it in a cookie is simple as well. The response would use the Set-Cookie HTTP header:

To pass the access token back to your protected APIs on the same domain, the browser would automatically include the cookie value. The request to your protected API would resemble:

So, What’s the difference?

If you compare these approaches, both receive a JWT down to the browser. Both are stateless because all the information your API needs is in the JWT. Both are simple to pass back up to your protected APIs. The difference is in the medium.

JWT sessionStorage and localStorage Security

Web Storage (localStorage/sessionStorage) is accessible through JavaScript on the same domain. This means that any JavaScript running on your site will have access to web storage, and because of this can be vulnerable to cross-site scripting (XSS) attacks. XSS, in a nutshell, is a type of vulnerability where an attacker can inject JavaScript that will run on your page. Basic XSS attacks attempt to inject JavaScript through form inputs, where the attacker puts <script>alert('You are Hacked');</script>into a form to see if it is run by the browser and can be viewed by other users.

To prevent XSS, the common response is to escape and encode all untrusted data. But this is far from the full story. In 2015, modern web apps use JavaScript hosted on CDNs or outside infrastructure. Modern web apps include 3rd party JavaScript libraries for A/B testing, funnel/market analysis, and ads. We use package managers like Bower to import other peoples’ code into our apps.

What if only one of the scripts you use is compromised? Malicious JavaScript can be embedded on the page, and Web Storage is compromised. These types of XSS attacks can get everyone’s Web Storage that visits your site, without their knowledge. This is probably why a bunch of organizations advise not to store anything of value or trust any information in web storage. This includes session identifiers and tokens.

As a storage mechanism, Web Storage does not enforce any secure standards during transfer. Whoever reads Web Storage and uses it must do their due diligence to ensure they always send the JWT over HTTPS and never HTTP.

Cookies, when used with the HttpOnly cookie flag, are not accessible through JavaScript, and are immune to XSS. You can also set the Secure cookie flag to guarantee the cookie is only sent over HTTPS. This is one of the main reasons that cookies have been leveraged in the past to store tokens or session data. Modern developers are hesitant to use cookies because they traditionally required state to be stored on the server, thus breaking RESTful best practices. Cookies as a storage mechanism do not require state to be stored on the server if you are storing a JWT in the cookie. This is because the JWT encapsulates everything the server needs to serve the request.

However, cookies are vulnerable to a different type of attack: cross-site request forgery (CSRF). A CSRF attack is a type of attack that occurs when a malicious web site, email, or blog causes a user’s web browser to perform an unwanted action on a trusted site on which the user is currently authenticated. This is an exploit of how the browser handles cookies. A cookie can only be sent to the domains in which it is allowed. By default, this is the domain that originally set the cookie. The cookie will be sent for a request regardless of whether you are on galaxies.com or hahagonnahackyou.com.

CSRF works by attempting to lure you to hahagonnahackyou.com. That site will have either an img tag or JavaScript to emulate a form post to galaxies.com and attempt to hijack your session, if it is still valid, and modify your account.

For example:

Both would send the cookie for galaxies.com and could potentially cause an unauthorized state change. CSRF can be prevented by using synchronized token patterns. This sounds complicated, but all modern web frameworks have support for this.

For example, AngularJS has a solution to validate that the cookie is accessible by only your domain. Straight from AngularJS docs:

When performing XHR requests, the $http service reads a token from a cookie (by default, XSRF-TOKEN) and sets it as an HTTP header (X-XSRF-TOKEN). Since only JavaScript that runs on your domain can read the cookie, your server can be assured that the XHR came from JavaScript running on your domain.

You can make this CSRF protection stateless by including a xsrfToken JWT claim:

If you are using the Stormpath SDK for AngularJS, you get stateless CSRF protection with no development effort.

Leveraging your web app framework’s CSRF protection makes cookies rock solid for storing a JWT. CSRF can also be partially prevented by checking the HTTP Referer and Origin header from your API. CSRF attacks will have Referer and Origin headers that are unrelated to your application.

Even though they are more secure to store your JWT, cookies can cause some developer headaches, depending on if your applications require cross-domain access to work. Just be aware that cookies have additional properties (Domain/Path) that can be modified to allow you to specify where the cookie is allowed to be sent. Using AJAX, your server side can also notify browsers whether credentials (including Cookies) should be sent with requests with CORS.

Conclusion

JWTs are an awesome authentication mechanism. They give you a structured way to declare users and what they can access. They can be encrypted and signed for to prevent tampering on the client side, but the devil is in the details and where you store them. Stormpath recommends that you store your JWT in cookies for web applications, because of the additional security they provide, and the simplicity of protecting against CSRF with modern web frameworks. HTML5 Web Storage is vulnerable to XSS, has a larger attack surface area, and can impact all application users on a successful attack.

转载于:https://www.cnblogs.com/davidwang456/p/6550413.html

Where to Store your JWTs – Cookies vs HTML5 Web Storage--转相关推荐

  1. HTML5 Web Storage用法

    早期的网页数据存储只能依赖于cookies,但它存在着容量有限且很小,不便于复杂数据的管理等问题,此外,还需将cookies附带在每一次网络请求之中.HTML5的出现,极大地增加了开发人员的开发灵活度 ...

  2. html5 web storage攻击,HTML5安全风险详析之二:Web Storage攻击

    **一.WebStorage简介** HTML5支持WebStorage,开发者可以为应用创建本地存储,存储一些有用的信息.例如LocalStorage可以长期存储,而且存放空间很大,一般是5M,极大 ...

  3. 使用 jQuery Mobile 与 HTML5 开发 Web App (十六) —— HTML5 Web Storage

    绝大多数的软件都需要使用某种具有持久性的方式来存储数据,Web Apps 也不例外,涉及到完整后台的 Web Apps ,可以直接在后台使用 mysql 等数据库来存储数据,但过多的 sql 查询会影 ...

  4. HTML5 Web Storage事件

    Storage事件 在某些复杂情况下,如果多个页面都需要访问本地存储的数据,就需要在存储区域的内容发生改变时,能够通知相关的页面. Web Storage API内建了一套事件通知机制,当存储区域的内 ...

  5. HTML5 Web Storage API

    Web Storage API Web Storage 是以键值对(key-value)的形式存储数据,要存储的数据需要一个名字作为键,然后就可以使用这个键来读取它的值.键是一个字符串.值可以是 Ja ...

  6. 四种有能力取代Cookies的客户端Web存储方案

    目前在用户的网络浏览器中保存大量数据需要遵循几大现有标准,每一种标准都拥有自己的优势.短板.独特的W3C标准化状态以及浏览器支持级别.但无论如何,这些标准的实际表现都优于广泛存在的cookies机制. ...

  7. HTML5 基础知识,第 3 部分 HTML5 API 之应用-介绍HTML5 API 的用法和价值,Canvas 提供的创造性,以及Web storage的离线应用

    HTML5 集设计者和开发者于一身,其主要任务就是构建高效的丰富 Internet 应用程序之富网络应用 (Rich Internet Application,简称RIA),尤其是富 UI(User ...

  8. HTML5 Web存储(Web Storage)技术以及用法

    使用HTML5可以在本地存储用户的浏览数据.早些时候,本地存储使用的是 cookie.但是Web 存储需要更加的安全与快速,这些数据不会被保存在服务器上,但是这些数据只用于用户请求网站数据上.它也可以 ...

  9. HTML5权威指南--Web Storage,本地数据库,本地缓存API,Web Sockets API,Geolocation API(简要学习笔记二)...

    1.Web Storage HTML5除了Canvas元素之外,还有一个非常重要的功能那就是客户端本地保存数据的Web Storage功能. 以前都是用cookies保存用户名等简单信息. 但是coo ...

最新文章

  1. 从java中的hibernate看Ado.net 与NHibernate的关系
  2. ML之回归预测:利用13种机器学习算法对Boston(波士顿房价)数据集【13+1,506】进行回归预测(房价预测)来比较各模型性能
  3. 如何使用SAP Analytics Cloud统计C4C系统每天新建的Lead个数和预测趋势
  4. python人脸识别环境搭建_人脸识别:Windows10系统环境搭建
  5. PHP操作Redis常用技巧
  6. Google Cloud TPUs支持Pytorch框架啦!
  7. 小米手机硬改技术_小米11手机爆料:首发骁龙875 或采用屏下摄像头技术
  8. windows mobile设置插移动卡没反应_u盘插入电脑没反应怎么办 u盘插入电脑没反应解决方法【详解】...
  9. APS技术中的多目标规划问题
  10. jQuery判断浏览器是移动端还是电脑端自动跳转
  11. linux的4k播放器,【Linux1GB4K(3840*2160)电视播放器】Linux1GB4K(3840*2160)电视播放器报价及图片大全-列表版-ZOL中关村在线...
  12. 如何使用Python实现一个pdf阅读器?
  13. UnicodeEncodeError: ‘gbk‘ codec can‘t encode character ‘\u25aa‘ in position 11923: illegal multibyte
  14. Web前端 HTML 基本结构标签
  15. 百度冰桶算法4.5更新:发力打击恶劣广告行为
  16. 2015.05.05,外语,读书笔记-《Word Power Made Easy》 15 “如何谈论事情进展” SESSION 42...
  17. 昨夜“星城”昨夜“疯”
  18. 计算机网卡更改mac地址,Mac电脑网卡MAC地址修改的具体步骤
  19. 哪个工具可以保护计算机免受ESD的影响,可以避免ESD影响的实用解决方案
  20. (一)航空发动机强度与振动复习纲要

热门文章

  1. php 不刷新提交,提交表单而不刷新页面ajax,php,javascript?
  2. 常用的java虚拟机_带你了解 JAVA虚拟机 面试必备
  3. xman的思维导图快捷键_一次性入门大纲笔记神器“幕布”,支持一键生成思维导图...
  4. 复杂查询练习_《从零学会SQL:简单查询》第二关 简单查询
  5. matlab用辛普森公式求积分_如何用Excel公式求最大值对应的行列序号
  6. java 判断是否是日期_java判断是否为日期的方法(附代码)
  7. 部署必备之Docker
  8. Pytorch学习 - 保存模型和重新加载
  9. orb_slam 编译错误
  10. python zip