- Notifications
You must be signed in to change notification settings - Fork17
A Go library to retrieve RSA public keys from a JWKS (JSON Web Key Set) endpoint
License
s12v/go-jwks
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
A Go library to retrieve RSA public keys from a JWKS (JSON Web Key Set) endpoint.
UsingGo modules
go get github.com/s12v/go-jwks@v0.2.1
github.com/square/go-jose
- JWT librarygithub.com/patrickmn/go-cache
- default in-memory cache
GetEncryptionKey
returns*jose.JSONWebKey
for a given key id:
package mainimport ("log""time""github.com/s12v/go-jwks""github.com/square/go-jose")funcmain() {jwksSource:=jwks.NewWebSource("https://www.googleapis.com/oauth2/v3/certs")jwksClient:=jwks.NewDefaultClient(jwksSource,time.Hour,// Refresh keys every 1 hour12*time.Hour,// Expire keys after 12 hours)varjwk*jose.JSONWebKeyjwk,err:=jwksClient.GetEncryptionKey("c6af7caa0895fd01e778dceaa7a7988347d8f25c")iferr!=nil {log.Fatal(err)}log.Printf("key: %v, alg: %v, use: %v",jwk.KeyID,jwk.Algorithm,jwk.Use)}
Log:
2018/07/30 01:22:35 Fetchng JWKS from https://www.googleapis.com/oauth2/v3/certs2018/07/30 01:22:36 key: c6af7caa0895fd01e778dceaa7a7988347d8f25c, alg: RS256, use: sig
There are two caching parameters:
refresh
- the key will be fetched from the source after this intervalttl
- if not used, the key will be deleted from cache
On the first request, the key is synchronously fetched from the key server and stored in the cache.On the next request afterrefresh
interval, the key will be refreshed in the background (not affect response time).Only 1 key refresh is executed at the same time.
If the key is not requested duringttl
interval, it will be removed from cache.
Default cache isgithub.com/patrickmn/go-cache
in-memory cache.You can provide your own cache implementation, seecache.go
:
typeCacheinterface {// Get an item from the cache and itsexpiration time.// Returns the item or nil, and a bool indicating whether the key was foundGetWithExpiration(kstring) (interface{}, time.Time,bool)// Add an item to the cache, replacing any existing item.Set(kstring,xinterface{})}
and pass it tofunc NewClient(...)
Default source isWebSource
. You can provide your own implementation, seesource.go
:
typeJWKSSourceinterface {JSONWebKeySet() (*jose.JSONWebKeySet,error)}
About
A Go library to retrieve RSA public keys from a JWKS (JSON Web Key Set) endpoint