Use JWT in Go combat--golang (JSON Web Token)

Source: Internet
Author: User

http://blog.csdn.net/wangshubo1989/article/details/74529333

Previously wrote a blog about how cookies are used in Golang:
Use cookies in combat –go

Let's talk a little bit about how to use tokens in Golang today, and rely on the excellent open source libraries on GitHub, of course.

First of all, to understand a problem, token, cookie, session of the difference.

token, cookie, session difference

Cookies
Cookies are always stored in the client, and can be divided into memory cookies and hard disk cookies by the storage location in the client.

The memory cookie is maintained by the browser, stored in memory, and disappears after the browser is closed, and its presence time is short. The hard disk cookie is saved on the hard drive, there is an expiration time, unless the user manually cleans up or expires, the hard disk cookie is not deleted and its presence time is long. Therefore, by time of existence, it can be divided into non-persistent cookies and persistent cookies.

A cookie is a very specific thing, refers to the browser can be permanently stored in a data, is only a browser implementation of a data storage function.

The cookie is generated by the server, sent to the browser, the browser saves the cookie in key-value form in a text file in a directory, and the next time the same website is requested, the cookie is sent to the server. Because the cookie is present on the client, the browser has added some restrictions to ensure that the cookie is not used maliciously and does not occupy too much disk space, so the number of cookies per domain is limited.

Session

The session is literally a conversation. This is similar to how you talk to a person, how do you know the current conversation with you is Zhang San rather than John Doe? The other person must have a certain character (looks, etc) to show that he is Zhang San.

The session is similar to the truth, the server should know who is currently sending the request to itself. To make this distinction, the server assigns a different "identity" to each client, and then each time the client sends a request to the server, it takes the "identity" and the server knows who the request came from. As for the client how to save this "identity", there can be many ways, for the browser client, everyone is the default way of using cookies.

The server uses the session to temporarily save the user's information on the server, and the session will be destroyed after the user leaves the site. This user information is stored in a more secure way than a cookie, but the session has a flaw: if the Web server is load balanced, the session is lost when the next operation requests to another server.

