Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract and verify token sent from frontend

Tags:

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?

like image 554
poise Avatar asked Sep 15 '16 18:09

poise


People also ask

How do I access the OneLogin token in express?

We can access it inside any Express request via the req.session.accessToken variable. We must send the access token to the OneLogin OIDC app’s introspection endpoint to validate the token. If the token is valid, the introspection endpoint will respond with an HTTP 200 response code.

How do I get a JWT token for an express user?

We’re going to add a token page under the users route to make it easy to acquire and inspect a JWT token. Let’s begin by adding a new route to routes/users.js: To inspect a JWT token, we must first obtain one. Fortunately, OneLogin’s sample app provides it. Once a user has logged in to the Express app, it stores a copy of the access token we need.

What is the best way to hook up a refresh token?

1. HTTP Client: The HTTP client is a perfect point to hook our refresh token solution. This is because our HTTP client would be responsible for sending requests to our backend service and returning the responses.

How do I retrieve the user’s access token from Express session?

We retrieve the user’s access token from Express’s session, set the token type hint to ‘access_token’ since that is the type of token we are sending, and we read the OIDC client ID from the app’s environment variables. The endpoint expects the POST body to be in a URL-encoded form format.


2 Answers

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.

like image 110
poise Avatar answered Oct 14 '22 22:10

poise


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> 
like image 31
brianbhsu Avatar answered Oct 14 '22 22:10

brianbhsu