Beego application does a pure API backend how to use JWT to implement stateless permission validation

Source: Internet
Author: User

JWT is what, can Baidu under other articles, I originally saw a talk of detailed, now can't find. A brief introduction to my personal understanding, is a token, but by means of encryption and decryption, can let this string of characters with some simple information. In this way after the decryption JWT do not have to check the database, the most commonly used examples, save user rights, and then multiple layers of permissions, in fact, only with a number, converted into binary, each one represents a permission. Similar to the use of this, as well as the key to save the session, through the value of the session will be able to obtain a richer data, to save the user state is also possible.

Below is a description of one of my Golang projects using the Beego framework to do a pure API interface using JWT method.

First, the go file with the JWT function is introduced into this library.

Import (
"Github.com/dgrijalva/jwt-go"
)

Login function Login successfully sent the JWT string to the client, the client needs to be saved such as localstorage, access to other APIs added to the header, note that this inside exp is necessary, life cycle. Others are the key-value pairs that are added to your needs:
ifpasswd = =user. Password {//Create a token with permissionClaims: =Make (JWT. MAPCLAIMS)claims["username"] =usernameifUsername = ="Admin"{claims["Admin"] ="true"            } Else{claims["Admin"] ="false"} claims["Exp"] = time. Now (). ADD (time. Hour *480). Unix ()//20 days validity, expiration requires re-login to get tokenToken: =JWT. Newwithclaims (JWT. SIGNINGMETHODHS256, claims)//Encrypt and get the complete encoded token as a string using a custom stringTokenstring, Err: = token. Signedstring ([]byte("MyKey"))            ifErr! =Nil {Beego. Error ("JWT. Signedstring:", Err) This. Reterror (Errsystem)return            }             This. data["JSON"] = map[string]Interface{}{"Status": $,"message":"Login Success","MoreInfo": Tokenstring}} Else {             This. data["JSON"] = map[string]Interface{}{"Status": -,"message":"Login Failed","MoreInfo": Time. Now (). Format ("2006-01-02 15:04:05")}        }


Basecontroler write this function, all other functions call this to do permission authentication
//Parsetoken Parse JWT token in HTTP header.Func (c *basecontroller) Parsetoken () (t *JWT. Token, E *controllererror) {authstring:= C.ctx.input.header ("Authorization") Beego. Debug ("authstring:", authstring) kv:= Strings. Split (Authstring," ")    ifLen (kv)! =2|| kv[0] !="Bearer"{Beego. Error ("authstring Invalid:", authstring)returnnil, Errinputdata} tokenstring:= kv[1]    //Parse Tokentoken, err: = JWT. Parse (Tokenstring, func (token *JWT). Token) (Interface{}, error) {        return[]byte("MyKey"), nil})ifErr! =Nil {Beego. Error ("Parse token:", Err)ifve, OK: = Err. (*JWT. ValidationError); OK {ifVe. ERRORS&JWT. Validationerrormalformed! =0 {                //That's not even a token                returnnil, errinputdata}Else ifVe. errors& (JWT. VALIDATIONERROREXPIRED|JWT. Validationerrornotvalidyet)! =0 {                //Token is either expired or not active yet                returnnil, errexpired}Else {                //couldn ' t handle this token                returnnil, Errinputdata}} Else {            //couldn ' t handle this token            returnnil, Errinputdata}} if!token. Valid {Beego. Error ("Token Invalid:", tokenstring)returnnil, errinputdata} beego. Debug ("Token:", token)returntoken, nil}

Other API Code Snippets
token, E:= This. Parsetoken ()ifE! =Nil { This. Reterror (e)return} claims, OK:=token. Claims. (JWT. MAPCLAIMS)if!OK { This. Reterror (errpermission)return    }varUserstring= claims["username"]. (string)


Beego app does a pure API backend how to use JWT for stateless permission validation

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.