| 背景
你已经或者正在实现API; 你正在考虑选择一个合适的方法保证API的安全性;
| JWT和OAuth2比较?
JWT是一种认证协议 JWT提供了一种用于发布接入令牌(Access Token),并对发布的签名接入令牌进行验证的方法。令牌(Token)本身包含了一系列声明,应用程序可以根据这些声明限制用户对资源的访问。 OAuth2是一种授权框架 OAuth2是一种授权框架,提供了一套详细的授权机制(指导)。用户或应用可以通过公开的或私有的设置,授权第三方应用访问特定资源。既然JWT和OAuth2没有可比性,为什么还要把这两个放在一起说呢?实际中确实会有很多人拿JWT和OAuth2作比较。标题里把这两个放在一起,确实有误导的意思。很多情况下,在讨论OAuth2的实现时,会把JSON Web Token作为一种认证机制使用。这也是为什么他们会经常一起出现。
| JSON Web Token (JWT)
JWT在标准中是这么定义的:
JSON Web Token (JWT) is a compact URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is digitally signed using JSON Web Signature (JWS). -RFC7519 https://tools.ietf.org/html/rfc7519
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
一个token包含三部分:
header.claims.signature
Header头部分头部分简单声明了类型(JWT)以及产生签名所使用的算法。
{ "alg" : "AES256", "typ" : "JWT"}
{ "sub": "1234567890", "name": "John Doe", "admin": true}
| OAuth2是什么?
相反,OAuth2不是一个标准协议,而是一个安全的授权框架。它详细描述了系统中不同角色、用户、服务前端应用(比如API),以及客户端(比如网站或移动App)之间怎么实现相互认证。
The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf. -RFC6749 https://tools.ietf.org/html/rfc6749
资源拥有者 资源服务器 客户端应用 认证服务器
私有的 公开的
Web应用 用户代理 原声应用
授权码 隐式授权 资源拥有者密码证书 客户端证书 Endpoints终端
认证终端 Token终端 重定向终端
使用HTTPS保护用户密码
| 结论
JWT使用场景
无状态的分布式API
快速开发 不需要cookie JSON在移动端的广泛应用 不依赖于社交登录 相对简单的概念理解
Token有长度限制 Token不能撤销 需要token有失效时间限制(exp) OAuth2使用场景
| 在作者看来两种比较有必要使用OAuth2的场景:
外包认证服务器
快速开发 实施代码量小 维护工作减少
大型企业解决方案
To be clear, OAuth 2.0 at the hand of a developer with deep understanding of web security will likely result is a secure implementation. However, at the hands of most developers – as has been the experience from the past two years – 2.0 is likely to produce insecure implementations. hueniverse - OAuth 2.0 and the Road to Hell
优势
灵活的实现方式
可以和JWT同时使用
可针对不同应用扩展
http://jwt.io - JWT官方网站,也可以查看到使用不同语言实现的库的状态。 http://oauth.net/2/ OAuth2官方网站, 也也可以查看到使用不同语言实现的库的状态。 OAuth 2 tutorials - Useful overview of how OAuth 2 works Oauth2 Spec issues Eran Hammer’s (推进OAuth标准的作者) views on what went wrong with the OAuth 2 spec process. Whatever your own opinion, good to get some framing by someone who understand’s key aspects of what make a security standard successful. Thoery and implemnetation: with Laravel and Angular Really informative guide to JWT in theory and in practice for Laravel and Angular.