Implement refresh token logic with fingerprint + rotation
This commit is contained in:
@@ -1,161 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/authorizerdev/authorizer/server/constants"
|
||||
"github.com/authorizerdev/authorizer/server/db/models"
|
||||
"github.com/authorizerdev/authorizer/server/envstore"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt"
|
||||
"github.com/robertkrimen/otto"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// CreateAuthToken util to create JWT token, based on
|
||||
// user information, roles config and CUSTOM_ACCESS_TOKEN_SCRIPT
|
||||
func CreateAuthToken(user models.User, tokenType string, roles []string) (string, int64, error) {
|
||||
t := jwt.New(jwt.GetSigningMethod(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyJwtType)))
|
||||
expiryBound := time.Hour
|
||||
if tokenType == constants.TokenTypeRefreshToken {
|
||||
// expires in 1 year
|
||||
expiryBound = time.Hour * 8760
|
||||
}
|
||||
|
||||
expiresAt := time.Now().Add(expiryBound).Unix()
|
||||
|
||||
resUser := GetResponseUserData(user)
|
||||
userBytes, _ := json.Marshal(&resUser)
|
||||
var userMap map[string]interface{}
|
||||
json.Unmarshal(userBytes, &userMap)
|
||||
|
||||
claimKey := envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyJwtRoleClaim)
|
||||
customClaims := jwt.MapClaims{
|
||||
"exp": expiresAt,
|
||||
"iat": time.Now().Unix(),
|
||||
"token_type": tokenType,
|
||||
"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
|
||||
accessTokenScript := os.Getenv(constants.EnvKeyCustomAccessTokenScript)
|
||||
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 {
|
||||
log.Println("error getting custom access token script:", err)
|
||||
} else {
|
||||
extraPayload := make(map[string]interface{})
|
||||
err = json.Unmarshal([]byte(fmt.Sprintf("%s", val)), &extraPayload)
|
||||
if err != nil {
|
||||
log.Println("error converting accessTokenScript response to map:", err)
|
||||
} else {
|
||||
for k, v := range extraPayload {
|
||||
customClaims[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
t.Claims = customClaims
|
||||
|
||||
token, err := t.SignedString([]byte(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyJwtSecret)))
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
|
||||
return token, expiresAt, nil
|
||||
}
|
||||
|
||||
// GetAuthToken helps in getting the JWT token from the
|
||||
// request cookie or authorization header
|
||||
func GetAuthToken(gc *gin.Context) (string, error) {
|
||||
token, err := GetCookie(gc)
|
||||
if err != nil || token == "" {
|
||||
// try to check in auth header for cookie
|
||||
auth := gc.Request.Header.Get("Authorization")
|
||||
if auth == "" {
|
||||
return "", fmt.Errorf(`unauthorized`)
|
||||
}
|
||||
|
||||
token = strings.TrimPrefix(auth, "Bearer ")
|
||||
}
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// VerifyAuthToken helps in verifying the JWT token
|
||||
func VerifyAuthToken(token string) (map[string]interface{}, error) {
|
||||
var res map[string]interface{}
|
||||
claims := jwt.MapClaims{}
|
||||
|
||||
_, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyJwtSecret)), nil
|
||||
})
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
// claim parses exp & iat into float 64 with e^10,
|
||||
// but we expect it to be int64
|
||||
// hence we need to assert interface and convert to int64
|
||||
intExp := int64(claims["exp"].(float64))
|
||||
intIat := int64(claims["iat"].(float64))
|
||||
|
||||
data, _ := json.Marshal(claims)
|
||||
json.Unmarshal(data, &res)
|
||||
res["exp"] = intExp
|
||||
res["iat"] = intIat
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// CreateAdminAuthToken creates the admin token based on secret key
|
||||
func CreateAdminAuthToken(tokenType string, c *gin.Context) (string, error) {
|
||||
return EncryptPassword(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAdminSecret))
|
||||
}
|
||||
|
||||
// GetAdminAuthToken helps in getting the admin token from the request cookie
|
||||
func GetAdminAuthToken(gc *gin.Context) (string, error) {
|
||||
token, err := GetAdminCookie(gc)
|
||||
if err != nil || token == "" {
|
||||
return "", fmt.Errorf("unauthorized")
|
||||
}
|
||||
|
||||
// cookie escapes special characters like $
|
||||
// hence we need to unescape before comparing
|
||||
decodedValue, err := url.QueryUnescape(token)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
err = bcrypt.CompareHashAndPassword([]byte(decodedValue), []byte(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAdminSecret)))
|
||||
log.Println("error comparing hash:", err)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf(`unauthorized`)
|
||||
}
|
||||
|
||||
return token, nil
|
||||
}
|
@@ -1,81 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/authorizerdev/authorizer/server/constants"
|
||||
"github.com/authorizerdev/authorizer/server/envstore"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// SetCookie sets the cookie in the response. It sets 2 cookies
|
||||
// 1 COOKIE_NAME for the host (abc.com)
|
||||
// 2 COOKIE_NAME-client for the domain (sub.abc.com).
|
||||
// Note all sites don't allow 2nd type of cookie
|
||||
func SetCookie(gc *gin.Context, token string) {
|
||||
secure := true
|
||||
httpOnly := true
|
||||
host, _ := GetHostParts(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAuthorizerURL))
|
||||
domain := GetDomainName(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAuthorizerURL))
|
||||
if domain != "localhost" {
|
||||
domain = "." + domain
|
||||
}
|
||||
|
||||
gc.SetSameSite(http.SameSiteNoneMode)
|
||||
gc.SetCookie(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyCookieName), token, 3600, "/", host, secure, httpOnly)
|
||||
gc.SetCookie(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyCookieName)+"-client", token, 3600, "/", domain, secure, httpOnly)
|
||||
}
|
||||
|
||||
// GetCookie gets the cookie from the request
|
||||
func GetCookie(gc *gin.Context) (string, error) {
|
||||
cookie, err := gc.Request.Cookie(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyCookieName))
|
||||
if err != nil {
|
||||
cookie, err = gc.Request.Cookie(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyCookieName) + "-client")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
|
||||
return cookie.Value, nil
|
||||
}
|
||||
|
||||
// DeleteCookie sets the cookie value as empty to make it expired
|
||||
func DeleteCookie(gc *gin.Context) {
|
||||
secure := true
|
||||
httpOnly := true
|
||||
|
||||
host, _ := GetHostParts(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAuthorizerURL))
|
||||
domain := GetDomainName(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAuthorizerURL))
|
||||
if domain != "localhost" {
|
||||
domain = "." + domain
|
||||
}
|
||||
|
||||
gc.SetSameSite(http.SameSiteNoneMode)
|
||||
gc.SetCookie(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyCookieName), "", -1, "/", host, secure, httpOnly)
|
||||
gc.SetCookie(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyCookieName)+"-client", "", -1, "/", domain, secure, httpOnly)
|
||||
}
|
||||
|
||||
// SetAdminCookie sets the admin cookie in the response
|
||||
func SetAdminCookie(gc *gin.Context, token string) {
|
||||
secure := true
|
||||
httpOnly := true
|
||||
host, _ := GetHostParts(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAuthorizerURL))
|
||||
|
||||
gc.SetCookie(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAdminCookieName), token, 3600, "/", host, secure, httpOnly)
|
||||
}
|
||||
|
||||
func GetAdminCookie(gc *gin.Context) (string, error) {
|
||||
cookie, err := gc.Request.Cookie(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAdminCookieName))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return cookie.Value, nil
|
||||
}
|
||||
|
||||
func DeleteAdminCookie(gc *gin.Context) {
|
||||
secure := true
|
||||
httpOnly := true
|
||||
host, _ := GetHostParts(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAuthorizerURL))
|
||||
|
||||
gc.SetCookie(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAdminCookieName), "", -1, "/", host, secure, httpOnly)
|
||||
}
|
@@ -1,32 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/authorizerdev/authorizer/server/envstore"
|
||||
)
|
||||
|
||||
func EncryptConfig(data map[string]interface{}) ([]byte, error) {
|
||||
jsonBytes, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return []byte{}, err
|
||||
}
|
||||
|
||||
envData := envstore.EnvInMemoryStoreObj.GetEnvStoreClone()
|
||||
|
||||
err = json.Unmarshal(jsonBytes, &envData)
|
||||
if err != nil {
|
||||
return []byte{}, err
|
||||
}
|
||||
|
||||
configData, err := json.Marshal(envData)
|
||||
if err != nil {
|
||||
return []byte{}, err
|
||||
}
|
||||
encryptedConfig, err := EncryptAES(configData)
|
||||
if err != nil {
|
||||
return []byte{}, err
|
||||
}
|
||||
|
||||
return encryptedConfig, nil
|
||||
}
|
@@ -1,35 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/authorizerdev/authorizer/server/db/models"
|
||||
"github.com/authorizerdev/authorizer/server/graph/model"
|
||||
)
|
||||
|
||||
// TODO move this to provider
|
||||
// rename it to AsAPIUser
|
||||
|
||||
func GetResponseUserData(user models.User) *model.User {
|
||||
isEmailVerified := user.EmailVerifiedAt != nil
|
||||
isPhoneVerified := user.PhoneNumberVerifiedAt != nil
|
||||
return &model.User{
|
||||
ID: user.ID,
|
||||
Email: user.Email,
|
||||
EmailVerified: isEmailVerified,
|
||||
SignupMethods: user.SignupMethods,
|
||||
GivenName: user.GivenName,
|
||||
FamilyName: user.FamilyName,
|
||||
MiddleName: user.MiddleName,
|
||||
Nickname: user.Nickname,
|
||||
PreferredUsername: &user.Email,
|
||||
Gender: user.Gender,
|
||||
Birthdate: user.Birthdate,
|
||||
PhoneNumber: user.PhoneNumber,
|
||||
PhoneNumberVerified: &isPhoneVerified,
|
||||
Picture: user.Picture,
|
||||
Roles: strings.Split(user.Roles, ","),
|
||||
CreatedAt: &user.CreatedAt,
|
||||
UpdatedAt: &user.UpdatedAt,
|
||||
}
|
||||
}
|
@@ -8,7 +8,7 @@ import (
|
||||
// GetHostName function returns hostname and port
|
||||
func GetHostParts(uri string) (string, string) {
|
||||
tempURI := uri
|
||||
if !strings.HasPrefix(tempURI, "http") && strings.HasPrefix(tempURI, "https") {
|
||||
if !strings.HasPrefix(tempURI, "http://") && !strings.HasPrefix(tempURI, "https://") {
|
||||
tempURI = "https://" + tempURI
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ func GetHostParts(uri string) (string, string) {
|
||||
// GetDomainName function to get domain name
|
||||
func GetDomainName(uri string) string {
|
||||
tempURI := uri
|
||||
if !strings.HasPrefix(tempURI, "http") && strings.HasPrefix(tempURI, "https") {
|
||||
if !strings.HasPrefix(tempURI, "http://") && !strings.HasPrefix(tempURI, "https://") {
|
||||
tempURI = "https://" + tempURI
|
||||
}
|
||||
|
||||
|
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"github.com/authorizerdev/authorizer/server/constants"
|
||||
"github.com/authorizerdev/authorizer/server/envstore"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// IsValidEmail validates email
|
||||
@@ -52,21 +51,6 @@ func IsValidOrigin(url string) bool {
|
||||
return hasValidURL
|
||||
}
|
||||
|
||||
// IsSuperAdmin checks if user is super admin
|
||||
func IsSuperAdmin(gc *gin.Context) bool {
|
||||
token, err := GetAdminAuthToken(gc)
|
||||
if err != nil {
|
||||
secret := gc.Request.Header.Get("x-authorizer-admin-secret")
|
||||
if secret == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
return secret == envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAdminSecret)
|
||||
}
|
||||
|
||||
return token != ""
|
||||
}
|
||||
|
||||
// IsValidRoles validates roles
|
||||
func IsValidRoles(userRoles []string, roles []string) bool {
|
||||
valid := true
|
||||
|
@@ -1,53 +0,0 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/authorizerdev/authorizer/server/constants"
|
||||
"github.com/authorizerdev/authorizer/server/envstore"
|
||||
"github.com/golang-jwt/jwt"
|
||||
)
|
||||
|
||||
// TODO see if we can move this to different service
|
||||
|
||||
// UserInfo is the user info that is stored in the JWT of verification request
|
||||
type UserInfo struct {
|
||||
Email string `json:"email"`
|
||||
Host string `json:"host"`
|
||||
RedirectURL string `json:"redirect_url"`
|
||||
}
|
||||
|
||||
// CustomClaim is the custom claim that is stored in the JWT of verification request
|
||||
type CustomClaim struct {
|
||||
*jwt.StandardClaims
|
||||
TokenType string `json:"token_type"`
|
||||
UserInfo
|
||||
}
|
||||
|
||||
// CreateVerificationToken creates a verification JWT token
|
||||
func CreateVerificationToken(email string, tokenType string) (string, error) {
|
||||
t := jwt.New(jwt.GetSigningMethod(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyJwtType)))
|
||||
|
||||
t.Claims = &CustomClaim{
|
||||
&jwt.StandardClaims{
|
||||
ExpiresAt: time.Now().Add(time.Minute * 30).Unix(),
|
||||
},
|
||||
tokenType,
|
||||
UserInfo{Email: email, Host: envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAuthorizerURL), RedirectURL: envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAppURL)},
|
||||
}
|
||||
|
||||
return t.SignedString([]byte(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyJwtSecret)))
|
||||
}
|
||||
|
||||
// VerifyVerificationToken verifies the verification JWT token
|
||||
func VerifyVerificationToken(token string) (*CustomClaim, error) {
|
||||
claims := &CustomClaim{}
|
||||
_, err := jwt.ParseWithClaims(token, claims, func(token *jwt.Token) (interface{}, error) {
|
||||
return []byte(envstore.EnvInMemoryStoreObj.GetStringStoreEnvVariable(constants.EnvKeyJwtSecret)), nil
|
||||
})
|
||||
if err != nil {
|
||||
return claims, err
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
Reference in New Issue
Block a user