khenaidoo | ab1f7bd | 2019-11-14 14:00:27 -0500 | [diff] [blame] | 1 | package jwt |
| 2 | |
| 3 | import ( |
| 4 | "sync" |
| 5 | ) |
| 6 | |
| 7 | var signingMethods = map[string]func() SigningMethod{} |
| 8 | var signingMethodLock = new(sync.RWMutex) |
| 9 | |
| 10 | // Implement SigningMethod to add new methods for signing or verifying tokens. |
| 11 | type SigningMethod interface { |
| 12 | Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid |
| 13 | Sign(signingString string, key interface{}) (string, error) // Returns encoded signature or error |
| 14 | Alg() string // returns the alg identifier for this method (example: 'HS256') |
| 15 | } |
| 16 | |
| 17 | // Register the "alg" name and a factory function for signing method. |
| 18 | // This is typically done during init() in the method's implementation |
| 19 | func RegisterSigningMethod(alg string, f func() SigningMethod) { |
| 20 | signingMethodLock.Lock() |
| 21 | defer signingMethodLock.Unlock() |
| 22 | |
| 23 | signingMethods[alg] = f |
| 24 | } |
| 25 | |
| 26 | // Get a signing method from an "alg" string |
| 27 | func GetSigningMethod(alg string) (method SigningMethod) { |
| 28 | signingMethodLock.RLock() |
| 29 | defer signingMethodLock.RUnlock() |
| 30 | |
| 31 | if methodF, ok := signingMethods[alg]; ok { |
| 32 | method = methodF() |
| 33 | } |
| 34 | return |
| 35 | } |