mirror of
https://github.com/kataras/iris.git
synced 2025-12-18 02:17:05 +00:00
add an extra security layer on JWT and able to separate access from refresh tokens without any end-developer action on the claims payload (e.g. set a different issuer)
This commit is contained in:
@@ -3,6 +3,7 @@ package jwt
|
||||
import (
|
||||
"crypto"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -338,7 +339,6 @@ func (j *JWT) token(maxAge time.Duration, claims interface{}) (string, error) {
|
||||
return "", nErr
|
||||
}
|
||||
|
||||
// Set expiration, if missing.
|
||||
ExpiryMap(maxAge, c)
|
||||
|
||||
var (
|
||||
@@ -531,22 +531,45 @@ func (j *JWT) VerifyTokenString(ctx *context.Context, token string, dest interfa
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var claims Claims
|
||||
if err = parsedToken.Claims(j.VerificationKey, dest, &claims); err != nil {
|
||||
var (
|
||||
claims Claims
|
||||
tokenMaxAger tokenWithMaxAge
|
||||
)
|
||||
|
||||
if err = parsedToken.Claims(j.VerificationKey, dest, &claims, &tokenMaxAger); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
expectMaxAge := j.MaxAge
|
||||
|
||||
// Build the Expected value.
|
||||
expected := Expected{}
|
||||
for _, e := range expectations {
|
||||
if e != nil {
|
||||
// expection can be used as a field validation too (see MeetRequirements).
|
||||
if err = e(&expected, dest); err != nil {
|
||||
if err == ErrExpectRefreshToken {
|
||||
if tokenMaxAger.MaxAge > 0 {
|
||||
// If max age exists, grab it and compare it later.
|
||||
// Otherwise fire the ErrExpectRefreshToken.
|
||||
expectMaxAge = tokenMaxAger.MaxAge
|
||||
continue
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
gotMaxAge := getMaxAge(claims)
|
||||
if !compareMaxAge(expectMaxAge, gotMaxAge) {
|
||||
// Additional check to automatically invalidate
|
||||
// any previous jwt maxAge setting change.
|
||||
// In-short, if the time.Now().Add j.MaxAge
|
||||
// does not match the "iat" (issued at) then we invalidate the token.
|
||||
return nil, ErrInvalidMaxAge
|
||||
}
|
||||
|
||||
// For other standard JWT claims fields such as "exp"
|
||||
// The developer can just add a field of Expiry *NumericDate `json:"exp"`
|
||||
// and will be filled by the parsed token automatically.
|
||||
@@ -593,16 +616,37 @@ type TokenPair struct {
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
}
|
||||
|
||||
type tokenWithMaxAge struct {
|
||||
// Useful to separate access from refresh tokens.
|
||||
// Can be used to by-pass the internal check of expected
|
||||
// MaxAge setting to match the token's received max age too.
|
||||
MaxAge time.Duration `json:"tokenMaxAge"`
|
||||
}
|
||||
|
||||
// TokenPair generates a token pair of access and refresh tokens.
|
||||
// The first two arguments required for the refresh token
|
||||
// and the last one is the claims for the access token one.
|
||||
func (j *JWT) TokenPair(refreshMaxAge time.Duration, refreshClaims interface{}, accessClaims interface{}) (TokenPair, error) {
|
||||
if refreshMaxAge <= j.MaxAge {
|
||||
return TokenPair{}, fmt.Errorf("refresh max age should be bigger than access token's one[%d - %d]", refreshMaxAge, j.MaxAge)
|
||||
}
|
||||
|
||||
accessToken, err := j.Token(accessClaims)
|
||||
if err != nil {
|
||||
return TokenPair{}, err
|
||||
}
|
||||
|
||||
refreshToken, err := j.token(refreshMaxAge, refreshClaims)
|
||||
c, err := normalize(refreshClaims)
|
||||
if err != nil {
|
||||
return TokenPair{}, err
|
||||
}
|
||||
if c == nil {
|
||||
c = make(context.Map)
|
||||
}
|
||||
// need to validate against its value instead of the setting's one (see `VerifyTokenString`).
|
||||
c["tokenMaxAge"] = refreshMaxAge
|
||||
|
||||
refreshToken, err := j.token(refreshMaxAge, c)
|
||||
if err != nil {
|
||||
return TokenPair{}, nil
|
||||
}
|
||||
|
||||
@@ -21,9 +21,9 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrMissing when token cannot be extracted from the request.
|
||||
// ErrMissing when token cannot be extracted from the request (custm error).
|
||||
ErrMissing = errors.New("token is missing")
|
||||
// ErrMissingKey when token does not contain a required JSON field.
|
||||
// ErrMissingKey when token does not contain a required JSON field (custom error).
|
||||
ErrMissingKey = errors.New("token is missing a required field")
|
||||
// ErrExpired indicates that token is used after expiry time indicated in exp claim.
|
||||
ErrExpired = errors.New("token is expired (exp)")
|
||||
@@ -32,8 +32,14 @@ var (
|
||||
// ErrIssuedInTheFuture indicates that the iat field is in the future.
|
||||
ErrIssuedInTheFuture = errors.New("token issued in the future (iat)")
|
||||
// ErrBlocked indicates that the token was not yet expired
|
||||
// but was blocked by the server's Blocklist.
|
||||
// but was blocked by the server's Blocklist (custom error).
|
||||
ErrBlocked = errors.New("token is blocked")
|
||||
// ErrInvalidMaxAge indicates that the token is using a different
|
||||
// max age than the configurated one ( custom error).
|
||||
ErrInvalidMaxAge = errors.New("token contains invalid max age")
|
||||
// ErrExpectRefreshToken indicates that the retrieved token
|
||||
// was not a refresh token one when `ExpectRefreshToken` is set (custome rror).
|
||||
ErrExpectRefreshToken = errors.New("expect refresh token")
|
||||
)
|
||||
|
||||
// Expectation option to provide
|
||||
@@ -81,6 +87,16 @@ func ExpectAudience(audience ...string) Expectation {
|
||||
}
|
||||
}
|
||||
|
||||
// ExpectRefreshToken SHOULD be passed when a token should be verified
|
||||
// based on the expiration set by `TokenPair` method instead of the JWT instance's MaxAge setting.
|
||||
// Useful to validate Refresh Tokens and invalidate Access ones when refresh API is fired,
|
||||
// if that option is missing then refresh tokens are invalidated when an access token was expected.
|
||||
//
|
||||
// Usage:
|
||||
// var refreshClaims jwt.Claims
|
||||
// _, err := j.VerifyTokenString(ctx, tokenPair.RefreshToken, &refreshClaims, jwt.ExpectRefreshToken)
|
||||
func ExpectRefreshToken(e *Expected, _ interface{}) error { return ErrExpectRefreshToken }
|
||||
|
||||
// MeetRequirements protects the custom fields of JWT claims
|
||||
// based on the json:required tag; `json:"name,required"`.
|
||||
// It accepts the value type.
|
||||
@@ -210,3 +226,33 @@ func getRequiredFieldIndexes(i interface{}) (v []int) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// getMaxAge returns the result of expiry-issued at.
|
||||
// Note that if in JWT MaxAge's was set to a value like: 3.5 seconds
|
||||
// this will return 3 on token retreival. Of course this is not a problem
|
||||
// in real world apps as they don't invalidate tokens in seconds
|
||||
// based on a division result like 2/7.
|
||||
func getMaxAge(claims Claims) time.Duration {
|
||||
if issuedAt := claims.IssuedAt.Time(); !issuedAt.IsZero() {
|
||||
gotMaxAge := claims.Expiry.Time().Sub(issuedAt)
|
||||
return gotMaxAge
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
func compareMaxAge(expected, got time.Duration) bool {
|
||||
if expected == got {
|
||||
return true
|
||||
}
|
||||
|
||||
// got is int64, maybe rounded, but the max age setting is precise, may be a float result
|
||||
// e.g. the result of a division 2/7=3.5,
|
||||
// try to validate by round of second so similar/or equal max age setting are considered valid.
|
||||
min, max := expected-time.Second, expected+time.Second
|
||||
if got < min || got > max {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user