Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't solve "token contains an invalid number of segments"

Tags:

go

I am using for the generation of tokens an identity provider and the generated token is valid (tested on https://jwt.io/). My main issue is the error "token contains an invalid number of segments", when I'm extracting the token from the authorization header. I have tipped the token into a variable and by doing so, it actually worked.I got the confirmation, that the token is valid. But in order for the application to work properly, I need to extract the token from the authentification header.

import (
    "fmt"
    "github.com/golang-jwt/jwt"
    "net/http"
)
var ReqToken string

func verifyToken(w http.ResponseWriter, r *http.Request) bool {
    SecretKey := "SECRETKEY"
    ReqToken = r.Header.Get("Authorization")
    key, er := jwt.ParseRSAPublicKeyFromPEM([]byte(SecretKey))
    if er != nil {
        fmt.Println(er)

        w.WriteHeader(http.StatusUnauthorized)
        return false
    }

    token, err := jwt.Parse(ReqToken, func(token *jwt.Token) (interface{}, error) {
        
        if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
            return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
        }
        return key, nil
    })

    if err != nil {
        fmt.Println(err)
        w.WriteHeader(http.StatusUnauthorized)
        return false
    }
    return true
}

I am receiving the error after I send a request to the backend. How should I approach this error?

like image 649
Emanuel Avadani Avatar asked Oct 21 '25 08:10

Emanuel Avadani


1 Answers

You should strip the "Bearer " prefix from the Authorization header value to get to the JWT token. jwt-go has a helper for this, request.AuthorizationHeaderExtractor:

package main

import (
    "crypto/rsa"
    "log"
    "net/http"

    jwt "github.com/golang-jwt/jwt/v4"
    request "github.com/golang-jwt/jwt/v4/request"
)

var verifyKey *rsa.PublicKey

func init() {
    verifyKey, _ = jwt.ParseRSAPublicKeyFromPEM([]byte("SECRETKEY"))
}

func verifyToken(w http.ResponseWriter, r *http.Request) bool {
    claims := jwt.StandardClaims{}
    extractor := request.AuthorizationHeaderExtractor
    token, err := request.ParseFromRequestWithClaims(r, extractor, &claims, func(token *jwt.Token) (interface{}, error) {
        return verifyKey, nil
    })

    if err != nil {
        log.Printf("verifyToken failed: %v", err)
        w.WriteHeader(http.StatusUnauthorized)

        return false
    }

    log.Printf("verifyToken: success, claims: %v", token.Claims)

    return true
}
like image 143
rustyx Avatar answered Oct 23 '25 15:10

rustyx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!