简体   繁体   English

单页应用程序授权

[英]Single Page Application Authorization

I'm developing SPA Application on AngularJS that receives data from REST Api written on PHP. 我正在AngularJS上开发SPA应用程序,该应用程序从用PHP编写的REST Api接收数据。 I need to implement JWT authorization for it. 我需要为其实现JWT授权。 I got simple PHP JWT library that can encode and decode JWT tokens, but don't know how to verify JWT token. 我有一个简单的PHP JWT库,可以对JWT令牌进行编码和解码,但是不知道如何验证JWT令牌。 Can someone explain me the steps of JWT verification on PHP side? 有人可以在PHP方面向我解释JWT验证的步骤吗?

You need to decode the header first (which is the first part of the JWT after you split by periods ".") this will contain the algorithm used to sign like: 您需要先对标头进行解码(这是按句点“。”分隔后的JWT的第一部分),这将包含用于签名的算法,例如:

{
  "alg": "HS256",
  "cty": "JWT"
}

This means that HMAC with SHA-256 was used to create the signature of this token. 这意味着使用具有SHA-256的HMAC来创建此令牌的签名。 An HMAC is a MAC generated by concatenating a secret to the message and computing the hash, in this case the hash function is SHA-256. HMAC是通过将消息秘密连接起来并计算哈希值而生成的MAC,在这种情况下,哈希函数为SHA-256。 Since, given a HASH is imposible (or at least very expensive in hardware terms) to compute the input, even knowing what is the message you can't guess the key. 由于给定HASH不可能(或者至少在硬件上非常昂贵)来计算输入,即使知道什么消息也无法猜出密钥。 But given the message (second part of the JWT) and the key, you can compute the hash again and validate if is equal to the signature (third part of the JWT). 但是给定消息(JWT的第二部分)和密钥,您可以再次计算散列并验证是否等于签名(JWT的第三部分)。 There is more information about HMAC in this answer 1 . 在此答案1中有关于HMAC的更多信息。

It goes without saying that although this is a very common algorithm for JWTs is not the only one, and hence the header to indicate the algorithm. 毋庸置疑,尽管对于JWT而言,这是一种非常常见的算法,但它并不是唯一的算法,因此它是表示该算法的标头。 For instance Google JWTs are signed with an asymmetric secret, ie they publish the public part of the key that can be used to verify signatures but it can't be used to sign. 例如,Google JWT用非对称机密进行签名,即它们发布了可用于验证签名但不能用于签名的密钥的公共部分。 This algorithm is RS256 (aka RSA SHA-256). 此算法为RS256(也称为RSA SHA-256)。

You will find this website really useful to debug 2 . 您会发现此网站对于调试2确实有用。 You can also see here the different algorithms and a collection of different implementations in many languages. 您还可以在这里看到多种语言的不同算法和不同实现的集合。

Firebase guys have a PHP implementation that can sign and verify JWTs 3 . Firebase的家伙有一个PHP实现,可以签名和验证JWT 3

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

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