How to extract and verify token sent from frontend
Asked Answered
S

5

29

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 frontend so that I can verify if the token that was sent is valid and if so the secured resource will be delivered.

Here is the token sent from frontend JavaScript:

headers: {
       'Authorization':'Bearer' + localStorage.getItem('id_token')
     }

Here is the code to send token

    token := jwt.New(jwt.GetSigningMethod("HS256"))
    claims := make(jwt.MapClaims)
    claims["userName"] = loginRequest.UserName
    claims["exp"] = time.Now().Add(time.Minute * 60).Unix()
    token.Claims = claims
    tokenString, err := token.SignedString([]byte(SecretKey))
    tokenByte, err := json.Marshal(data)
    w.WriteHeader(201)
    w.Write(tokenByte)

Here is the code to verify the token

    func VerifyToken(r *http.Request) bool {

    reqToken := r.Header.Get("Authorization")
    token, err := jwt.Parse(reqToken, func(t *jwt.Token) (interface{}, error) {
        return []byte(SecretKey), nil
    })
    if err == nil && token.Valid {
        fmt.Println("valid token")
        return true
    } else {
        fmt.Println("invalid token")
        return false
    }

}

Am getting nil token as a return, my guess is I have sent bearer and I think it might need parsing if so how?

Sperling answered 15/9, 2016 at 18:43 Comment(0)
S
46

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.

Sperling answered 22/6, 2017 at 13:26 Comment(3)
In your example you're carrying a space in front of the token (as a result of the split) which is a bad thing. You should either include the space when splitting the string or trim it laterJari
Yes, it should be "Bearer " (note the space). Else you will get a "illegal base64 data at input byte 0"Ripping
You may catch panicForum
P
22

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>
Prithee answered 16/5, 2019 at 19:7 Comment(1)
You're gonna need to get the splitToken at index 1. And also verify that the splitToken has a length of 2Miter
P
5

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

const BEARER_SCHEMA = "Bearer "
authHeader := req.Header.Get("Authorization")
token := authHeader[len(BEARER_SCHEMA):]
Petey answered 27/11, 2019 at 13:18 Comment(2)
this will panic if Authorization value is shorter than "Bearer " - better to ensure via strings.HasPrefix()Scabious
You may catch panic errorForum
M
2

To be extra resilient to different casing or whitespace preferences, you can also leverage the strings.Fields function from the go std lib. This works well:

authHeader := req.Header.Get("Authorization")
authFields := strings.Fields(authHeader)
if len(authFields) != 2 || strings.ToLower(authFields[0]) != "bearer" {
  return errors.New("bad authorization header")
}
token := authFields[1]
Monacid answered 9/8, 2022 at 21:58 Comment(0)
W
0

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

Warmedover answered 30/10, 2020 at 23:12 Comment(1)
The shiva link is discontinued/brokenPanorama

© 2022 - 2025 — McMap. All rights reserved.