2016-07-26 01:30:28 +05:30
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2016-12-23 06:11:30 +05:30
|
|
|
"errors"
|
2016-07-26 01:30:28 +05:30
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"path"
|
2016-08-26 04:48:09 +05:30
|
|
|
"sort"
|
2016-07-26 01:30:28 +05:30
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/gorilla/mux"
|
|
|
|
jose "gopkg.in/square/go-jose.v2"
|
|
|
|
|
2018-09-03 12:14:44 +05:30
|
|
|
"github.com/dexidp/dex/connector"
|
|
|
|
"github.com/dexidp/dex/server/internal"
|
|
|
|
"github.com/dexidp/dex/storage"
|
2016-07-26 01:30:28 +05:30
|
|
|
)
|
|
|
|
|
2016-10-05 05:15:52 +05:30
|
|
|
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
|
|
|
start := s.now()
|
|
|
|
err := func() error {
|
|
|
|
// Instead of trying to introspect health, just try to use the underlying storage.
|
|
|
|
a := storage.AuthRequest{
|
|
|
|
ID: storage.NewID(),
|
|
|
|
ClientID: storage.NewID(),
|
|
|
|
|
|
|
|
// Set a short expiry so if the delete fails this will be cleaned up quickly by garbage collection.
|
|
|
|
Expiry: s.now().Add(time.Minute),
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := s.storage.CreateAuthRequest(a); err != nil {
|
|
|
|
return fmt.Errorf("create auth request: %v", err)
|
|
|
|
}
|
|
|
|
if err := s.storage.DeleteAuthRequest(a.ID); err != nil {
|
|
|
|
return fmt.Errorf("delete auth request: %v", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}()
|
|
|
|
|
|
|
|
t := s.now().Sub(start)
|
|
|
|
if err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("Storage health check failed: %v", err)
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Health check failed.")
|
2016-10-05 05:15:52 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
fmt.Fprintf(w, "Health check passed in %s", t)
|
|
|
|
}
|
|
|
|
|
2016-07-26 01:30:28 +05:30
|
|
|
func (s *Server) handlePublicKeys(w http.ResponseWriter, r *http.Request) {
|
|
|
|
// TODO(ericchiang): Cache this.
|
|
|
|
keys, err := s.storage.GetKeys()
|
|
|
|
if err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("failed to get keys: %v", err)
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Internal server error.")
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if keys.SigningKeyPub == nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("No public keys found.")
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Internal server error.")
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
jwks := jose.JSONWebKeySet{
|
|
|
|
Keys: make([]jose.JSONWebKey, len(keys.VerificationKeys)+1),
|
|
|
|
}
|
|
|
|
jwks.Keys[0] = *keys.SigningKeyPub
|
|
|
|
for i, verificationKey := range keys.VerificationKeys {
|
|
|
|
jwks.Keys[i+1] = *verificationKey.PublicKey
|
|
|
|
}
|
|
|
|
|
|
|
|
data, err := json.MarshalIndent(jwks, "", " ")
|
|
|
|
if err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("failed to marshal discovery data: %v", err)
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Internal server error.")
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
maxAge := keys.NextRotation.Sub(s.now())
|
|
|
|
if maxAge < (time.Minute * 2) {
|
|
|
|
maxAge = time.Minute * 2
|
|
|
|
}
|
|
|
|
|
2016-10-27 03:28:18 +05:30
|
|
|
w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, must-revalidate", int(maxAge.Seconds())))
|
2016-07-26 01:30:28 +05:30
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
|
|
|
|
w.Write(data)
|
|
|
|
}
|
|
|
|
|
|
|
|
type discovery struct {
|
|
|
|
Issuer string `json:"issuer"`
|
|
|
|
Auth string `json:"authorization_endpoint"`
|
|
|
|
Token string `json:"token_endpoint"`
|
|
|
|
Keys string `json:"jwks_uri"`
|
|
|
|
ResponseTypes []string `json:"response_types_supported"`
|
|
|
|
Subjects []string `json:"subject_types_supported"`
|
|
|
|
IDTokenAlgs []string `json:"id_token_signing_alg_values_supported"`
|
|
|
|
Scopes []string `json:"scopes_supported"`
|
|
|
|
AuthMethods []string `json:"token_endpoint_auth_methods_supported"`
|
|
|
|
Claims []string `json:"claims_supported"`
|
|
|
|
}
|
|
|
|
|
2017-01-14 14:48:48 +05:30
|
|
|
func (s *Server) discoveryHandler() (http.HandlerFunc, error) {
|
2016-07-26 01:30:28 +05:30
|
|
|
d := discovery{
|
2016-08-26 04:48:09 +05:30
|
|
|
Issuer: s.issuerURL.String(),
|
|
|
|
Auth: s.absURL("/auth"),
|
|
|
|
Token: s.absURL("/token"),
|
|
|
|
Keys: s.absURL("/keys"),
|
|
|
|
Subjects: []string{"public"},
|
|
|
|
IDTokenAlgs: []string{string(jose.RS256)},
|
2016-11-19 02:43:32 +05:30
|
|
|
Scopes: []string{"openid", "email", "groups", "profile", "offline_access"},
|
2016-08-26 04:48:09 +05:30
|
|
|
AuthMethods: []string{"client_secret_basic"},
|
2016-07-26 01:30:28 +05:30
|
|
|
Claims: []string{
|
2016-08-09 07:40:32 +05:30
|
|
|
"aud", "email", "email_verified", "exp",
|
2016-07-26 01:30:28 +05:30
|
|
|
"iat", "iss", "locale", "name", "sub",
|
|
|
|
},
|
|
|
|
}
|
2016-08-26 04:48:09 +05:30
|
|
|
|
|
|
|
for responseType := range s.supportedResponseTypes {
|
|
|
|
d.ResponseTypes = append(d.ResponseTypes, responseType)
|
|
|
|
}
|
|
|
|
sort.Strings(d.ResponseTypes)
|
|
|
|
|
2016-07-26 01:30:28 +05:30
|
|
|
data, err := json.MarshalIndent(d, "", " ")
|
|
|
|
if err != nil {
|
2016-08-26 04:48:09 +05:30
|
|
|
return nil, fmt.Errorf("failed to marshal discovery data: %v", err)
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
2016-08-26 04:48:09 +05:30
|
|
|
|
2017-01-14 14:48:48 +05:30
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2016-08-26 04:48:09 +05:30
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
|
|
|
|
w.Write(data)
|
2017-01-14 14:48:48 +05:30
|
|
|
}), nil
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
// handleAuthorization handles the OAuth2 auth endpoint.
|
|
|
|
func (s *Server) handleAuthorization(w http.ResponseWriter, r *http.Request) {
|
2017-01-10 00:16:16 +05:30
|
|
|
authReq, err := s.parseAuthorizationRequest(r)
|
2016-07-26 01:30:28 +05:30
|
|
|
if err != nil {
|
2016-12-15 03:47:59 +05:30
|
|
|
s.logger.Errorf("Failed to parse authorization request: %v", err)
|
2017-01-10 00:16:16 +05:30
|
|
|
if handler, ok := err.Handle(); ok {
|
|
|
|
// client_id and redirect_uri checked out and we can redirect back to
|
|
|
|
// the client with the error.
|
|
|
|
handler.ServeHTTP(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Otherwise render the error to the user.
|
|
|
|
//
|
|
|
|
// TODO(ericchiang): Should we just always render the error?
|
|
|
|
s.renderError(w, err.Status(), err.Error())
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
2017-01-10 00:16:16 +05:30
|
|
|
|
2017-02-02 23:59:57 +05:30
|
|
|
// TODO(ericchiang): Create this authorization request later in the login flow
|
|
|
|
// so users don't hit "not found" database errors if they wait at the login
|
|
|
|
// screen too long.
|
|
|
|
//
|
2018-09-03 12:14:44 +05:30
|
|
|
// See: https://github.com/dexidp/dex/issues/646
|
2018-12-13 16:10:58 +05:30
|
|
|
authReq.Expiry = s.now().Add(s.authRequestsValidFor)
|
2016-07-26 01:30:28 +05:30
|
|
|
if err := s.storage.CreateAuthRequest(authReq); err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("Failed to create authorization request: %v", err)
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Failed to connect to the database.")
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
2017-02-02 23:59:57 +05:30
|
|
|
|
2017-04-18 04:11:41 +05:30
|
|
|
connectors, e := s.storage.ListConnectors()
|
|
|
|
if e != nil {
|
|
|
|
s.logger.Errorf("Failed to get list of connectors: %v", err)
|
|
|
|
s.renderError(w, http.StatusInternalServerError, "Failed to retrieve connector list.")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(connectors) == 1 {
|
|
|
|
for _, c := range connectors {
|
2017-02-02 23:59:57 +05:30
|
|
|
// TODO(ericchiang): Make this pass on r.URL.RawQuery and let something latter
|
|
|
|
// on create the auth request.
|
2017-04-18 04:11:41 +05:30
|
|
|
http.Redirect(w, r, s.absPath("/auth", c.ID)+"?req="+authReq.ID, http.StatusFound)
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-18 04:11:41 +05:30
|
|
|
connectorInfos := make([]connectorInfo, len(connectors))
|
2016-07-26 01:30:28 +05:30
|
|
|
i := 0
|
2017-04-18 04:11:41 +05:30
|
|
|
for _, conn := range connectors {
|
2016-07-26 01:30:28 +05:30
|
|
|
connectorInfos[i] = connectorInfo{
|
2017-04-18 04:11:41 +05:30
|
|
|
ID: conn.ID,
|
|
|
|
Name: conn.Name,
|
2017-02-02 23:59:57 +05:30
|
|
|
// TODO(ericchiang): Make this pass on r.URL.RawQuery and let something latter
|
|
|
|
// on create the auth request.
|
2017-04-18 04:11:41 +05:30
|
|
|
URL: s.absPath("/auth", conn.ID) + "?req=" + authReq.ID,
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
i++
|
|
|
|
}
|
|
|
|
|
2017-02-02 23:59:57 +05:30
|
|
|
if err := s.templates.login(w, connectorInfos); err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("Server template error: %v", err)
|
|
|
|
}
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) handleConnectorLogin(w http.ResponseWriter, r *http.Request) {
|
|
|
|
connID := mux.Vars(r)["connector"]
|
2017-04-18 04:11:41 +05:30
|
|
|
conn, err := s.getConnector(connID)
|
|
|
|
if err != nil {
|
|
|
|
s.logger.Errorf("Failed to create authorization request: %v", err)
|
|
|
|
s.renderError(w, http.StatusBadRequest, "Requested resource does not exist")
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-10-27 22:50:30 +05:30
|
|
|
authReqID := r.FormValue("req")
|
2016-10-27 22:38:08 +05:30
|
|
|
|
2016-11-19 03:10:41 +05:30
|
|
|
authReq, err := s.storage.GetAuthRequest(authReqID)
|
|
|
|
if err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("Failed to get auth request: %v", err)
|
2017-02-02 23:59:57 +05:30
|
|
|
if err == storage.ErrNotFound {
|
|
|
|
s.renderError(w, http.StatusBadRequest, "Login session expired.")
|
|
|
|
} else {
|
|
|
|
s.renderError(w, http.StatusInternalServerError, "Database error.")
|
|
|
|
}
|
2016-11-19 03:10:41 +05:30
|
|
|
return
|
|
|
|
}
|
2017-12-08 16:19:47 +05:30
|
|
|
|
|
|
|
// Set the connector being used for the login.
|
2017-12-11 12:55:25 +05:30
|
|
|
if authReq.ConnectorID != connID {
|
|
|
|
updater := func(a storage.AuthRequest) (storage.AuthRequest, error) {
|
|
|
|
a.ConnectorID = connID
|
|
|
|
return a, nil
|
|
|
|
}
|
|
|
|
if err := s.storage.UpdateAuthRequest(authReqID, updater); err != nil {
|
|
|
|
s.logger.Errorf("Failed to set connector ID on auth request: %v", err)
|
|
|
|
s.renderError(w, http.StatusInternalServerError, "Database error.")
|
|
|
|
return
|
|
|
|
}
|
2017-12-08 16:19:47 +05:30
|
|
|
}
|
|
|
|
|
2016-11-19 03:10:41 +05:30
|
|
|
scopes := parseScopes(authReq.Scopes)
|
2017-11-09 20:50:20 +05:30
|
|
|
showBacklink := len(s.connectors) > 1
|
2016-07-26 01:30:28 +05:30
|
|
|
|
|
|
|
switch r.Method {
|
2018-12-27 13:56:39 +05:30
|
|
|
case http.MethodGet:
|
2016-07-26 01:30:28 +05:30
|
|
|
switch conn := conn.Connector.(type) {
|
|
|
|
case connector.CallbackConnector:
|
2016-10-27 22:50:30 +05:30
|
|
|
// Use the auth request ID as the "state" token.
|
|
|
|
//
|
|
|
|
// TODO(ericchiang): Is this appropriate or should we also be using a nonce?
|
2016-11-19 03:10:41 +05:30
|
|
|
callbackURL, err := conn.LoginURL(scopes, s.absURL("/callback"), authReqID)
|
2016-07-26 01:30:28 +05:30
|
|
|
if err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("Connector %q returned error when creating callback: %v", connID, err)
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Login error.")
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
http.Redirect(w, r, callbackURL, http.StatusFound)
|
|
|
|
case connector.PasswordConnector:
|
2017-11-09 20:50:20 +05:30
|
|
|
if err := s.templates.password(w, r.URL.String(), "", usernamePrompt(conn), false, showBacklink); err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("Server template error: %v", err)
|
|
|
|
}
|
2016-12-21 06:54:32 +05:30
|
|
|
case connector.SAMLConnector:
|
2017-03-22 01:46:42 +05:30
|
|
|
action, value, err := conn.POSTData(scopes, authReqID)
|
2016-12-21 06:54:32 +05:30
|
|
|
if err != nil {
|
|
|
|
s.logger.Errorf("Creating SAML data: %v", err)
|
|
|
|
s.renderError(w, http.StatusInternalServerError, "Connector Login Error")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO(ericchiang): Don't inline this.
|
|
|
|
fmt.Fprintf(w, `<!DOCTYPE html>
|
|
|
|
<html lang="en">
|
|
|
|
<head>
|
|
|
|
<meta http-equiv="content-type" content="text/html; charset=utf-8">
|
|
|
|
<title>SAML login</title>
|
|
|
|
</head>
|
|
|
|
<body>
|
|
|
|
<form method="post" action="%s" >
|
|
|
|
<input type="hidden" name="SAMLRequest" value="%s" />
|
|
|
|
<input type="hidden" name="RelayState" value="%s" />
|
|
|
|
</form>
|
|
|
|
<script>
|
|
|
|
document.forms[0].submit();
|
|
|
|
</script>
|
|
|
|
</body>
|
|
|
|
</html>`, action, value, authReqID)
|
2016-07-26 01:30:28 +05:30
|
|
|
default:
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusBadRequest, "Requested resource does not exist.")
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
2018-12-27 13:56:39 +05:30
|
|
|
case http.MethodPost:
|
2016-07-26 01:30:28 +05:30
|
|
|
passwordConnector, ok := conn.Connector.(connector.PasswordConnector)
|
|
|
|
if !ok {
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusBadRequest, "Requested resource does not exist.")
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-08-26 01:40:19 +05:30
|
|
|
username := r.FormValue("login")
|
2016-07-26 01:30:28 +05:30
|
|
|
password := r.FormValue("password")
|
|
|
|
|
2016-11-19 03:10:41 +05:30
|
|
|
identity, ok, err := passwordConnector.Login(r.Context(), scopes, username, password)
|
2016-07-26 01:30:28 +05:30
|
|
|
if err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("Failed to login user: %v", err)
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Login error.")
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
if !ok {
|
2017-11-09 20:50:20 +05:30
|
|
|
if err := s.templates.password(w, r.URL.String(), username, usernamePrompt(passwordConnector), true, showBacklink); err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("Server template error: %v", err)
|
|
|
|
}
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
2016-10-27 22:38:08 +05:30
|
|
|
redirectURL, err := s.finalizeLogin(identity, authReq, conn.Connector)
|
2016-07-26 01:30:28 +05:30
|
|
|
if err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("Failed to finalize login: %v", err)
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Login error.")
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-08-03 09:44:24 +05:30
|
|
|
http.Redirect(w, r, redirectURL, http.StatusSeeOther)
|
2016-07-26 01:30:28 +05:30
|
|
|
default:
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusBadRequest, "Unsupported request method.")
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) handleConnectorCallback(w http.ResponseWriter, r *http.Request) {
|
2016-12-21 06:54:32 +05:30
|
|
|
var authID string
|
|
|
|
switch r.Method {
|
2018-12-27 13:56:39 +05:30
|
|
|
case http.MethodGet: // OAuth2 callback
|
2016-12-21 06:54:32 +05:30
|
|
|
if authID = r.URL.Query().Get("state"); authID == "" {
|
|
|
|
s.renderError(w, http.StatusBadRequest, "User session error.")
|
|
|
|
return
|
|
|
|
}
|
2018-12-27 13:56:39 +05:30
|
|
|
case http.MethodPost: // SAML POST binding
|
2016-12-21 06:54:32 +05:30
|
|
|
if authID = r.PostFormValue("RelayState"); authID == "" {
|
|
|
|
s.renderError(w, http.StatusBadRequest, "User session error.")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
s.renderError(w, http.StatusBadRequest, "Method not supported")
|
2016-10-27 22:38:08 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-12-21 06:54:32 +05:30
|
|
|
authReq, err := s.storage.GetAuthRequest(authID)
|
2016-10-27 22:38:08 +05:30
|
|
|
if err != nil {
|
|
|
|
if err == storage.ErrNotFound {
|
2016-12-15 03:47:59 +05:30
|
|
|
s.logger.Errorf("Invalid 'state' parameter provided: %v", err)
|
|
|
|
s.renderError(w, http.StatusInternalServerError, "Requested resource does not exist.")
|
2016-10-27 22:38:08 +05:30
|
|
|
return
|
|
|
|
}
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("Failed to get auth request: %v", err)
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Database error.")
|
2016-10-27 22:38:08 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-10-21 20:24:54 +05:30
|
|
|
if connID := mux.Vars(r)["connector"]; connID != "" && connID != authReq.ConnectorID {
|
|
|
|
s.logger.Errorf("Connector mismatch: authentication started with id %q, but callback for id %q was triggered", authReq.ConnectorID, connID)
|
|
|
|
s.renderError(w, http.StatusInternalServerError, "Requested resource does not exist.")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-04-18 04:11:41 +05:30
|
|
|
conn, err := s.getConnector(authReq.ConnectorID)
|
|
|
|
if err != nil {
|
|
|
|
s.logger.Errorf("Failed to get connector with id %q : %v", authReq.ConnectorID, err)
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Requested resource does not exist.")
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
2016-12-21 06:54:32 +05:30
|
|
|
|
|
|
|
var identity connector.Identity
|
|
|
|
switch conn := conn.Connector.(type) {
|
|
|
|
case connector.CallbackConnector:
|
2018-12-27 13:56:39 +05:30
|
|
|
if r.Method != http.MethodGet {
|
2016-12-21 06:54:32 +05:30
|
|
|
s.logger.Errorf("SAML request mapped to OAuth2 connector")
|
|
|
|
s.renderError(w, http.StatusBadRequest, "Invalid request")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
identity, err = conn.HandleCallback(parseScopes(authReq.Scopes), r)
|
|
|
|
case connector.SAMLConnector:
|
2018-12-27 13:56:39 +05:30
|
|
|
if r.Method != http.MethodPost {
|
2016-12-21 06:54:32 +05:30
|
|
|
s.logger.Errorf("OAuth2 request mapped to SAML connector")
|
|
|
|
s.renderError(w, http.StatusBadRequest, "Invalid request")
|
|
|
|
return
|
|
|
|
}
|
2017-03-22 01:46:42 +05:30
|
|
|
identity, err = conn.HandlePOST(parseScopes(authReq.Scopes), r.PostFormValue("SAMLResponse"), authReq.ID)
|
2016-12-21 06:54:32 +05:30
|
|
|
default:
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Requested resource does not exist.")
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("Failed to authenticate: %v", err)
|
2018-11-14 05:14:28 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to authenticate: %v", err))
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
2016-08-03 09:44:24 +05:30
|
|
|
|
2016-10-27 22:38:08 +05:30
|
|
|
redirectURL, err := s.finalizeLogin(identity, authReq, conn.Connector)
|
2016-07-26 01:30:28 +05:30
|
|
|
if err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("Failed to finalize login: %v", err)
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Login error.")
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
2016-08-03 09:44:24 +05:30
|
|
|
|
|
|
|
http.Redirect(w, r, redirectURL, http.StatusSeeOther)
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
|
2017-08-11 22:47:30 +05:30
|
|
|
// finalizeLogin associates the user's identity with the current AuthRequest, then returns
|
|
|
|
// the approval page's path.
|
2016-10-27 22:38:08 +05:30
|
|
|
func (s *Server) finalizeLogin(identity connector.Identity, authReq storage.AuthRequest, conn connector.Connector) (string, error) {
|
2016-08-03 10:27:36 +05:30
|
|
|
claims := storage.Claims{
|
2016-08-03 09:44:24 +05:30
|
|
|
UserID: identity.UserID,
|
|
|
|
Username: identity.Username,
|
|
|
|
Email: identity.Email,
|
|
|
|
EmailVerified: identity.EmailVerified,
|
2016-11-19 03:10:41 +05:30
|
|
|
Groups: identity.Groups,
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
2016-08-03 09:44:24 +05:30
|
|
|
|
|
|
|
updater := func(a storage.AuthRequest) (storage.AuthRequest, error) {
|
2016-09-15 05:08:12 +05:30
|
|
|
a.LoggedIn = true
|
|
|
|
a.Claims = claims
|
2016-08-03 09:44:24 +05:30
|
|
|
a.ConnectorData = identity.ConnectorData
|
|
|
|
return a, nil
|
|
|
|
}
|
2016-10-27 22:38:08 +05:30
|
|
|
if err := s.storage.UpdateAuthRequest(authReq.ID, updater); err != nil {
|
2016-08-03 09:44:24 +05:30
|
|
|
return "", fmt.Errorf("failed to update auth request: %v", err)
|
|
|
|
}
|
2017-08-11 22:47:30 +05:30
|
|
|
|
|
|
|
email := claims.Email
|
|
|
|
if !claims.EmailVerified {
|
|
|
|
email = email + " (unverified)"
|
|
|
|
}
|
|
|
|
|
|
|
|
s.logger.Infof("login successful: connector %q, username=%q, email=%q, groups=%q",
|
|
|
|
authReq.ConnectorID, claims.Username, email, claims.Groups)
|
|
|
|
|
2016-10-27 22:50:30 +05:30
|
|
|
return path.Join(s.issuerURL.Path, "/approval") + "?req=" + authReq.ID, nil
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) handleApproval(w http.ResponseWriter, r *http.Request) {
|
2016-10-27 22:50:30 +05:30
|
|
|
authReq, err := s.storage.GetAuthRequest(r.FormValue("req"))
|
2016-07-26 01:30:28 +05:30
|
|
|
if err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("Failed to get auth request: %v", err)
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Database error.")
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
2016-09-15 05:08:12 +05:30
|
|
|
if !authReq.LoggedIn {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("Auth request does not have an identity for approval")
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Login process not yet finalized.")
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
switch r.Method {
|
2018-12-27 13:56:39 +05:30
|
|
|
case http.MethodGet:
|
2016-07-26 01:30:28 +05:30
|
|
|
if s.skipApproval {
|
2016-08-03 10:27:36 +05:30
|
|
|
s.sendCodeResponse(w, r, authReq)
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
client, err := s.storage.GetClient(authReq.ClientID)
|
|
|
|
if err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("Failed to get client %q: %v", authReq.ClientID, err)
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Failed to retrieve client.")
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
2016-12-13 04:24:01 +05:30
|
|
|
if err := s.templates.approval(w, authReq.ID, authReq.Claims.Username, client.Name, authReq.Scopes); err != nil {
|
|
|
|
s.logger.Errorf("Server template error: %v", err)
|
|
|
|
}
|
2018-12-27 13:56:39 +05:30
|
|
|
case http.MethodPost:
|
2016-07-26 01:30:28 +05:30
|
|
|
if r.FormValue("approval") != "approve" {
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Approval rejected.")
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
2016-08-03 10:27:36 +05:30
|
|
|
s.sendCodeResponse(w, r, authReq)
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-08-03 10:27:36 +05:30
|
|
|
func (s *Server) sendCodeResponse(w http.ResponseWriter, r *http.Request, authReq storage.AuthRequest) {
|
2016-10-13 07:20:48 +05:30
|
|
|
if s.now().After(authReq.Expiry) {
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusBadRequest, "User session has expired.")
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := s.storage.DeleteAuthRequest(authReq.ID); err != nil {
|
|
|
|
if err != storage.ErrNotFound {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("Failed to delete authorization request: %v", err)
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Internal server error.")
|
2016-07-26 01:30:28 +05:30
|
|
|
} else {
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusBadRequest, "User session error.")
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
u, err := url.Parse(authReq.RedirectURI)
|
|
|
|
if err != nil {
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Invalid redirect URI.")
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
2017-01-10 00:16:16 +05:30
|
|
|
|
|
|
|
var (
|
|
|
|
// Was the initial request using the implicit or hybrid flow instead of
|
|
|
|
// the "normal" code flow?
|
|
|
|
implicitOrHybrid = false
|
|
|
|
|
|
|
|
// Only present in hybrid or code flow. code.ID == "" if this is not set.
|
|
|
|
code storage.AuthCode
|
|
|
|
|
|
|
|
// ID token returned immediately if the response_type includes "id_token".
|
|
|
|
// Only valid for implicit and hybrid flows.
|
|
|
|
idToken string
|
|
|
|
idTokenExpiry time.Time
|
2017-01-11 07:21:12 +05:30
|
|
|
|
|
|
|
accessToken = storage.NewID()
|
2017-01-10 00:16:16 +05:30
|
|
|
)
|
2016-08-20 05:54:49 +05:30
|
|
|
|
|
|
|
for _, responseType := range authReq.ResponseTypes {
|
|
|
|
switch responseType {
|
|
|
|
case responseTypeCode:
|
2017-01-10 00:16:16 +05:30
|
|
|
code = storage.AuthCode{
|
2016-11-19 03:10:41 +05:30
|
|
|
ID: storage.NewID(),
|
|
|
|
ClientID: authReq.ClientID,
|
|
|
|
ConnectorID: authReq.ConnectorID,
|
|
|
|
Nonce: authReq.Nonce,
|
|
|
|
Scopes: authReq.Scopes,
|
|
|
|
Claims: authReq.Claims,
|
|
|
|
Expiry: s.now().Add(time.Minute * 30),
|
|
|
|
RedirectURI: authReq.RedirectURI,
|
|
|
|
ConnectorData: authReq.ConnectorData,
|
2016-08-20 05:54:49 +05:30
|
|
|
}
|
|
|
|
if err := s.storage.CreateAuthCode(code); err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("Failed to create auth code: %v", err)
|
2016-12-15 03:47:59 +05:30
|
|
|
s.renderError(w, http.StatusInternalServerError, "Internal server error.")
|
2016-08-20 05:54:49 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-01-10 00:16:16 +05:30
|
|
|
// Implicit and hybrid flows that try to use the OOB redirect URI are
|
|
|
|
// rejected earlier. If we got here we're using the code flow.
|
2016-08-20 05:54:49 +05:30
|
|
|
if authReq.RedirectURI == redirectURIOOB {
|
2016-12-13 04:24:01 +05:30
|
|
|
if err := s.templates.oob(w, code.ID); err != nil {
|
|
|
|
s.logger.Errorf("Server template error: %v", err)
|
|
|
|
}
|
2016-08-20 05:54:49 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
case responseTypeToken:
|
2017-01-10 00:16:16 +05:30
|
|
|
implicitOrHybrid = true
|
|
|
|
case responseTypeIDToken:
|
|
|
|
implicitOrHybrid = true
|
|
|
|
var err error
|
2017-02-11 01:03:54 +05:30
|
|
|
idToken, idTokenExpiry, err = s.newIDToken(authReq.ClientID, authReq.Claims, authReq.Scopes, authReq.Nonce, accessToken, authReq.ConnectorID)
|
2016-08-20 05:54:49 +05:30
|
|
|
if err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("failed to create ID token: %v", err)
|
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
2016-08-20 05:54:49 +05:30
|
|
|
return
|
|
|
|
}
|
2017-01-10 00:16:16 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if implicitOrHybrid {
|
|
|
|
v := url.Values{}
|
2017-01-11 07:21:12 +05:30
|
|
|
v.Set("access_token", accessToken)
|
2017-01-10 00:16:16 +05:30
|
|
|
v.Set("token_type", "bearer")
|
|
|
|
v.Set("state", authReq.State)
|
|
|
|
if idToken != "" {
|
2016-08-20 05:54:49 +05:30
|
|
|
v.Set("id_token", idToken)
|
2017-01-10 00:16:16 +05:30
|
|
|
// The hybrid flow with only "code token" or "code id_token" doesn't return an
|
|
|
|
// "expires_in" value. If "code" wasn't provided, indicating the implicit flow,
|
|
|
|
// don't add it.
|
|
|
|
//
|
|
|
|
// https://openid.net/specs/openid-connect-core-1_0.html#HybridAuthResponse
|
|
|
|
if code.ID == "" {
|
|
|
|
v.Set("expires_in", strconv.Itoa(int(idTokenExpiry.Sub(s.now()).Seconds())))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if code.ID != "" {
|
|
|
|
v.Set("code", code.ID)
|
2016-08-20 05:54:49 +05:30
|
|
|
}
|
2017-01-10 00:16:16 +05:30
|
|
|
|
|
|
|
// Implicit and hybrid flows return their values as part of the fragment.
|
|
|
|
//
|
|
|
|
// HTTP/1.1 303 See Other
|
|
|
|
// Location: https://client.example.org/cb#
|
|
|
|
// access_token=SlAV32hkKG
|
|
|
|
// &token_type=bearer
|
|
|
|
// &id_token=eyJ0 ... NiJ9.eyJ1c ... I6IjIifX0.DeWt4Qu ... ZXso
|
|
|
|
// &expires_in=3600
|
|
|
|
// &state=af0ifjsldkj
|
|
|
|
//
|
|
|
|
u.Fragment = v.Encode()
|
|
|
|
} else {
|
|
|
|
// The code flow add values to the URL query.
|
|
|
|
//
|
|
|
|
// HTTP/1.1 303 See Other
|
|
|
|
// Location: https://client.example.org/cb?
|
|
|
|
// code=SplxlOBeZQQYbYS6WxSbIA
|
|
|
|
// &state=af0ifjsldkj
|
|
|
|
//
|
|
|
|
q := u.Query()
|
|
|
|
q.Set("code", code.ID)
|
|
|
|
q.Set("state", authReq.State)
|
|
|
|
u.RawQuery = q.Encode()
|
2016-08-20 05:54:49 +05:30
|
|
|
}
|
|
|
|
|
2016-07-26 01:30:28 +05:30
|
|
|
http.Redirect(w, r, u.String(), http.StatusSeeOther)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *Server) handleToken(w http.ResponseWriter, r *http.Request) {
|
|
|
|
clientID, clientSecret, ok := r.BasicAuth()
|
|
|
|
if ok {
|
|
|
|
var err error
|
|
|
|
if clientID, err = url.QueryUnescape(clientID); err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.tokenErrHelper(w, errInvalidRequest, "client_id improperly encoded", http.StatusBadRequest)
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
if clientSecret, err = url.QueryUnescape(clientSecret); err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.tokenErrHelper(w, errInvalidRequest, "client_secret improperly encoded", http.StatusBadRequest)
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
clientID = r.PostFormValue("client_id")
|
|
|
|
clientSecret = r.PostFormValue("client_secret")
|
|
|
|
}
|
|
|
|
|
|
|
|
client, err := s.storage.GetClient(clientID)
|
|
|
|
if err != nil {
|
|
|
|
if err != storage.ErrNotFound {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("failed to get client: %v", err)
|
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
2016-07-26 01:30:28 +05:30
|
|
|
} else {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.tokenErrHelper(w, errInvalidClient, "Invalid client credentials.", http.StatusUnauthorized)
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if client.Secret != clientSecret {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.tokenErrHelper(w, errInvalidClient, "Invalid client credentials.", http.StatusUnauthorized)
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
grantType := r.PostFormValue("grant_type")
|
|
|
|
switch grantType {
|
2016-08-24 23:44:38 +05:30
|
|
|
case grantTypeAuthorizationCode:
|
2016-07-26 01:30:28 +05:30
|
|
|
s.handleAuthCode(w, r, client)
|
2016-08-24 23:44:38 +05:30
|
|
|
case grantTypeRefreshToken:
|
2016-07-26 01:30:28 +05:30
|
|
|
s.handleRefreshToken(w, r, client)
|
|
|
|
default:
|
2016-12-13 04:24:01 +05:30
|
|
|
s.tokenErrHelper(w, errInvalidGrant, "", http.StatusBadRequest)
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// handle an access token request https://tools.ietf.org/html/rfc6749#section-4.1.3
|
|
|
|
func (s *Server) handleAuthCode(w http.ResponseWriter, r *http.Request, client storage.Client) {
|
|
|
|
code := r.PostFormValue("code")
|
|
|
|
redirectURI := r.PostFormValue("redirect_uri")
|
|
|
|
|
|
|
|
authCode, err := s.storage.GetAuthCode(code)
|
|
|
|
if err != nil || s.now().After(authCode.Expiry) || authCode.ClientID != client.ID {
|
|
|
|
if err != storage.ErrNotFound {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("failed to get auth code: %v", err)
|
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
2016-07-26 01:30:28 +05:30
|
|
|
} else {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.tokenErrHelper(w, errInvalidRequest, "Invalid or expired code parameter.", http.StatusBadRequest)
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if authCode.RedirectURI != redirectURI {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.tokenErrHelper(w, errInvalidRequest, "redirect_uri did not match URI from initial request.", http.StatusBadRequest)
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-01-11 07:21:12 +05:30
|
|
|
accessToken := storage.NewID()
|
2017-02-11 01:03:54 +05:30
|
|
|
idToken, expiry, err := s.newIDToken(client.ID, authCode.Claims, authCode.Scopes, authCode.Nonce, accessToken, authCode.ConnectorID)
|
2016-07-26 01:30:28 +05:30
|
|
|
if err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("failed to create ID token: %v", err)
|
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := s.storage.DeleteAuthCode(code); err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("failed to delete auth code: %v", err)
|
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
reqRefresh := func() bool {
|
2017-03-24 02:36:30 +05:30
|
|
|
// Ensure the connector supports refresh tokens.
|
|
|
|
//
|
2017-04-11 06:01:07 +05:30
|
|
|
// Connectors like `saml` do not implement RefreshConnector.
|
2017-04-18 04:11:41 +05:30
|
|
|
conn, err := s.getConnector(authCode.ConnectorID)
|
|
|
|
if err != nil {
|
|
|
|
s.logger.Errorf("connector with ID %q not found: %v", authCode.ConnectorID, err)
|
2017-03-24 02:36:30 +05:30
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
|
|
|
return false
|
|
|
|
}
|
2017-04-18 04:11:41 +05:30
|
|
|
|
|
|
|
_, ok := conn.Connector.(connector.RefreshConnector)
|
2017-03-24 02:36:30 +05:30
|
|
|
if !ok {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2016-07-26 01:30:28 +05:30
|
|
|
for _, scope := range authCode.Scopes {
|
|
|
|
if scope == scopeOfflineAccess {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}()
|
|
|
|
var refreshToken string
|
|
|
|
if reqRefresh {
|
2016-08-03 10:27:36 +05:30
|
|
|
refresh := storage.RefreshToken{
|
2016-12-23 06:11:30 +05:30
|
|
|
ID: storage.NewID(),
|
|
|
|
Token: storage.NewID(),
|
2016-11-19 03:10:41 +05:30
|
|
|
ClientID: authCode.ClientID,
|
|
|
|
ConnectorID: authCode.ConnectorID,
|
|
|
|
Scopes: authCode.Scopes,
|
|
|
|
Claims: authCode.Claims,
|
|
|
|
Nonce: authCode.Nonce,
|
|
|
|
ConnectorData: authCode.ConnectorData,
|
2016-12-23 06:11:30 +05:30
|
|
|
CreatedAt: s.now(),
|
|
|
|
LastUsed: s.now(),
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
2016-12-23 06:11:30 +05:30
|
|
|
token := &internal.RefreshToken{
|
|
|
|
RefreshId: refresh.ID,
|
|
|
|
Token: refresh.Token,
|
|
|
|
}
|
|
|
|
if refreshToken, err = internal.Marshal(token); err != nil {
|
|
|
|
s.logger.Errorf("failed to marshal refresh token: %v", err)
|
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-07-26 01:30:28 +05:30
|
|
|
if err := s.storage.CreateRefresh(refresh); err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("failed to create refresh token: %v", err)
|
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
2017-02-01 05:41:59 +05:30
|
|
|
|
|
|
|
// deleteToken determines if we need to delete the newly created refresh token
|
|
|
|
// due to a failure in updating/creating the OfflineSession object for the
|
|
|
|
// corresponding user.
|
|
|
|
var deleteToken bool
|
|
|
|
defer func() {
|
|
|
|
if deleteToken {
|
|
|
|
// Delete newly created refresh token from storage.
|
|
|
|
if err := s.storage.DeleteRefresh(refresh.ID); err != nil {
|
|
|
|
s.logger.Errorf("failed to delete refresh token: %v", err)
|
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
tokenRef := storage.RefreshTokenRef{
|
|
|
|
ID: refresh.ID,
|
|
|
|
ClientID: refresh.ClientID,
|
|
|
|
CreatedAt: refresh.CreatedAt,
|
|
|
|
LastUsed: refresh.LastUsed,
|
|
|
|
}
|
|
|
|
|
|
|
|
// Try to retrieve an existing OfflineSession object for the corresponding user.
|
|
|
|
if session, err := s.storage.GetOfflineSessions(refresh.Claims.UserID, refresh.ConnectorID); err != nil {
|
|
|
|
if err != storage.ErrNotFound {
|
|
|
|
s.logger.Errorf("failed to get offline session: %v", err)
|
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
|
|
|
deleteToken = true
|
|
|
|
return
|
|
|
|
}
|
|
|
|
offlineSessions := storage.OfflineSessions{
|
|
|
|
UserID: refresh.Claims.UserID,
|
|
|
|
ConnID: refresh.ConnectorID,
|
|
|
|
Refresh: make(map[string]*storage.RefreshTokenRef),
|
|
|
|
}
|
|
|
|
offlineSessions.Refresh[tokenRef.ClientID] = &tokenRef
|
|
|
|
|
|
|
|
// Create a new OfflineSession object for the user and add a reference object for
|
2017-03-20 21:46:56 +05:30
|
|
|
// the newly received refreshtoken.
|
2017-02-01 05:41:59 +05:30
|
|
|
if err := s.storage.CreateOfflineSessions(offlineSessions); err != nil {
|
|
|
|
s.logger.Errorf("failed to create offline session: %v", err)
|
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
|
|
|
deleteToken = true
|
|
|
|
return
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if oldTokenRef, ok := session.Refresh[tokenRef.ClientID]; ok {
|
|
|
|
// Delete old refresh token from storage.
|
|
|
|
if err := s.storage.DeleteRefresh(oldTokenRef.ID); err != nil {
|
|
|
|
s.logger.Errorf("failed to delete refresh token: %v", err)
|
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
|
|
|
deleteToken = true
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update existing OfflineSession obj with new RefreshTokenRef.
|
|
|
|
if err := s.storage.UpdateOfflineSessions(session.UserID, session.ConnID, func(old storage.OfflineSessions) (storage.OfflineSessions, error) {
|
|
|
|
old.Refresh[tokenRef.ClientID] = &tokenRef
|
|
|
|
return old, nil
|
|
|
|
}); err != nil {
|
|
|
|
s.logger.Errorf("failed to update offline session: %v", err)
|
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
|
|
|
deleteToken = true
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
2017-01-11 07:21:12 +05:30
|
|
|
s.writeAccessToken(w, idToken, accessToken, refreshToken, expiry)
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
// handle a refresh token request https://tools.ietf.org/html/rfc6749#section-6
|
|
|
|
func (s *Server) handleRefreshToken(w http.ResponseWriter, r *http.Request, client storage.Client) {
|
|
|
|
code := r.PostFormValue("refresh_token")
|
|
|
|
scope := r.PostFormValue("scope")
|
|
|
|
if code == "" {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.tokenErrHelper(w, errInvalidRequest, "No refresh token in request.", http.StatusBadRequest)
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-12-23 06:11:30 +05:30
|
|
|
token := new(internal.RefreshToken)
|
|
|
|
if err := internal.Unmarshal(code, token); err != nil {
|
|
|
|
// For backward compatibility, assume the refresh_token is a raw refresh token ID
|
|
|
|
// if it fails to decode.
|
|
|
|
//
|
|
|
|
// Because refresh_token values that aren't unmarshable were generated by servers
|
|
|
|
// that don't have a Token value, we'll still reject any attempts to claim a
|
|
|
|
// refresh_token twice.
|
|
|
|
token = &internal.RefreshToken{RefreshId: code, Token: ""}
|
|
|
|
}
|
|
|
|
|
|
|
|
refresh, err := s.storage.GetRefresh(token.RefreshId)
|
|
|
|
if err != nil {
|
|
|
|
s.logger.Errorf("failed to get refresh token: %v", err)
|
|
|
|
if err == storage.ErrNotFound {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.tokenErrHelper(w, errInvalidRequest, "Refresh token is invalid or has already been claimed by another client.", http.StatusBadRequest)
|
2016-12-23 06:11:30 +05:30
|
|
|
} else {
|
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2016-12-23 06:11:30 +05:30
|
|
|
if refresh.ClientID != client.ID {
|
|
|
|
s.logger.Errorf("client %s trying to claim token for client %s", client.ID, refresh.ClientID)
|
|
|
|
s.tokenErrHelper(w, errInvalidRequest, "Refresh token is invalid or has already been claimed by another client.", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if refresh.Token != token.Token {
|
|
|
|
s.logger.Errorf("refresh token with id %s claimed twice", refresh.ID)
|
|
|
|
s.tokenErrHelper(w, errInvalidRequest, "Refresh token is invalid or has already been claimed by another client.", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
2016-07-26 01:30:28 +05:30
|
|
|
|
2016-11-19 03:10:41 +05:30
|
|
|
// Per the OAuth2 spec, if the client has omitted the scopes, default to the original
|
|
|
|
// authorized scopes.
|
|
|
|
//
|
|
|
|
// https://tools.ietf.org/html/rfc6749#section-6
|
2016-07-26 01:30:28 +05:30
|
|
|
scopes := refresh.Scopes
|
|
|
|
if scope != "" {
|
2016-10-13 04:01:01 +05:30
|
|
|
requestedScopes := strings.Fields(scope)
|
2016-10-10 23:32:27 +05:30
|
|
|
var unauthorizedScopes []string
|
|
|
|
|
|
|
|
for _, s := range requestedScopes {
|
|
|
|
contains := func() bool {
|
2016-07-26 01:30:28 +05:30
|
|
|
for _, scope := range refresh.Scopes {
|
|
|
|
if s == scope {
|
2016-10-10 23:32:27 +05:30
|
|
|
return true
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
2016-10-10 23:32:27 +05:30
|
|
|
}()
|
|
|
|
if !contains {
|
|
|
|
unauthorizedScopes = append(unauthorizedScopes, s)
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
2016-10-10 23:32:27 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
if len(unauthorizedScopes) > 0 {
|
|
|
|
msg := fmt.Sprintf("Requested scopes contain unauthorized scope(s): %q.", unauthorizedScopes)
|
2016-12-13 04:24:01 +05:30
|
|
|
s.tokenErrHelper(w, errInvalidRequest, msg, http.StatusBadRequest)
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
scopes = requestedScopes
|
|
|
|
}
|
|
|
|
|
2017-04-18 04:11:41 +05:30
|
|
|
conn, err := s.getConnector(refresh.ConnectorID)
|
|
|
|
if err != nil {
|
|
|
|
s.logger.Errorf("connector with ID %q not found: %v", refresh.ConnectorID, err)
|
2016-12-13 04:24:01 +05:30
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
2016-11-19 03:10:41 +05:30
|
|
|
return
|
|
|
|
}
|
2016-12-23 06:11:30 +05:30
|
|
|
ident := connector.Identity{
|
|
|
|
UserID: refresh.Claims.UserID,
|
|
|
|
Username: refresh.Claims.Username,
|
|
|
|
Email: refresh.Claims.Email,
|
|
|
|
EmailVerified: refresh.Claims.EmailVerified,
|
|
|
|
Groups: refresh.Claims.Groups,
|
|
|
|
ConnectorData: refresh.ConnectorData,
|
|
|
|
}
|
2016-11-19 03:10:41 +05:30
|
|
|
|
|
|
|
// Can the connector refresh the identity? If so, attempt to refresh the data
|
|
|
|
// in the connector.
|
|
|
|
//
|
|
|
|
// TODO(ericchiang): We may want a strict mode where connectors that don't implement
|
|
|
|
// this interface can't perform refreshing.
|
|
|
|
if refreshConn, ok := conn.Connector.(connector.RefreshConnector); ok {
|
2016-12-23 06:11:30 +05:30
|
|
|
newIdent, err := refreshConn.Refresh(r.Context(), parseScopes(scopes), ident)
|
2016-11-19 03:10:41 +05:30
|
|
|
if err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("failed to refresh identity: %v", err)
|
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
2016-11-19 03:10:41 +05:30
|
|
|
return
|
|
|
|
}
|
2016-12-23 06:11:30 +05:30
|
|
|
ident = newIdent
|
|
|
|
}
|
2016-11-19 03:10:41 +05:30
|
|
|
|
2016-12-23 06:11:30 +05:30
|
|
|
claims := storage.Claims{
|
|
|
|
UserID: ident.UserID,
|
|
|
|
Username: ident.Username,
|
|
|
|
Email: ident.Email,
|
|
|
|
EmailVerified: ident.EmailVerified,
|
|
|
|
Groups: ident.Groups,
|
2016-11-19 03:10:41 +05:30
|
|
|
}
|
2016-07-26 01:30:28 +05:30
|
|
|
|
2017-01-11 07:21:12 +05:30
|
|
|
accessToken := storage.NewID()
|
2017-02-11 01:03:54 +05:30
|
|
|
idToken, expiry, err := s.newIDToken(client.ID, claims, scopes, refresh.Nonce, accessToken, refresh.ConnectorID)
|
2016-07-26 01:30:28 +05:30
|
|
|
if err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("failed to create ID token: %v", err)
|
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-12-23 06:11:30 +05:30
|
|
|
newToken := &internal.RefreshToken{
|
|
|
|
RefreshId: refresh.ID,
|
|
|
|
Token: storage.NewID(),
|
|
|
|
}
|
|
|
|
rawNewToken, err := internal.Marshal(newToken)
|
|
|
|
if err != nil {
|
|
|
|
s.logger.Errorf("failed to marshal refresh token: %v", err)
|
2016-12-13 04:24:01 +05:30
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
2016-12-23 06:11:30 +05:30
|
|
|
|
2017-02-01 05:41:59 +05:30
|
|
|
lastUsed := s.now()
|
2016-12-23 06:11:30 +05:30
|
|
|
updater := func(old storage.RefreshToken) (storage.RefreshToken, error) {
|
|
|
|
if old.Token != refresh.Token {
|
|
|
|
return old, errors.New("refresh token claimed twice")
|
|
|
|
}
|
|
|
|
old.Token = newToken.Token
|
|
|
|
// Update the claims of the refresh token.
|
|
|
|
//
|
|
|
|
// UserID intentionally ignored for now.
|
|
|
|
old.Claims.Username = ident.Username
|
|
|
|
old.Claims.Email = ident.Email
|
|
|
|
old.Claims.EmailVerified = ident.EmailVerified
|
|
|
|
old.Claims.Groups = ident.Groups
|
|
|
|
old.ConnectorData = ident.ConnectorData
|
2017-02-01 05:41:59 +05:30
|
|
|
old.LastUsed = lastUsed
|
2016-12-23 06:11:30 +05:30
|
|
|
return old, nil
|
|
|
|
}
|
2017-02-01 05:41:59 +05:30
|
|
|
|
|
|
|
// Update LastUsed time stamp in refresh token reference object
|
|
|
|
// in offline session for the user.
|
|
|
|
if err := s.storage.UpdateOfflineSessions(refresh.Claims.UserID, refresh.ConnectorID, func(old storage.OfflineSessions) (storage.OfflineSessions, error) {
|
|
|
|
if old.Refresh[refresh.ClientID].ID != refresh.ID {
|
|
|
|
return old, errors.New("refresh token invalid")
|
|
|
|
}
|
|
|
|
old.Refresh[refresh.ClientID].LastUsed = lastUsed
|
|
|
|
return old, nil
|
|
|
|
}); err != nil {
|
|
|
|
s.logger.Errorf("failed to update offline session: %v", err)
|
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Update refresh token in the storage.
|
2016-12-23 06:11:30 +05:30
|
|
|
if err := s.storage.UpdateRefreshToken(refresh.ID, updater); err != nil {
|
|
|
|
s.logger.Errorf("failed to update refresh token: %v", err)
|
2016-12-13 04:24:01 +05:30
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
2017-02-01 05:41:59 +05:30
|
|
|
|
2017-01-11 07:21:12 +05:30
|
|
|
s.writeAccessToken(w, idToken, accessToken, rawNewToken, expiry)
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
|
|
|
|
2017-01-11 07:21:12 +05:30
|
|
|
func (s *Server) writeAccessToken(w http.ResponseWriter, idToken, accessToken, refreshToken string, expiry time.Time) {
|
2016-07-26 01:30:28 +05:30
|
|
|
// TODO(ericchiang): figure out an access token story and support the user info
|
|
|
|
// endpoint. For now use a random value so no one depends on the access_token
|
|
|
|
// holding a specific structure.
|
|
|
|
resp := struct {
|
|
|
|
AccessToken string `json:"access_token"`
|
|
|
|
TokenType string `json:"token_type"`
|
|
|
|
ExpiresIn int `json:"expires_in"`
|
|
|
|
RefreshToken string `json:"refresh_token,omitempty"`
|
|
|
|
IDToken string `json:"id_token"`
|
|
|
|
}{
|
2017-01-11 07:21:12 +05:30
|
|
|
accessToken,
|
2016-07-26 01:30:28 +05:30
|
|
|
"bearer",
|
2016-11-04 10:09:31 +05:30
|
|
|
int(expiry.Sub(s.now()).Seconds()),
|
2016-07-26 01:30:28 +05:30
|
|
|
refreshToken,
|
|
|
|
idToken,
|
|
|
|
}
|
|
|
|
data, err := json.Marshal(resp)
|
|
|
|
if err != nil {
|
2016-12-13 04:24:01 +05:30
|
|
|
s.logger.Errorf("failed to marshal access token response: %v", err)
|
|
|
|
s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError)
|
2016-07-26 01:30:28 +05:30
|
|
|
return
|
|
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
|
|
|
|
w.Write(data)
|
|
|
|
}
|
|
|
|
|
2016-12-15 03:47:59 +05:30
|
|
|
func (s *Server) renderError(w http.ResponseWriter, status int, description string) {
|
2017-12-01 10:53:45 +05:30
|
|
|
if err := s.templates.err(w, status, description); err != nil {
|
2016-12-15 03:47:59 +05:30
|
|
|
s.logger.Errorf("Server template error: %v", err)
|
|
|
|
}
|
2016-07-26 01:30:28 +05:30
|
|
|
}
|
2016-12-13 04:24:01 +05:30
|
|
|
|
|
|
|
func (s *Server) tokenErrHelper(w http.ResponseWriter, typ string, description string, statusCode int) {
|
|
|
|
if err := tokenErr(w, typ, description, statusCode); err != nil {
|
2017-03-20 21:46:56 +05:30
|
|
|
s.logger.Errorf("token error response: %v", err)
|
2016-12-13 04:24:01 +05:30
|
|
|
}
|
|
|
|
}
|
2017-11-07 14:58:21 +05:30
|
|
|
|
|
|
|
// Check for username prompt override from connector. Defaults to "Username".
|
|
|
|
func usernamePrompt(conn connector.PasswordConnector) string {
|
|
|
|
if attr := conn.Prompt(); attr != "" {
|
|
|
|
return attr
|
|
|
|
}
|
|
|
|
return "Username"
|
|
|
|
}
|