无法解决“token contains an invalid number of segments”错误。

huangapple go评论365阅读模式
英文:

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

问题

我正在使用一个身份提供者来生成令牌,并且生成的令牌是有效的(在https://jwt.io/上进行了测试)。我的主要问题是在从授权头中提取令牌时出现错误"token contains an invalid number of segments"。我已经将令牌存储到一个变量中,并且这样做实际上是有效的。我已经确认了令牌的有效性。但是为了使应用程序正常工作,我需要从身份验证头中提取令牌。

在发送请求到后端之后,我收到了这个错误。我应该如何处理这个错误?

英文:

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?

答案1

得分: 2

你应该从Authorization头部的值中去掉"Bearer "前缀,以获取JWT令牌。jwt-go库提供了一个辅助函数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
}
英文:

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
}

huangapple
  • 本文由 发表于 2022年2月27日 08:19:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/71281242.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定