How to extract and verify token sent from frontend

前端 未结 4 740
深忆病人
深忆病人 2021-01-04 00:36

I am using "github.com/dgrijalva/jwt-go", and able to send a token to my frontend, and what I would like to know how I could retrieve the token sent from the front

4条回答
  •  星月不相逢
    2021-01-04 01:12

    The answer above is slightly incorrect because after splitting the reqToken, there should only be one value in splitToken, which is the token itself.

    Assuming that the token is of the following format:

    'Authorization': 'Bearer '
    

    Which is the standard format - with a space between the string "Bearer" and the actual token itself.

    The following code will perform the correct token extraction:

    reqToken := r.Header.Get("Authorization")
    splitToken := strings.Split(reqToken, "Bearer")
    if len(splitToken) != 2 {
        // Error: Bearer token not in proper format
    }
    
    reqToken = strings.TrimSpace(splitToken[1])
    
    fmt.Println(reqToken) // 
    

提交回复
热议问题