How can I inherit bearer token from collection? (POSTMAN, Golang RESTAPI)

Viewed 301

I am able to verify the JWT Token, by manually setting each individual request with the bearer token, but whenever I set them to inherit auth from parent, it returns Unauthorized, it says clearly that it's taking the auth from the name of the collection, and I've set the collection to the bearer token.

Here is the JWTMiddleware:

func JWTMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        authHeader := strings.Split(r.Header.Get("Authorization"), "Bearer ")
        if len(authHeader) != 2 {
            fmt.Println("Malformed token")
            w.WriteHeader(http.StatusUnauthorized)
            w.Write([]byte("Malformed Token"))
        } else {
            jwtToken := authHeader[1]
            token, err := jwt.Parse(jwtToken, func(token *jwt.Token) (interface{}, error) {
                if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
                    return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
                }
                return []byte(os.Getenv("JWT_SECRET")), nil
            })

            if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
                ctx := context.WithValue(r.Context(), "props", claims)

                next.ServeHTTP(w, r.WithContext(ctx))
            } else {
                fmt.Println(err)
                w.WriteHeader(http.StatusUnauthorized)
                w.Write([]byte("Unauthorized"))
            }
        }
    })
}

Here is how the token is generated:

func generateJWT() (JWTToken, error) {
    signingKey := []byte(os.Getenv("JWT_SECRET"))
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
        "exp":    time.Now().Add(time.Hour * 1 * 1).Unix(),
    })
    tokenString, err := token.SignedString(signingKey)
    return JWTToken{tokenString}, err
}

Here is how my routes are structured:

var Routes = router.RoutePrefix{
    "/generate",
    []router.Route{
        router.Route{
            "gen_token",
            "GET",
            "",
            gen_token,
            false,
        },  
        router.Route{
            "testToken",
            "GET",
            "/test",
            testToken,
            true,
        },
    },
}

I am considering setting a global variable that I can set as the token for testing purposes, what would the solution be?

0 Answers
Related