英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论