Token
Token means "tokens", which is the authentication method of the user identity, the simplest token composition: UID (user's unique identity), time (timestamp of the current time), sign (signature, the hash algorithm is compressed into a long hexadecimal string by the first several + salts of token, Can prevent malicious third party stitching token request server). You can also put the invariant parameters into token, avoid multiple check the library

The token here refers to the son Web token:
JSON Web Token (JWT) is a compact url-safe means of representing claims to be transferred between. The claims in a JWT was encoded as a JSON object that is digitally signed using JSON Web Signature (JWS).

using JWT for certification
JSON Web Tokens (JWT) is a more modern approach to authentication.

As the web moves to a greater separation between the client and server, JWT provides a wonderful alternative to Traditiona L Cookie based authentication models.

Jwts provide a-on-clients to authenticate every request without have to maintain a session or repeatedly pass login Credentials to the server.

After the user registers, the server generates a JWT token to return to the browser, the browser sends the JWT token to the server when requesting data from the server, and the server decodes it in the way defined in signature
JWT gets the user information.

A JWT token consists of 3 parts:
1. Header: Tell us the algorithm and token type used
2. Payload: You must use Sub key to specify the user ID, and can include other information such as email, username, etc.
3. Signature: Used to ensure the authenticity of the JWT. Different algorithms can be used

JWT Application

It says so much, the next step is to coding.
Open Source Libraries used:
Github.com/codegangsta/negroni
Idiomatic HTTP middleware for Golang
A middleware for HTTP

github.com/dgrijalva/jwt-go
Golang implementation of JSON Web Tokens (JWT)

Github.com/dgrijalva/jwt-go/request

Here are two APIs, one to get tokens through login, and then to access another API based on token. First look at how login is generating tokens:
Of course the first is to verify the user name and password, in order to save space here is just the code snippet, the complete code is finally presented.

 token: = JWT. New (JWT. SIGNINGMETHODHS256) Claims: = make (JWT. mapclaims) Claims[ "exp"] = time. Now (). ADD (time. Hour * time. Duration (1)). Unix () Claims[ "iat" = time. Now (). Unix () token. Claims = Claims if err! = nil {w.writeheader (http. Statusinternalservererror) fmt. Fprintln (W,  "Error extracting the Key") Fatal (ERR)} tokenstring, err: = token. Signedstring ([]byte (secretkey)) if err! = nil {w.writeheader (http. Statusinternalservererror) fmt. Fprintln (W,  "Error while signing the token") Fatal (ERR)}     
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

The next step is to verify the token middleware:

 token, err: = Request. Parsefromrequest (R, request.) Authorizationheaderextractor, func (token *JWT. Token) (interface{}, error) {return []byte (Secretkey), nil}) if err = = nil {if token. Valid {Next (W, R)} else {w.writeheader (http. statusunauthorized) fmt. Fprint (W,  "Token is not valid")}} else {w.writeheader (http. statusunauthorized) fmt. Fprint (W,  "unauthorized access to this resource")}      
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

Final complete code:

Package MainImport ("Encoding/json""FMT""Log""Net/http""Strings""Time""Github.com/codegangsta/negroni""Github.com/dgrijalva/jwt-go""Github.com/dgrijalva/jwt-go/request")Const (Secretkey ="Welcome to Wangshubo ' s blog")Func Fatal (err error) {If Err! =Nil {log. Fatal (ERR)}}Type Usercredentialsstruct {UsernameString' JSON: ' username ' PasswordString' JSON: ' Password '}Type Userstruct {IDInt' JSON: ' id ' ' Name 'String' JSON: ' Name ' ' UsernameString' JSON: ' username ' PasswordString' JSON: ' Password '}Type Responsestruct {DataString' JSON: ' Data '}Type Tokenstruct {TokenString' JSON: ' token '}Func startserver () {http. Handlefunc ("/login", Loginhandler) http. Handle ("/resource", Negroni. New (Negroni. Handlerfunc (Validatetokenmiddleware), Negroni. Wrap (http. Handlerfunc (Protectedhandler))) log. Println ("Now listening ...") http. Listenandserve (": 8080",NIL)}Func Main () {StartServer ()}Func Protectedhandler (w http. Responsewriter, R *http. Request) {response: = response{"gained access to protected resource"} jsonresponse (Response, W)}Func Loginhandler (w http. Responsewriter, R *http. Request) {var user usercredentials Err: = json. Newdecoder (R.body). Decode (&user)If Err! =Nil {W.writeheader (http. Statusforbidden) fmt. Fprint (W,"Error in Request")return}If strings. ToLower (user. Username)! ="Someone" {If user. Password! ="[Email protected]" {W.writeheader (http. Statusforbidden) fmt. Println ("Error Logging in") fmt. Fprint (W,"Invalid Credentials")Return}} Token: = JWT. New (JWT. SIGNINGMETHODHS256) Claims: =Make (JWT. MAPCLAIMS) claims["Exp"] = time. Now (). ADD (time. Hour * time. Duration(1)). Unix () claims["IAT"] = time. Now (). Unix () token. Claims = ClaimsIf Err! =Nil {W.writeheader (http. Statusinternalservererror) fmt. Fprintln (W,"Error extracting the Key") Fatal (ERR)} tokenstring, err: = token. Signedstring ([]Byte (Secretkey))If Err! =Nil {W.writeheader (http. Statusinternalservererror) fmt. Fprintln (W,"Error while signing the token") Fatal (ERR)} Response: = token{tokenstring} jsonresponse (Response, W)}Func validatetokenmiddleware (w http. Responsewriter, R *http. Request, next http. Handlerfunc) {token, err: = Request. Parsefromrequest (R, request.) Authorizationheaderextractor,Func (token *JWT. Token) (interface{}, error) {return []Byte (Secretkey),NIL})if err = = nil {if token. Valid {Next (W, R)} else {w.writeheader (http. statusunauthorized) fmt. Fprint (W,  "Token is not valid")}} else {w.writeheader (http. statusunauthorized) fmt. Fprint (W,  "unauthorized access to this resource")}}func Jsonresponse (response interface{}, W http. Responsewriter) {json, err: = json. Marshal (response) if err! = nil {http. Error (W, err. Error (), HTTP. Statusinternalservererror) return} w.writeheader (http. Statusok) W.header (). Set ( "Content-type",  "Application/json") W.write (JSON)} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21st
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147

Verify with Postman:
Login

Get request based on Get token:

Use JWT in Go combat--golang (JSON Web Token)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.