How to extract and verify token sent from frontend

前端 未结 4 735
深忆病人
深忆病人 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 <YOUR_TOKEN_HERE>'
    

    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) // <YOUR_TOKEN_HERE>
    
    0 讨论(0)
  • 2021-01-04 01:12

    Credit: https://github.com/harlow/authtoken/blob/master/authtoken.go

    const BEARER_SCHEMA = "Bearer "
    authHeader := req.Header.Get("Authorization")
    token := authHeader[len(BEARER_SCHEMA):]
    
    0 讨论(0)
  • 2021-01-04 01:25

    The server requires a token string without added strings in my case I have added Bearer string to the token string in the header when sending request to the web server i.e.

    'Authorization':'Bearer ' + localStorage.getItem('id_token')
    

    At the web server we need to split only the valid token without the Bearer string

    reqToken := r.Header.Get("Authorization")
    splitToken := strings.Split(reqToken, "Bearer ")
    reqToken = splitToken[1]
    

    As a result it becomes valid token without nil.

    0 讨论(0)
  • 2021-01-04 01:31

    1)here there is the function profilehandler (author theShivaa);

    link1: https://gist.github.com/theShivaa/999cec98fc29d77ea47b2bdaf0a6b4fb

    link2: https://medium.com/@theShiva5/creating-simple-login-api-using-go-and-mongodb-9b3c1c775d2f

    2)to use/test this function, in the bash shell I run this command.

    curl -i -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmaXJzdG5hbWUiOiJwaXBwbzIiLCJsYXN0bmFtZSI6InBpcHBvMyIsInVzZXJuYW1lIjoicGlwcG8xZiJ9.MkcI4JNUgoOeMzJUhDe4dLOsK3zXSAGC9fCV5EqwA98" -X GET http://localhost:8080/profile

    0 讨论(0)
提交回复
热议问题