fosite-example icon indicating copy to clipboard operation
fosite-example copied to clipboard

How to use JWT as access token?

Open riadevatix opened this issue 3 years ago • 1 comments

Hi, I've tried this but got the error. Can anyone tell me what am I missing here?

NOTE : I only changed this portion of the code.

// in file authorizationserver/oauth2.go

var oauth2 = ComposeJWTAccessToken(config, store, privateKey)

func ComposeJWTAccessToken(config *fosite.Config, storage interface{}, key interface{}) fosite.OAuth2Provider {
	keyGetter := func(context.Context) interface{} {
		return key
	}
	return compose.Compose(
		config,
		storage,
		&compose.CommonStrategy{
			CoreStrategy: compose.NewOAuth2JWTStrategy(
				func(ctx context.Context) interface{} { return privateKey2 },
				compose.NewOAuth2HMACStrategy(config), config),
			OpenIDConnectTokenStrategy: compose.NewOpenIDConnectStrategy(keyGetter, config),
			Signer:                     &jwt.DefaultSigner{GetPrivateKey: keyGetter},
		},
		compose.OAuth2AuthorizeExplicitFactory,
		compose.OAuth2AuthorizeImplicitFactory,
		compose.OAuth2ClientCredentialsGrantFactory,
		compose.OAuth2RefreshTokenGrantFactory,
		compose.OAuth2ResourceOwnerPasswordCredentialsFactory,
		compose.RFC7523AssertionGrantFactory,

		compose.OpenIDConnectExplicitFactory,
		compose.OpenIDConnectImplicitFactory,
		compose.OpenIDConnectHybridFactory,
		compose.OpenIDConnectRefreshFactory,

		compose.OAuth2TokenIntrospectionFactory,
		compose.OAuth2TokenRevocationFactory,

		compose.OAuth2PKCEFactory,
	)
}

Got this error:

I tried to exchange the authorize code for an access token but it did not work 
but got error: oauth2: cannot fetch token: 400 Bad Request 
Response: 
{
    "error":"invalid_grant",
    "error_description":"The provided authorization grant (e.g., authorization code, resource owner credentials) 
or refresh token is invalid, expired, revoked, 
does not match the redirection URI used in the authorization request,
 or was issued to another client. Unable to find initial PKCE data tied to this request"
}

riadevatix avatar May 24 '22 15:05 riadevatix

I did like you, but I had to build a new session type to pass when creating a session on fosite. Its a jwtsession and an openid one:

type OpenIDJWTSession struct {
	openid.DefaultSession
}

func (s *OpenIDJWTSession) GetJWTClaims() jwt.JWTClaimsContainer {
	claims := &jwt.JWTClaims{}
	if s.Claims != nil {
		claims.FromMapClaims(s.Claims.ToMapClaims())
	}
	return claims
}

func (s *OpenIDJWTSession) GetJWTHeader() *jwt.Headers {
	return s.IDTokenHeaders()
}

func NewOpenIDJWTSession() *OpenIDJWTSession {
	return &OpenIDJWTSession{
		*openid.NewDefaultSession(),
	}
}

there are some tipe casts inside the handlers and I had to create it. I need to review the code, claims and headers to make sure it's not buggy

igorcavalcante avatar Dec 22 '22 21:12 igorcavalcante