Summary Knowledge of principles and use -05token

1, token have two main functions:
(1) prevent duplicate submission form (set in how much time)

Principle: generating at the server a unique random number identification, jargon called Token (token), while preserving the current user in the Session Token field.

Then the Token is sent to the client in the form Form, Form using hidden fields in the form to store the Token, when the form is submitted, together with the Token submitted to the server,

Then the server determines whether the client submitted up with Token Token generated by the server, and if not, it is submitted to repeat,

At this time, the server side may not process the form submission is repeated. If the same process form submission, dealt clear the current user's domain identification number stored Session

https://blog.csdn.net/qq_38714573/article/details/78771862

(2) is used for authentication (login request with the obtained token determines whether the same token)

Principle: Use the Token-based authentication methods, logon recorded in the server does not need to store the user. Probably the process is this:

The client uses the user requests a login name and password into
the server receives the request, to verify the user name and password
After successful authentication, the server will issue a Token, then the Token is sent to the client
after the client receives the Token can store it up, such as on a Cookie or Local Storage in
Token every time a client requests a resource to the server needs with the server issued
the server receives the request, and then to verify the Token inside with client requests, and if the verification successful, it returns the requested data to the client terminal

https://blog.csdn.net/qq_32784541/article/details/79655146

2, token verification process
1, user registration information, the front-end user name and password to the back-end

2, the rear end of reception parameter and stored in the database, and then generates a token is returned to the front end (main token is used to verify the user's login state)
3, the front end of the rear end of the return token is received, to put it exists inside sessionStorage
4, front-end implementation login, the user name with password transmitted to the background, and bring token.
5, a new token returned by the backend to the frontend, and verify that the user name and password are correct, the results are returned to the front.
6, the rear end of the front end of the received message is returned, performs the corresponding operation, and to keep the token inside sessionStorage.
7, after successful login, goto, and requests the data back home, bring the rear end token pass.
8, the rear end to the front end coming token received, determines whether or not valid. If valid, it returns the corresponding data information to the distal end; if invalid, then return "login failed, again similar to the login fields."
9, the front end of the rear end of the return message is received, and performs a corresponding operation.
https://blog.csdn.net/weixin_43748930/article/details/87901038

3, code analysis
// token inside to add user information, user information may be useful after verification token

type MyClaims struct {
   UserName string `json:"user_name"`
 UserId   string `json:"user_id"`
 jwt.StandardClaims
}

// 根据用户名生成token,传递给客户端
func GenToken(username string, userId string) (token string) {
   myClaims := MyClaims{
      username,
      userId,
      jwt.StandardClaims{
         NotBefore: int64(time.Now().Unix()),
         ExpiresAt: int64(time.Now().Unix() + 86400), // 86400 为一天
 Issuer:    "duxiaoman",
      },
   }
   key := beego.AppConfig.String("TokenSignKey")
   fmt.Println(key)
   ss := jwt.NewWithClaims(jwt.SigningMethodHS256, myClaims)
   token, _ = ss.SignedString([]byte(key))
   return token
}
//beego.AppConfig.String()读取配置信息

读取不同模式下配置参数的方法是“模式::配置参数名”,比如:beego.AppConfig.String(“dev::mysqluser”)

https://blog.csdn.net/qq_33610643/article/details/53511058

// parse token, token to determine whether a valid and effective, then extract user information

func ValidateTokenMiddleware(tokenString string) (username string, userId string, isOk bool) {
   olog.Debug("start validate token")
   token, err := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
      return []byte(beego.AppConfig.String("TokenSignKey")), nil
   })
   claims, ok := token.Claims.(*MyClaims)
   if ok && token.Valid {
      username = claims.UserName
      userId = claims.UserId
      isOk = ok
      olog.Debug("token is validate")
   } else {
      olog.Debug("token is not validate ,err is ", err)
   }
   return
}

// other operations after landing, whether the user has token authentication request

var AuthFilter = func(ctx *context.Context) {
   if ctx.Request.RequestURI != "/fsg-resource/ui/auth/login" {
      olog.Debug("start auth request")
      token := ctx.Request.Header.Get("Authorization")
      if token != "" {
         username, userId, isOk := ValidateTokenMiddleware(token)
         olog.Debug("request is ok ,username is ", username)
         if isOk {
            ctx.Input.SetData("username", username)
            ctx.Input.SetData("userID", userId)
         }
         if !isOk {
            olog.Debug("request token is not validate")
            ctx.Redirect(401, "/401")
         }
      } else {
         olog.Debug("request token is not exists")
         ctx.Redirect(401, "/401")
      }
   }
}

URI, is the uniform resource identifier, uniform resource identifier, used to uniquely identify a resource.

The URL is a uniform resource locator, Uniform Resource Locator, which is a specific URI, namely URL can be used to identify a resource, but also indicates how locate this resource.

https://www.jianshu.com/p/449b30411964

Get token: token: = ctx.Request.Header.Get ( " Authorization")
in the HTTP request token field usually placed Authorization
token acquiring information according to the user: username, userId, isOk: = ValidateTokenMiddleware (token)

https://hacpai.com/article/1540349739379

ctx.Input.SetData ( "username", username)
the GetData data from the controller for acquiring a filter. It not only allows you to pass the value of the string.

From Beego document: GetData Gets the value of the input data

SetData data input setting values. GetData and SetData for data transfer from the filter to the controller

https://stackoverflow.com/questions/50373654/functionality-of-beego-syntax-ctx-input-getdatavariable-name

Complete token codes

https://www.cnblogs.com/dust90/p/11168585.html

https://www.cnblogs.com/zhzhlong/articles/10009141.html

https://studygolang.com/articles/24285?fr=sidebar

// authentication ticket, correctly returns token

func AuthTicket(ticket string, nexturl string) (userInfo map[string]interface{}, err error) {
   olog.Debug("认证ticket")
   url := fmt.Sprintf("%s?service=%s?next=%s&ticket=%s&appKey=%s", global.UUAPAuthUrl, global.ServiceUrl, nexturl, ticket, global.UUAPAppKey)
   olog.Debug(url)
   resp, err := http.Get(url)
   if err == nil {
      defer resp.Body.Close()
      body, err := ioutil.ReadAll(resp.Body)
      username, err := parserXml(string(body))
      if err == nil {
         // 获取到username 生成token
 userInfo = UserAuth(username)
         token := GenToken(username, strconv.Itoa(userInfo["userID"].(int)))
         userInfo["token"] = token
         olog.Debug("认证ticket 成功", ticket)
      }
   }
   return
}

ctx.Input.SetData () and c.Ctx.Input.GetData () principle

() One to one relationship ctx.Input.SetData

After user authentication token there, each request will be holding the token after token parsed inside the user's information.

Every request will go to the verification token, authentication is successful will setData user name, and then in the controller in order to get value.

Published 10 original articles · won praise 0 · Views 78

Guess you like

Origin blog.csdn.net/weixin_42282999/article/details/104459151