在项目开发过程经常对接其他系统和被其他系统对接,发现很多系统都有一套自己的鉴权规则,还不提供库或代码,只有文字描述,经常需要自己实现鉴权方法,这真是太低效了。本文介绍一个在项目中使用一个成熟稳定的开源框架JWT( JSON Web Token )。
哎呀,不好意思,还是在写鉴权哎。 希望不要烦到你哦
详细地址在:https://jwt.io/ 。
JWT的特点有:
简单:有各种语言的sdk和样例,不需要自己写加解密算法了
安全:加密和签名方法可靠,比自己想出来的加密方法靠谱多啦
规范: RFC 7519标准定义的
下面文档是项目过程中写的,欢迎参考:
JWT(Json Web Token)是实现token技术的一种解决方案,JWT由三部分组成: header(头)、payload(载体)、signature(签名)。
jwt header
JWT第一部分是header,header主要包含两个部分,alg为token的类型,typ为加密的算法。
{
"alg": "HS256",
"typ": "JWT"
}
jwt payload
JWT第二部分是payload,payload是Token的详细内容,包含一些标准字段,也可以包含自定义字段。
{
"exp": 1493090001,
"iss": "appid"
}
如下是一些标准字段,我们只用exp/iss
iss:Issuer,发行者
sub:Subject,主题
aud:Audience,观众
exp:Expiration time,过期时间
nbf:Not before
iat:Issued at,发行时间
jti:JWT ID
签名 token
JWT第二部分是Signature,这部分的内容是这样计算得来的:
Base64(header).Base64(payload)得到一个Base64编码的字符串(下文成EncodeString)
HS256(EncodeString,"秘钥");计算得到的即使签名。
计算得到上面三部分内容后,用.连接起来就是一个完整的JWT TOKEN,秘钥是保存在服务器上的一个私有密
钥。
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoi5byg5LiJIiwiaWF0IjoxNDkzMDkxNjk0fQ.IrhnrcvDh1ygngW7HDWLhh2Bc2zG674Lum2BROE_7sI
可以使用https://jwt.io 的在线工具,进行token的编码和解码的测试和验证。
下面是工具截图:
JWT各种编程语言的库
官网已经提供大部分编程语言,请参考所使用编程语言对应的库的示例代码使用 https://jwt.io/#libraries-io。
Java示例代码
Maven安装
com.auth0
java-jwt
3.3.0
生成token
try {
Algorithm algorithm = Algorithm.HMAC256("secret");
String token = JWT.create()
.withIssuer("appId")
.withClaim("exp", new Date(new Date().getTime() + 60*1000));
)
.sign(algorithm);
} catch (UnsupportedEncodingException exception){
//UTF-8 encoding not supported
} catch (JWTCreationException exception){
//Invalid Signing configuration / Couldn't convert Claims.
}
Python示例代码
安装PyJwt
Install withpip:
$ pip install PyJWT
生成token
>>> import jwt
>>> token = jwt.encode({'iss': 'appId', 'exp' : date() }, 'secret', algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoicGF5bG9hZCJ9.4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZg'
GO示例代码
Example creating, signing, and encoding a JWT token using the HMAC signing method
Code:
// Create a new token object, specifying signing method and the claims // you would like it to contain.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "iss": "appId", "exp": time.Date(2015, 10, 10, 12, 0, 0, 0, time.UTC).Unix(), })
// Sign and get the complete encoded token as a string using the secret
secret := []byte("password")
tokenString, err := token.SignedString(secret)
fmt.Println(tokenString, err)
Output:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJuYmYiOjE0NDQ0Nzg0MDB9.u1riaD1rW97opCoAuRCTy4w58Br-Zk-bh7vLiRIsrpU
使用方法
将生成的token放到HTTP请求的token参数中即可。示例如下: