jwt

package module
v0.0.0-...-66e0f27 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 2, 2020 License: MIT Imports: 10 Imported by: 0

README

Go 实现 JWT

原理

以前是用 cookie/ session,后来变成 JWT。

以前用户每次访问都会带上 SessionID,服务器校验 SessionID判断是同一个用户,用户信息保存在服务端,服务端需要查表找到用户

JWT 是服务端生成信息,并用自己的密钥(key)签名数据,服务端不存数据,JWT 包含了用户的所有信息,用户信息保存在客户端,服务端不做任何存储,这意味着你可以用一个 JWT,请求多个服务器,不会存在一个服务器有客户端Session,但另一个服务器没有客户端Session

+---------+                       +----------+
|  Client |                       |  Server  |
|         |                       |          |
+---+-----+                       +-----+----+
    |                                   |
    |    POST /user/login               |
    |    {email, password}              |
    +---------------------------------->+ Store User
    |                                   | Session
    |    Send SessionID as cookie       | in Server
    <-----------------------------------+ Memory
    |                                   |
    |                                   |
    | Send Requsest with SessionID(Cookie)
    +----------------------------------->
    |                                   | get Usedrd
    |     Send Respopnse                | from session
    <-----------------------------------+ based on id
    |                                   | and verify them
    |                                   |
    |                                   |
    |                                   |
    |                                   |



+---------+                       +----------+
| Client  |                       |  Server  |
|         |                       |          |
+---+-----+                       +-----+----+
    |                                   |
    |      POST /user/login             |
    |      {email, password}            |
    +---------------------------------->+
    |                                   | Create JWT
    |     Send JWT to browser           | for user with
    <-----------------------------------+ secret
    |                                   |
    |                                   |
    |     send Request with JWT         |
    +-----------------------------------> Verify JWT
    |                                   | Signature
    |     Send Response                 | and Get User
    <-----------------------------------+ From JWT
    |                                   |
    |                                   |
    |                                   |
    |                                   |
    |                                   |
        

使用场景

Bank                        Retirement

+------------+              +------------+
|            |              |            |
|            |              |            |
|            |              |            |
|            |              |            |
|            |              |            |
|            |              |            |
|            |              |            |
|            |              |            |
+----^-------+              +-------^----+
     |                              |
     |                              |
     |                              |
     +---------+           +--------+
               |           |
               |           |
               |           |
               |           |
         +-----+-----------+--------+
         |                          |
         |     Client(Broswer)      |
         |                          |
         +--------------------------+

访问多个服务器,只要服务器上存储相同的 secret key,就可以认证成功,不需要每次都登录

总结

编码的过程

分别对Header,payload 序列化之后,再base64编码,

HMAC 算法

Hash Message Authentication Code

需要用到密钥

JWT 的优缺点

reference

https://github.com/robbert229/jwt

https://jwt.io/

https://www.youtube.com/watch?v=7Q17ubqLfaM

https://www.youtube.com/watch?v=rxzOqP9YwmM

https://www.youtube.com/playlist?list=PLZlA0Gpn_vH8DWL14Wud_m8NeNNbYKOkj

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Algorithm

type Algorithm struct {
	// contains filtered or unexported fields
}

Algorithms is used to sign and validate a token 用于签发和验证 token

func HmacSha256

func HmacSha256(key string) Algorithm

HmacSha256 returns the SingingMethod for HMAC with SHA256 入参是Hash算法的key

func HmacSha384

func HmacSha384(key string) Algorithm

HmacSha384 returns the SigningMethod for HMAC with SHA384

func HmacSha512

func HmacSha512(key string) Algorithm

HmacSha512 returns the SigningMethod for HMAC with SHA512

func (*Algorithm) Decode

func (a *Algorithm) Decode(encoded string) (*Claims, error)

Decode returns a map representing the token's claims. DOESN'T valiadate the claims though 解码数据,还原Claims

func (*Algorithm) DecodeAndValidate

func (a *Algorithm) DecodeAndValidate(encoded string) (claims *Claims, err error)

DecodeAndValidate verifies a token validity. It returns nil if it is valid, and an error if invalid 验证 token:验证token的签名(其实就是把header和payload签一下,然后和token里的最后一段对比是否一直),是否过期,是否在时间之前

func (*Algorithm) Encode

func (a *Algorithm) Encode(payload *Claims) (string, error)

encode returns an encoded JWT token from a header, payload and secret 对claims用哈希算法编码,并返回

func (*Algorithm) NewHeader

func (a *Algorithm) NewHeader() *Header

NewHeader returns a header object

func (*Algorithm) Sign

func (a *Algorithm) Sign(unsignedToken string) ([]byte, error)

Sign signs the token with the given hash, and key 对token进行签名(哈希),要用用于消息验证的哈希算法 HMAC

func (*Algorithm) Validate

func (a *Algorithm) Validate(encoded string) error

Validate 验证,其实就是解码claims数据,然后比对

type Claims

type Claims struct {
	// contains filtered or unexported fields
}

Claims contains the claims of a jwt Claims就是一个Map,存放各种键值对,提供存取功能

func NewClaims

func NewClaims() *Claims

NewClaim returns a new map representing the claims with the default values. The schema is detailed below.

claim["iis"] Issuer - string - identifies principal that issued the JWT;
claim["sub"] Subject - string - identifies the subject of the JWT;
claim["aud"] Audience - string - The "aud" (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the aud claim when this claim is present, then the JWT MUST be rejected.
claim["exp"] Expiration time - time - The "exp" (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing.
claim["nbf"] Not before - time - Similarly, the not-before time claim identifies the time on which the JWT will start to be accepted for processing.
claim["iat"] Issued at - time - The "iat" (issued at) claim identifies the time at which the JWT was issued.
claim["jti"] JWT ID - string - case sensitive unique identifier of the token even among different issuers.

func (Claims) Get

func (c Claims) Get(key string) (interface{}, error)

func (*Claims) GetTime

func (c *Claims) GetTime(key string) (time.Time, error)

func (*Claims) HasClaim

func (c *Claims) HasClaim(key string) bool

func (*Claims) Set

func (c *Claims) Set(key string, value interface{})

func (*Claims) SetTime

func (c *Claims) SetTime(key string, value time.Time)
type Header struct {
	Typ string `json:"typ"` // Token type
	Alg string `json:"alg"` // Message Authentication Code Algorithm - The issuer can freely set an algorithm to verify the signature on the token. However, some asymmetrical algorithms pose security concerns
	Cty string `json:"cty"` // Content Type This claim should always be JWT
}

Header 包含了重要的诸如加密、解密信息

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL