authorizer/server/handlers/token.go

214 lines
6.5 KiB
Go
Raw Normal View History

2022-03-04 07:26:11 +00:00
package handlers
import (
"crypto/sha256"
"encoding/base64"
"net/http"
"strings"
"time"
2022-03-04 07:26:11 +00:00
2022-05-23 06:22:51 +00:00
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
2022-03-07 03:01:39 +00:00
"github.com/authorizerdev/authorizer/server/constants"
2022-03-04 07:26:11 +00:00
"github.com/authorizerdev/authorizer/server/cookie"
"github.com/authorizerdev/authorizer/server/db"
2022-05-27 17:50:38 +00:00
"github.com/authorizerdev/authorizer/server/memorystore"
2022-03-04 07:26:11 +00:00
"github.com/authorizerdev/authorizer/server/token"
)
2022-03-08 13:19:42 +00:00
// TokenHandler to handle /oauth/token requests
// grant type required
2022-03-04 07:26:11 +00:00
func TokenHandler() gin.HandlerFunc {
return func(gc *gin.Context) {
var reqBody map[string]string
if err := gc.BindJSON(&reqBody); err != nil {
2022-05-23 06:22:51 +00:00
log.Debug("Error binding JSON: ", err)
2022-03-04 07:26:11 +00:00
gc.JSON(http.StatusBadRequest, gin.H{
"error": "error_binding_json",
"error_description": err.Error(),
})
return
}
codeVerifier := strings.TrimSpace(reqBody["code_verifier"])
code := strings.TrimSpace(reqBody["code"])
2022-03-07 03:01:39 +00:00
clientID := strings.TrimSpace(reqBody["client_id"])
grantType := strings.TrimSpace(reqBody["grant_type"])
refreshToken := strings.TrimSpace(reqBody["refresh_token"])
if grantType == "" {
grantType = "authorization_code"
}
isRefreshTokenGrant := grantType == "refresh_token"
isAuthorizationCodeGrant := grantType == "authorization_code"
if !isRefreshTokenGrant && !isAuthorizationCodeGrant {
2022-05-25 07:00:22 +00:00
log.Debug("Invalid grant type: ", grantType)
gc.JSON(http.StatusBadRequest, gin.H{
"error": "invalid_grant_type",
"error_description": "grant_type is invalid",
})
}
2022-03-07 03:01:39 +00:00
if clientID == "" {
2022-05-23 06:22:51 +00:00
log.Debug("Client ID is empty")
2022-03-07 03:01:39 +00:00
gc.JSON(http.StatusBadRequest, gin.H{
"error": "client_id_required",
"error_description": "The client id is required",
})
return
}
2022-05-29 11:52:46 +00:00
if client, err := memorystore.Provider.GetStringStoreEnvVariable(constants.EnvKeyClientID); clientID != client || err != nil {
2022-05-25 07:00:22 +00:00
log.Debug("Client ID is invalid: ", clientID)
2022-03-07 03:01:39 +00:00
gc.JSON(http.StatusBadRequest, gin.H{
"error": "invalid_client_id",
"error_description": "The client id is invalid",
})
return
}
2022-03-04 07:26:11 +00:00
var userID string
var roles, scope []string
if isAuthorizationCodeGrant {
2022-03-04 07:26:11 +00:00
if codeVerifier == "" {
2022-05-23 06:22:51 +00:00
log.Debug("Code verifier is empty")
gc.JSON(http.StatusBadRequest, gin.H{
"error": "invalid_code_verifier",
"error_description": "The code verifier is required",
})
return
}
2022-03-04 07:26:11 +00:00
if code == "" {
2022-05-23 06:22:51 +00:00
log.Debug("Code is empty")
gc.JSON(http.StatusBadRequest, gin.H{
"error": "invalid_code",
"error_description": "The code is required",
})
return
}
2022-03-04 07:26:11 +00:00
hash := sha256.New()
hash.Write([]byte(codeVerifier))
encryptedCode := strings.ReplaceAll(base64.URLEncoding.EncodeToString(hash.Sum(nil)), "+", "-")
encryptedCode = strings.ReplaceAll(encryptedCode, "/", "_")
encryptedCode = strings.ReplaceAll(encryptedCode, "=", "")
2022-05-29 11:52:46 +00:00
sessionData, err := memorystore.Provider.GetState(encryptedCode)
if sessionData == "" || err != nil {
2022-05-25 07:00:22 +00:00
log.Debug("Session data is empty")
gc.JSON(http.StatusBadRequest, gin.H{
"error": "invalid_code_verifier",
"error_description": "The code verifier is invalid",
})
return
}
2022-03-04 07:26:11 +00:00
2022-06-11 18:57:21 +00:00
go memorystore.Provider.RemoveState(encryptedCode)
// split session data
// it contains code@sessiontoken
sessionDataSplit := strings.Split(sessionData, "@")
2022-03-04 07:26:11 +00:00
if sessionDataSplit[0] != code {
2022-05-25 07:00:22 +00:00
log.Debug("Invalid code verifier. Unable to split session data")
gc.JSON(http.StatusBadRequest, gin.H{
"error": "invalid_code_verifier",
"error_description": "The code verifier is invalid",
})
return
}
// validate session
claims, err := token.ValidateBrowserSession(gc, sessionDataSplit[1])
if err != nil {
2022-05-23 06:22:51 +00:00
log.Debug("Error validating session: ", err)
gc.JSON(http.StatusUnauthorized, gin.H{
"error": "unauthorized",
"error_description": "Invalid session data",
})
return
}
userID = claims.Subject
roles = claims.Roles
scope = claims.Scope
2022-06-11 18:57:21 +00:00
// rollover the session for security
go memorystore.Provider.DeleteUserSession(userID, claims.Nonce)
} else {
// validate refresh token
if refreshToken == "" {
2022-05-23 06:22:51 +00:00
log.Debug("Refresh token is empty")
gc.JSON(http.StatusBadRequest, gin.H{
"error": "invalid_refresh_token",
"error_description": "The refresh token is invalid",
})
}
claims, err := token.ValidateRefreshToken(gc, refreshToken)
if err != nil {
2022-05-23 06:22:51 +00:00
log.Debug("Error validating refresh token: ", err)
gc.JSON(http.StatusUnauthorized, gin.H{
"error": "unauthorized",
"error_description": err.Error(),
})
}
userID = claims["sub"].(string)
2022-03-08 15:43:23 +00:00
rolesInterface := claims["roles"].([]interface{})
scopeInterface := claims["scope"].([]interface{})
for _, v := range rolesInterface {
roles = append(roles, v.(string))
}
for _, v := range scopeInterface {
scope = append(scope, v.(string))
}
2022-03-08 13:48:33 +00:00
// remove older refresh token and rotate it for security
2022-06-11 18:57:21 +00:00
go memorystore.Provider.DeleteUserSession(userID, claims["nonce"].(string))
2022-03-04 07:26:11 +00:00
}
2022-03-04 07:26:11 +00:00
user, err := db.Provider.GetUserByID(userID)
if err != nil {
2022-05-23 06:22:51 +00:00
log.Debug("Error getting user: ", err)
2022-03-04 07:26:11 +00:00
gc.JSON(http.StatusUnauthorized, gin.H{
"error": "unauthorized",
"error_description": "User not found",
})
return
}
authToken, err := token.CreateAuthToken(gc, user, roles, scope)
2022-03-04 07:26:11 +00:00
if err != nil {
2022-05-23 06:22:51 +00:00
log.Debug("Error creating auth token: ", err)
2022-03-04 07:26:11 +00:00
gc.JSON(http.StatusUnauthorized, gin.H{
"error": "unauthorized",
"error_description": "User not found",
})
return
}
2022-06-11 18:57:21 +00:00
memorystore.Provider.SetUserSession(user.ID, constants.TokenTypeSessionToken+"_"+authToken.FingerPrint, authToken.FingerPrintHash)
memorystore.Provider.SetUserSession(user.ID, constants.TokenTypeAccessToken+"_"+authToken.FingerPrint, authToken.AccessToken.Token)
2022-03-04 07:26:11 +00:00
cookie.SetSession(gc, authToken.FingerPrintHash)
expiresIn := authToken.AccessToken.ExpiresAt - time.Now().Unix()
if expiresIn <= 0 {
expiresIn = 1
}
2022-03-04 07:26:11 +00:00
res := map[string]interface{}{
"access_token": authToken.AccessToken.Token,
"id_token": authToken.IDToken.Token,
"scope": scope,
"roles": roles,
2022-03-04 07:26:11 +00:00
"expires_in": expiresIn,
}
if authToken.RefreshToken != nil {
res["refresh_token"] = authToken.RefreshToken.Token
2022-06-11 18:57:21 +00:00
memorystore.Provider.SetUserSession(user.ID, constants.TokenTypeRefreshToken+"_"+authToken.FingerPrint, authToken.RefreshToken.Token)
2022-03-04 07:26:11 +00:00
}
gc.JSON(http.StatusOK, res)
}
}