2022-01-22 19:54:41 +00:00
|
|
|
package token
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2022-05-24 07:20:33 +00:00
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
|
2022-03-02 12:12:31 +00:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/golang-jwt/jwt"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/robertkrimen/otto"
|
|
|
|
|
2022-01-22 19:54:41 +00:00
|
|
|
"github.com/authorizerdev/authorizer/server/constants"
|
2022-02-28 15:56:49 +00:00
|
|
|
"github.com/authorizerdev/authorizer/server/crypto"
|
2022-01-22 19:54:41 +00:00
|
|
|
"github.com/authorizerdev/authorizer/server/db/models"
|
2022-05-27 17:50:38 +00:00
|
|
|
"github.com/authorizerdev/authorizer/server/memorystore"
|
2022-05-30 06:24:16 +00:00
|
|
|
"github.com/authorizerdev/authorizer/server/parsers"
|
2022-03-02 12:12:31 +00:00
|
|
|
"github.com/authorizerdev/authorizer/server/utils"
|
2022-01-22 19:54:41 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// JWTToken is a struct to hold JWT token and its expiration time
|
|
|
|
type JWTToken struct {
|
|
|
|
Token string `json:"token"`
|
|
|
|
ExpiresAt int64 `json:"expires_at"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// Token object to hold the finger print and refresh token information
|
|
|
|
type Token struct {
|
|
|
|
FingerPrint string `json:"fingerprint"`
|
|
|
|
FingerPrintHash string `json:"fingerprint_hash"`
|
|
|
|
RefreshToken *JWTToken `json:"refresh_token"`
|
|
|
|
AccessToken *JWTToken `json:"access_token"`
|
2022-03-02 12:12:31 +00:00
|
|
|
IDToken *JWTToken `json:"id_token"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// SessionData
|
|
|
|
type SessionData struct {
|
|
|
|
Subject string `json:"sub"`
|
|
|
|
Roles []string `json:"roles"`
|
|
|
|
Scope []string `json:"scope"`
|
|
|
|
Nonce string `json:"nonce"`
|
|
|
|
IssuedAt int64 `json:"iat"`
|
|
|
|
ExpiresAt int64 `json:"exp"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// CreateSessionToken creates a new session token
|
|
|
|
func CreateSessionToken(user models.User, nonce string, roles, scope []string) (*SessionData, string, error) {
|
|
|
|
fingerPrintMap := &SessionData{
|
|
|
|
Nonce: nonce,
|
|
|
|
Roles: roles,
|
|
|
|
Subject: user.ID,
|
|
|
|
Scope: scope,
|
|
|
|
IssuedAt: time.Now().Unix(),
|
|
|
|
ExpiresAt: time.Now().AddDate(1, 0, 0).Unix(),
|
|
|
|
}
|
|
|
|
fingerPrintBytes, _ := json.Marshal(fingerPrintMap)
|
|
|
|
fingerPrintHash, err := crypto.EncryptAES(string(fingerPrintBytes))
|
|
|
|
if err != nil {
|
|
|
|
return nil, "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return fingerPrintMap, fingerPrintHash, nil
|
2022-01-22 19:54:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// CreateAuthToken creates a new auth token when userlogs in
|
2022-03-02 12:12:31 +00:00
|
|
|
func CreateAuthToken(gc *gin.Context, user models.User, roles, scope []string) (*Token, error) {
|
2022-05-30 06:24:16 +00:00
|
|
|
hostname := parsers.GetHost(gc)
|
2022-03-02 12:12:31 +00:00
|
|
|
nonce := uuid.New().String()
|
|
|
|
_, fingerPrintHash, err := CreateSessionToken(user, nonce, roles, scope)
|
2022-01-22 19:54:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-03-02 12:12:31 +00:00
|
|
|
accessToken, accessTokenExpiresAt, err := CreateAccessToken(user, roles, scope, hostname, nonce)
|
2022-01-22 19:54:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-03-02 12:12:31 +00:00
|
|
|
idToken, idTokenExpiresAt, err := CreateIDToken(user, roles, hostname, nonce)
|
2022-01-22 19:54:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
2022-03-02 12:12:31 +00:00
|
|
|
res := &Token{
|
|
|
|
FingerPrint: nonce,
|
|
|
|
FingerPrintHash: fingerPrintHash,
|
2022-01-22 19:54:41 +00:00
|
|
|
AccessToken: &JWTToken{Token: accessToken, ExpiresAt: accessTokenExpiresAt},
|
2022-03-02 12:12:31 +00:00
|
|
|
IDToken: &JWTToken{Token: idToken, ExpiresAt: idTokenExpiresAt},
|
|
|
|
}
|
|
|
|
|
|
|
|
if utils.StringSliceContains(scope, "offline_access") {
|
2022-03-08 09:26:46 +00:00
|
|
|
refreshToken, refreshTokenExpiresAt, err := CreateRefreshToken(user, roles, scope, hostname, nonce)
|
2022-03-02 12:12:31 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
res.RefreshToken = &JWTToken{Token: refreshToken, ExpiresAt: refreshTokenExpiresAt}
|
|
|
|
}
|
|
|
|
|
|
|
|
return res, nil
|
2022-01-22 19:54:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// CreateRefreshToken util to create JWT token
|
2022-03-08 09:26:46 +00:00
|
|
|
func CreateRefreshToken(user models.User, roles, scopes []string, hostname, nonce string) (string, int64, error) {
|
2022-01-22 19:54:41 +00:00
|
|
|
// expires in 1 year
|
|
|
|
expiryBound := time.Hour * 8760
|
|
|
|
expiresAt := time.Now().Add(expiryBound).Unix()
|
2022-05-30 05:30:00 +00:00
|
|
|
clientID, err := memorystore.Provider.GetStringStoreEnvVariable(constants.EnvKeyClientID)
|
|
|
|
if err != nil {
|
|
|
|
return "", 0, err
|
|
|
|
}
|
2022-01-22 19:54:41 +00:00
|
|
|
customClaims := jwt.MapClaims{
|
2022-03-02 12:12:31 +00:00
|
|
|
"iss": hostname,
|
2022-05-30 05:30:00 +00:00
|
|
|
"aud": clientID,
|
2022-02-22 05:36:47 +00:00
|
|
|
"sub": user.ID,
|
2022-01-22 19:54:41 +00:00
|
|
|
"exp": expiresAt,
|
|
|
|
"iat": time.Now().Unix(),
|
|
|
|
"token_type": constants.TokenTypeRefreshToken,
|
|
|
|
"roles": roles,
|
2022-03-08 09:26:46 +00:00
|
|
|
"scope": scopes,
|
2022-03-02 12:12:31 +00:00
|
|
|
"nonce": nonce,
|
2022-01-22 19:54:41 +00:00
|
|
|
}
|
|
|
|
|
2022-02-12 10:24:23 +00:00
|
|
|
token, err := SignJWTToken(customClaims)
|
2022-01-22 19:54:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", 0, err
|
|
|
|
}
|
2022-03-02 12:12:31 +00:00
|
|
|
|
2022-01-22 19:54:41 +00:00
|
|
|
return token, expiresAt, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// CreateAccessToken util to create JWT token, based on
|
|
|
|
// user information, roles config and CUSTOM_ACCESS_TOKEN_SCRIPT
|
2022-03-02 12:12:31 +00:00
|
|
|
func CreateAccessToken(user models.User, roles, scopes []string, hostName, nonce string) (string, int64, error) {
|
2022-05-30 05:30:00 +00:00
|
|
|
expireTime, err := memorystore.Provider.GetStringStoreEnvVariable(constants.EnvKeyAccessTokenExpiryTime)
|
|
|
|
if err != nil {
|
|
|
|
return "", 0, err
|
|
|
|
}
|
|
|
|
expiryBound, err := utils.ParseDurationInSeconds(expireTime)
|
2022-03-25 12:21:20 +00:00
|
|
|
if err != nil {
|
2022-03-25 14:59:00 +00:00
|
|
|
expiryBound = time.Minute * 30
|
2022-03-25 12:21:20 +00:00
|
|
|
}
|
|
|
|
|
2022-03-02 12:12:31 +00:00
|
|
|
expiresAt := time.Now().Add(expiryBound).Unix()
|
|
|
|
|
2022-05-30 05:30:00 +00:00
|
|
|
clientID, err := memorystore.Provider.GetStringStoreEnvVariable(constants.EnvKeyClientID)
|
|
|
|
if err != nil {
|
|
|
|
return "", 0, err
|
|
|
|
}
|
2022-03-02 12:12:31 +00:00
|
|
|
customClaims := jwt.MapClaims{
|
|
|
|
"iss": hostName,
|
2022-05-30 05:30:00 +00:00
|
|
|
"aud": clientID,
|
2022-03-02 12:12:31 +00:00
|
|
|
"nonce": nonce,
|
|
|
|
"sub": user.ID,
|
|
|
|
"exp": expiresAt,
|
|
|
|
"iat": time.Now().Unix(),
|
|
|
|
"token_type": constants.TokenTypeAccessToken,
|
|
|
|
"scope": scopes,
|
|
|
|
"roles": roles,
|
|
|
|
}
|
|
|
|
|
|
|
|
token, err := SignJWTToken(customClaims)
|
|
|
|
if err != nil {
|
|
|
|
return "", 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return token, expiresAt, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetAccessToken returns the access token from the request (either from header or cookie)
|
|
|
|
func GetAccessToken(gc *gin.Context) (string, error) {
|
|
|
|
// try to check in auth header for cookie
|
|
|
|
auth := gc.Request.Header.Get("Authorization")
|
|
|
|
if auth == "" {
|
|
|
|
return "", fmt.Errorf(`unauthorized`)
|
|
|
|
}
|
|
|
|
|
2022-03-24 08:01:56 +00:00
|
|
|
authSplit := strings.Split(auth, " ")
|
|
|
|
if len(authSplit) != 2 {
|
|
|
|
return "", fmt.Errorf(`unauthorized`)
|
|
|
|
}
|
|
|
|
|
|
|
|
if strings.ToLower(authSplit[0]) != "bearer" {
|
2022-03-02 12:12:31 +00:00
|
|
|
return "", fmt.Errorf(`not a bearer token`)
|
|
|
|
}
|
|
|
|
|
|
|
|
token := strings.TrimPrefix(auth, "Bearer ")
|
|
|
|
return token, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Function to validate access token for authorizer apis (profile, update_profile)
|
|
|
|
func ValidateAccessToken(gc *gin.Context, accessToken string) (map[string]interface{}, error) {
|
|
|
|
var res map[string]interface{}
|
|
|
|
|
|
|
|
if accessToken == "" {
|
|
|
|
return res, fmt.Errorf(`unauthorized`)
|
|
|
|
}
|
|
|
|
|
2022-05-29 11:52:46 +00:00
|
|
|
savedSession, err := memorystore.Provider.GetState(accessToken)
|
|
|
|
if savedSession == "" || err != nil {
|
2022-03-02 12:12:31 +00:00
|
|
|
return res, fmt.Errorf(`unauthorized`)
|
|
|
|
}
|
|
|
|
|
|
|
|
savedSessionSplit := strings.Split(savedSession, "@")
|
|
|
|
nonce := savedSessionSplit[0]
|
|
|
|
userID := savedSessionSplit[1]
|
|
|
|
|
2022-05-30 06:24:16 +00:00
|
|
|
hostname := parsers.GetHost(gc)
|
2022-05-29 11:52:46 +00:00
|
|
|
res, err = ParseJWTToken(accessToken, hostname, nonce, userID)
|
2022-03-02 12:12:31 +00:00
|
|
|
if err != nil {
|
|
|
|
return res, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if res["token_type"] != constants.TokenTypeAccessToken {
|
|
|
|
return res, fmt.Errorf(`unauthorized: invalid token type`)
|
|
|
|
}
|
|
|
|
|
|
|
|
return res, nil
|
|
|
|
}
|
|
|
|
|
2022-03-08 09:26:46 +00:00
|
|
|
// Function to validate refreshToken
|
|
|
|
func ValidateRefreshToken(gc *gin.Context, refreshToken string) (map[string]interface{}, error) {
|
|
|
|
var res map[string]interface{}
|
|
|
|
|
|
|
|
if refreshToken == "" {
|
|
|
|
return res, fmt.Errorf(`unauthorized`)
|
|
|
|
}
|
|
|
|
|
2022-05-29 11:52:46 +00:00
|
|
|
savedSession, err := memorystore.Provider.GetState(refreshToken)
|
|
|
|
if savedSession == "" || err != nil {
|
2022-03-08 09:26:46 +00:00
|
|
|
return res, fmt.Errorf(`unauthorized`)
|
|
|
|
}
|
|
|
|
|
|
|
|
savedSessionSplit := strings.Split(savedSession, "@")
|
|
|
|
nonce := savedSessionSplit[0]
|
|
|
|
userID := savedSessionSplit[1]
|
|
|
|
|
2022-05-30 06:24:16 +00:00
|
|
|
hostname := parsers.GetHost(gc)
|
2022-05-29 11:52:46 +00:00
|
|
|
res, err = ParseJWTToken(refreshToken, hostname, nonce, userID)
|
2022-03-08 09:26:46 +00:00
|
|
|
if err != nil {
|
|
|
|
return res, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if res["token_type"] != constants.TokenTypeRefreshToken {
|
|
|
|
return res, fmt.Errorf(`unauthorized: invalid token type`)
|
|
|
|
}
|
|
|
|
|
|
|
|
return res, nil
|
|
|
|
}
|
|
|
|
|
2022-03-02 12:12:31 +00:00
|
|
|
func ValidateBrowserSession(gc *gin.Context, encryptedSession string) (*SessionData, error) {
|
|
|
|
if encryptedSession == "" {
|
|
|
|
return nil, fmt.Errorf(`unauthorized`)
|
|
|
|
}
|
|
|
|
|
2022-05-29 11:52:46 +00:00
|
|
|
savedSession, err := memorystore.Provider.GetState(encryptedSession)
|
|
|
|
if savedSession == "" || err != nil {
|
2022-03-02 12:12:31 +00:00
|
|
|
return nil, fmt.Errorf(`unauthorized`)
|
|
|
|
}
|
|
|
|
|
|
|
|
savedSessionSplit := strings.Split(savedSession, "@")
|
|
|
|
nonce := savedSessionSplit[0]
|
|
|
|
userID := savedSessionSplit[1]
|
|
|
|
|
|
|
|
decryptedFingerPrint, err := crypto.DecryptAES(encryptedSession)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
var res SessionData
|
|
|
|
err = json.Unmarshal([]byte(decryptedFingerPrint), &res)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if res.Nonce != nonce {
|
|
|
|
return nil, fmt.Errorf(`unauthorized: invalid nonce`)
|
|
|
|
}
|
|
|
|
|
|
|
|
if res.Subject != userID {
|
|
|
|
return nil, fmt.Errorf(`unauthorized: invalid user id`)
|
|
|
|
}
|
|
|
|
|
|
|
|
if res.ExpiresAt < time.Now().Unix() {
|
|
|
|
return nil, fmt.Errorf(`unauthorized: token expired`)
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO validate scope
|
|
|
|
// if !reflect.DeepEqual(res.Roles, roles) {
|
|
|
|
// return res, "", fmt.Errorf(`unauthorized`)
|
|
|
|
// }
|
|
|
|
|
|
|
|
return &res, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// CreateIDToken util to create JWT token, based on
|
|
|
|
// user information, roles config and CUSTOM_ACCESS_TOKEN_SCRIPT
|
|
|
|
func CreateIDToken(user models.User, roles []string, hostname, nonce string) (string, int64, error) {
|
2022-05-30 05:30:00 +00:00
|
|
|
expireTime, err := memorystore.Provider.GetStringStoreEnvVariable(constants.EnvKeyAccessTokenExpiryTime)
|
|
|
|
if err != nil {
|
|
|
|
return "", 0, err
|
|
|
|
}
|
|
|
|
expiryBound, err := utils.ParseDurationInSeconds(expireTime)
|
2022-03-25 12:21:20 +00:00
|
|
|
if err != nil {
|
2022-03-25 14:59:00 +00:00
|
|
|
expiryBound = time.Minute * 30
|
2022-03-25 12:21:20 +00:00
|
|
|
}
|
|
|
|
|
2022-01-22 19:54:41 +00:00
|
|
|
expiresAt := time.Now().Add(expiryBound).Unix()
|
|
|
|
|
|
|
|
resUser := user.AsAPIUser()
|
|
|
|
userBytes, _ := json.Marshal(&resUser)
|
|
|
|
var userMap map[string]interface{}
|
|
|
|
json.Unmarshal(userBytes, &userMap)
|
|
|
|
|
2022-05-30 05:30:00 +00:00
|
|
|
claimKey, err := memorystore.Provider.GetStringStoreEnvVariable(constants.EnvKeyJwtRoleClaim)
|
|
|
|
if err != nil {
|
|
|
|
claimKey = "roles"
|
|
|
|
}
|
|
|
|
|
|
|
|
clientID, err := memorystore.Provider.GetStringStoreEnvVariable(constants.EnvKeyClientID)
|
|
|
|
if err != nil {
|
|
|
|
return "", 0, err
|
|
|
|
}
|
2022-01-22 19:54:41 +00:00
|
|
|
customClaims := jwt.MapClaims{
|
2022-03-02 12:12:31 +00:00
|
|
|
"iss": hostname,
|
2022-05-30 05:30:00 +00:00
|
|
|
"aud": clientID,
|
2022-03-02 12:12:31 +00:00
|
|
|
"nonce": nonce,
|
2022-02-22 05:36:47 +00:00
|
|
|
"sub": user.ID,
|
2022-01-22 19:54:41 +00:00
|
|
|
"exp": expiresAt,
|
|
|
|
"iat": time.Now().Unix(),
|
2022-03-02 12:12:31 +00:00
|
|
|
"token_type": constants.TokenTypeIdentityToken,
|
2022-01-22 19:54:41 +00:00
|
|
|
"allowed_roles": strings.Split(user.Roles, ","),
|
|
|
|
claimKey: roles,
|
|
|
|
}
|
|
|
|
|
|
|
|
for k, v := range userMap {
|
|
|
|
if k != "roles" {
|
|
|
|
customClaims[k] = v
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// check for the extra access token script
|
2022-05-30 05:30:00 +00:00
|
|
|
accessTokenScript, err := memorystore.Provider.GetStringStoreEnvVariable(constants.EnvKeyCustomAccessTokenScript)
|
|
|
|
if err != nil {
|
|
|
|
log.Debug("Failed to get custom access token script: ", err)
|
|
|
|
accessTokenScript = ""
|
|
|
|
}
|
2022-01-22 19:54:41 +00:00
|
|
|
if accessTokenScript != "" {
|
|
|
|
vm := otto.New()
|
|
|
|
|
|
|
|
claimBytes, _ := json.Marshal(customClaims)
|
|
|
|
vm.Run(fmt.Sprintf(`
|
|
|
|
var user = %s;
|
|
|
|
var tokenPayload = %s;
|
|
|
|
var customFunction = %s;
|
|
|
|
var functionRes = JSON.stringify(customFunction(user, tokenPayload));
|
|
|
|
`, string(userBytes), string(claimBytes), accessTokenScript))
|
|
|
|
|
|
|
|
val, err := vm.Get("functionRes")
|
|
|
|
if err != nil {
|
2022-05-25 07:00:22 +00:00
|
|
|
log.Debug("error getting custom access token script: ", err)
|
2022-01-22 19:54:41 +00:00
|
|
|
} else {
|
|
|
|
extraPayload := make(map[string]interface{})
|
|
|
|
err = json.Unmarshal([]byte(fmt.Sprintf("%s", val)), &extraPayload)
|
|
|
|
if err != nil {
|
2022-05-25 07:00:22 +00:00
|
|
|
log.Debug("error converting accessTokenScript response to map: ", err)
|
2022-01-22 19:54:41 +00:00
|
|
|
} else {
|
|
|
|
for k, v := range extraPayload {
|
|
|
|
customClaims[k] = v
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-12 10:24:23 +00:00
|
|
|
token, err := SignJWTToken(customClaims)
|
2022-01-22 19:54:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return token, expiresAt, nil
|
|
|
|
}
|
|
|
|
|
2022-03-02 12:12:31 +00:00
|
|
|
// GetIDToken returns the id token from the request header
|
|
|
|
func GetIDToken(gc *gin.Context) (string, error) {
|
|
|
|
// try to check in auth header for cookie
|
|
|
|
auth := gc.Request.Header.Get("Authorization")
|
|
|
|
if auth == "" {
|
2022-01-22 19:54:41 +00:00
|
|
|
return "", fmt.Errorf(`unauthorized`)
|
|
|
|
}
|
|
|
|
|
2022-03-24 08:01:56 +00:00
|
|
|
authSplit := strings.Split(auth, " ")
|
|
|
|
if len(authSplit) != 2 {
|
|
|
|
return "", fmt.Errorf(`unauthorized`)
|
|
|
|
}
|
|
|
|
|
|
|
|
if strings.ToLower(authSplit[0]) != "bearer" {
|
2022-03-02 12:12:31 +00:00
|
|
|
return "", fmt.Errorf(`not a bearer token`)
|
2022-01-22 19:54:41 +00:00
|
|
|
}
|
|
|
|
|
2022-03-02 12:12:31 +00:00
|
|
|
token := strings.TrimPrefix(auth, "Bearer ")
|
|
|
|
return token, nil
|
2022-01-22 19:54:41 +00:00
|
|
|
}
|