1
0
Fork 0
mirror of https://github.com/documize/community.git synced 2025-07-24 15:49:44 +02:00

keycloak jwt processing

This commit is contained in:
Harvey Kandola 2017-03-17 08:46:33 +00:00
parent a585a55033
commit b5f85637a7
9 changed files with 334 additions and 121 deletions

View file

@ -24,7 +24,7 @@ import (
"github.com/documize/community/core/api/request"
"github.com/documize/community/core/api/util"
"github.com/documize/community/core/log"
"github.com/documize/community/core/section/provider"
// "github.com/documize/community/core/section/provider"
"github.com/documize/community/core/utility"
"github.com/documize/community/core/web"
)
@ -45,15 +45,15 @@ func Authenticate(w http.ResponseWriter, r *http.Request) {
// decode what we received
data := strings.Replace(authHeader, "Basic ", "", 1)
decodedBytes, err := utility.DecodeBase64([]byte(data))
decodedBytes, err := utility.DecodeBase64([]byte(data))
if err != nil {
writeBadRequestError(w, method, "Unable to decode authentication token")
return
}
decoded := string(decodedBytes)
// check that we have domain:email:password (but allow for : in password field!)
decoded := string(decodedBytes)
credentials := strings.SplitN(decoded, ":", 3)
if len(credentials) != 3 {
@ -228,65 +228,6 @@ func Authorize(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
}
}
// ValidateAuthToken checks the auth token and returns the corresponding user.
func ValidateAuthToken(w http.ResponseWriter, r *http.Request) {
// TODO should this go after token validation?
if s := r.URL.Query().Get("section"); s != "" {
if err := provider.Callback(s, w, r); err != nil {
log.Error("section validation failure", err)
w.WriteHeader(http.StatusUnauthorized)
}
return
}
method := "ValidateAuthToken"
context, claims, err := decodeJWT(findJWT(r))
if err != nil {
log.Error("token validation", err)
w.WriteHeader(http.StatusUnauthorized)
return
}
request.SetContext(r, context)
p := request.GetPersister(r)
org, err := p.GetOrganization(context.OrgID)
if err != nil {
log.Error("token validation", err)
w.WriteHeader(http.StatusUnauthorized)
return
}
domain := request.GetSubdomainFromHost(r)
if org.Domain != domain || claims["domain"] != domain {
log.Error("token validation", err)
w.WriteHeader(http.StatusUnauthorized)
return
}
user, err := getSecuredUser(p, context.OrgID, context.UserID)
if err != nil {
log.Error("get user error for token validation", err)
w.WriteHeader(http.StatusUnauthorized)
return
}
json, err := json.Marshal(user)
if err != nil {
writeJSONMarshalError(w, method, "user", err)
return
}
writeSuccessBytes(w, json)
}
// Certain assets/URL do not require authentication.
// Just stops the log files being clogged up with failed auth errors.
func preAuthorizeStaticAssets(r *http.Request) bool {
@ -303,3 +244,62 @@ func preAuthorizeStaticAssets(r *http.Request) bool {
return false
}
// // ValidateAuthToken checks the auth token and returns the corresponding user.
// func ValidateAuthToken(w http.ResponseWriter, r *http.Request) {
// // TODO should this go after token validation?
// if s := r.URL.Query().Get("section"); s != "" {
// if err := provider.Callback(s, w, r); err != nil {
// log.Error("section validation failure", err)
// w.WriteHeader(http.StatusUnauthorized)
// }
// return
// }
// method := "ValidateAuthToken"
// context, claims, err := decodeJWT(findJWT(r))
// if err != nil {
// log.Error("token validation", err)
// w.WriteHeader(http.StatusUnauthorized)
// return
// }
// request.SetContext(r, context)
// p := request.GetPersister(r)
// org, err := p.GetOrganization(context.OrgID)
// if err != nil {
// log.Error("token validation", err)
// w.WriteHeader(http.StatusUnauthorized)
// return
// }
// domain := request.GetSubdomainFromHost(r)
// if org.Domain != domain || claims["domain"] != domain {
// log.Error("token validation", err)
// w.WriteHeader(http.StatusUnauthorized)
// return
// }
// user, err := getSecuredUser(p, context.OrgID, context.UserID)
// if err != nil {
// log.Error("get user error for token validation", err)
// w.WriteHeader(http.StatusUnauthorized)
// return
// }
// json, err := json.Marshal(user)
// if err != nil {
// writeJSONMarshalError(w, method, "user", err)
// return
// }
// writeSuccessBytes(w, json)
// }

View file

@ -13,6 +13,7 @@ package endpoint
import (
"crypto/rand"
"crypto/rsa"
"fmt"
"net/http"
"strings"
@ -151,3 +152,73 @@ func decodeJWT(tokenString string) (c request.Context, claims map[string]interfa
return c, token.Claims, nil
}
// We take in Keycloak token string and decode it.
func decodeKeycloakJWT(t, pk string) (err error) {
// method := "decodeKeycloakJWT"
log.Info(t)
log.Info(pk)
var rsaPSSKey *rsa.PublicKey
if rsaPSSKey, err = jwt.ParseRSAPublicKeyFromPEM([]byte(pk)); err != nil {
log.Error("Unable to parse RSA public key", err)
return
}
parts := strings.Split(t, ".")
m := jwt.GetSigningMethod("RSA256")
err = m.Verify(strings.Join(parts[0:2], "."), parts[2], rsaPSSKey)
if err != nil {
log.Error("Error while verifying key", err)
return
}
// token, err := jwt.Parse(t, func(token *jwt.Token) (interface{}, error) {
// p, pe := jwt.ParseRSAPublicKeyFromPEM([]byte(pk))
// if pe != nil {
// log.Error("have jwt err", pe)
// }
// return p, pe
// // return []byte(jwtKey), nil
// })
// if err != nil {
// err = fmt.Errorf("bad authorization token")
// return
// }
// if !token.Valid {
// if ve, ok := err.(*jwt.ValidationError); ok {
// if ve.Errors&jwt.ValidationErrorMalformed != 0 {
// log.Error("invalid token", err)
// err = fmt.Errorf("bad token")
// return
// } else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
// log.Error("expired token", err)
// err = fmt.Errorf("expired token")
// return
// } else {
// log.Error("invalid token", err)
// err = fmt.Errorf("bad token")
// return
// }
// } else {
// log.Error("invalid token", err)
// err = fmt.Errorf("bad token")
// return
// }
// }
// email := token.Claims["user"].(string)
// exp := token.Claims["exp"].(string)
// sub := token.Claims["sub"].(string)
// if len(email) == 0 || len(exp) == 0 || len(sub) == 0 {
// err = fmt.Errorf("%s : unable parse Keycloak token data", method)
// return
// }
return nil
}

View file

@ -0,0 +1,169 @@
// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com
package endpoint
import (
"database/sql"
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"github.com/documize/community/core/api/endpoint/models"
"github.com/documize/community/core/api/request"
"github.com/documize/community/core/log"
// "github.com/documize/community/core/section/provider"
"github.com/documize/community/core/utility"
)
// AuthenticateKeycloak checks Keycloak authentication credentials.
//
// TODO:
// 1. validate keycloak token
// 2. implement new user additions: user & account with RefID
//
func AuthenticateKeycloak(w http.ResponseWriter, r *http.Request) {
method := "AuthenticateKeycloak"
p := request.GetPersister(r)
defer utility.Close(r.Body)
body, err := ioutil.ReadAll(r.Body)
if err != nil {
writeBadRequestError(w, method, "Bad payload")
return
}
a := keycloakAuthRequest{}
err = json.Unmarshal(body, &a)
if err != nil {
writePayloadError(w, method, err)
return
}
// Clean data.
a.Domain = strings.TrimSpace(strings.ToLower(a.Domain))
a.Domain = request.CheckDomain(a.Domain) // TODO optimize by removing this once js allows empty domains
a.Email = strings.TrimSpace(strings.ToLower(a.Email))
// Check for required fields.
if len(a.Email) == 0 {
writeUnauthorizedError(w)
return
}
// Validate Keycloak credentials
pks := "LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS1NSUlCSWpBTkJna3Foa2lHOXcwQkFRRUZBQU9DQVE4QU1JSUJDZ0tDQVFFQTAwRzI3KzZYNzJFWllIY3NyY1pHekYwZzFsL1gzeVdLS20vZ3NnMCtjMWdXQ2R4ZmI4QmtkbFdCcXhXZVRoSEZCVUVETnorakFyTjBlL0dFMXorMmxnQzJlMkQwemFlcjdlSHZ6bzlBK1hkb0h4KzRNS3RUbkxZZS9aYUFpc3ExSHVURkRKZElKZFRJVUpTWUFXZlNrSmJtdGhIOUVPMmF3SVhEQzlMMWpDa2IwNHZmZ0xERFA3bVo1YzV6NHJPcGluTU45V3RkSm8xeC90VG0xVDlwRHQ3NDRIUHBoMENSbW5OcTRCdWo2SGpaQ3hCcFF1aUp5am0yT0lIdm4vWUJxVUlSUitMcFlJREV1d2FQRU04QkF1eWYvU3BBTGNNaG9oZndzR255QnFMV3QwVFBua3plZjl6ZWN3WEdsQXlYbUZCWlVkR1k3Z0hOdDRpVmdvMXp5d0lEQVFBQi0tLS0tRU5EIFBVQkxJQyBLRVktLS0tLQ=="
pkb, err := utility.DecodeBase64([]byte(pks))
if err != nil {
log.Error("", err)
writeBadRequestError(w, method, "Unable to decode authentication token")
return
}
pk := string(pkb)
pk = `
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA00G27+6X72EZYHcsrcZGzF0g1l/X3yWKKm/gsg0+c1gWCdxfb8BkdlWBqxWeThHFBUEDNz+jArN0e/GE1z+2lgC2e2D0zaer7eHvzo9A+XdoHx+4MKtTnLYe/ZaAisq1HuTFDJdIJdTIUJSYAWfSkJbmthH9EO2awIXDC9L1jCkb04vfgLDDP7mZ5c5z4rOpinMN9WtdJo1x/tTm1T9pDt744HPph0CRmnNq4Buj6HjZCxBpQuiJyjm2OIHvn/YBqUIRR+LpYIDEuwaPEM8BAuyf/SpALcMhohfwsGnyBqLWt0TPnkzef9zecwXGlAyXmFBZUdGY7gHNt4iVgo1zywIDAQAB
-----END PUBLIC KEY-----
`
err = decodeKeycloakJWT(a.Token, pk)
if err != nil {
writeServerError(w, method, err)
return
}
log.Info("keycloak logon attempt " + a.Email + " @ " + a.Domain)
user, err := p.GetUserByDomain(a.Domain, a.Email)
if err != nil && err != sql.ErrNoRows {
writeServerError(w, method, err)
return
}
// Create user account if not found
if err == sql.ErrNoRows {
log.Info("keycloak add user " + a.Email + " @ " + a.Domain)
p.Context.Transaction, err = request.Db.Beginx()
if err != nil {
writeTransactionError(w, method, err)
return
}
}
// Password correct and active user
if a.Email != strings.TrimSpace(strings.ToLower(user.Email)) {
writeUnauthorizedError(w)
return
}
org, err := p.GetOrganizationByDomain(a.Domain)
if err != nil {
writeUnauthorizedError(w)
return
}
// Attach user accounts and work out permissions.
attachUserAccounts(p, org.RefID, &user)
// No accounts signals data integrity problem
// so we reject login request.
if len(user.Accounts) == 0 {
writeUnauthorizedError(w)
return
}
// Abort login request if account is disabled.
for _, ac := range user.Accounts {
if ac.OrgID == org.RefID {
if ac.Active == false {
writeUnauthorizedError(w)
return
}
break
}
}
// Generate JWT token
authModel := models.AuthenticationModel{}
authModel.Token = generateJWT(user.RefID, org.RefID, a.Domain)
authModel.User = user
json, err := json.Marshal(authModel)
if err != nil {
writeJSONMarshalError(w, method, "user", err)
return
}
writeSuccessBytes(w, json)
}
// Data received via Keycloak client library
type keycloakAuthRequest struct {
Domain string `json:"domain"`
Token string `json:"token"`
RemoteID string `json:"remoteId"`
Email string `json:"email"`
Username string `json:"username"`
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
Enabled bool `json:"enabled"`
}
// Keycloak server configuration
type keycloakConfig struct {
URL string `json:"url"`
Realm string `json:"realm"`
ClientID string `json:"clientId"`
PublicKey string `json:"publicKey"`
}

View file

@ -132,8 +132,9 @@ func init() {
//**************************************************
log.IfErr(Add(RoutePrefixPublic, "meta", []string{"GET", "OPTIONS"}, nil, GetMeta))
log.IfErr(Add(RoutePrefixPublic, "authenticate/keycloak", []string{"POST", "OPTIONS"}, nil, AuthenticateKeycloak))
log.IfErr(Add(RoutePrefixPublic, "authenticate", []string{"POST", "OPTIONS"}, nil, Authenticate))
log.IfErr(Add(RoutePrefixPublic, "validate", []string{"GET", "OPTIONS"}, nil, ValidateAuthToken))
// log.IfErr(Add(RoutePrefixPublic, "validate", []string{"GET", "OPTIONS"}, nil, ValidateAuthToken))
log.IfErr(Add(RoutePrefixPublic, "forgot", []string{"POST", "OPTIONS"}, nil, ForgotUserPassword))
log.IfErr(Add(RoutePrefixPublic, "reset/{token}", []string{"POST", "OPTIONS"}, nil, ResetUserPassword))
log.IfErr(Add(RoutePrefixPublic, "share/{folderID}", []string{"POST", "OPTIONS"}, nil, AcceptSharedFolder))