Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

decode jwt with rs256 algorithm in golang-jwt / jwt #292

Answered by oxisto
chaotic98 asked this question in Q&A
Discussion options

the documentation only has parsing and validate with Hmac
https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-Parse-Hmac
is there any way to decode in rs256 ?

You must be logged in to vote

Please do NOT use ParseUnverified unless you REALLY know what you are doing.

We really need to supply an appropriate example using asymmetric keys. Basically it works the same way as for HMAC, but instead of supplying a []byte key, you need to supply a *rsa.PublicKey in the keyfunc. Something like

var myPublicKey *rsa.PublicKey
// Load key from file
myPublicKey = /*...*/
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
	// Don't forget to validate the alg is what you expect:
	if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
		return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
	}
	return myPublicKey, nil
})

Replies: 2 comments

Comment options

Try using ParseUnverified, it useful if you want to extract values without validate.

func TestParser_ParseUnverified(t *testing.T) {
You must be logged in to vote
0 replies
Comment options

Please do NOT use ParseUnverified unless you REALLY know what you are doing.

We really need to supply an appropriate example using asymmetric keys. Basically it works the same way as for HMAC, but instead of supplying a []byte key, you need to supply a *rsa.PublicKey in the keyfunc. Something like

var myPublicKey *rsa.PublicKey
// Load key from file
myPublicKey = /*...*/
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
	// Don't forget to validate the alg is what you expect:
	if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
		return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
	}
	return myPublicKey, nil
})
You must be logged in to vote
0 replies
Answer selected by oxisto
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
Converted from issue

This discussion was converted from issue #280 on March 25, 2023 14:39.

AltStyle によって変換されたページ (->オリジナル) /