mirror of
https://github.com/pomerium/pomerium.git
synced 2025-08-04 01:09:36 +02:00
authenticator: support groups (#57)
- authenticate/providers: add group support to azure - authenticate/providers: add group support to google - authenticate/providers: add group support to okta - authenticate/providers: add group support to onelogin - {authenticate/proxy}: change default cookie lifetime timeout to 14 hours - proxy: sign group membership - proxy: add group header - deployment: add CHANGELOG - deployment: fix where make release wasn’t including version
This commit is contained in:
parent
a2d647ee5b
commit
1187be2bf3
54 changed files with 1757 additions and 1706 deletions
|
@ -10,7 +10,7 @@ import (
|
|||
// JWTSigner implements JWT signing according to JSON Web Token (JWT) RFC7519
|
||||
// https://tools.ietf.org/html/rfc7519
|
||||
type JWTSigner interface {
|
||||
SignJWT(string, string) (string, error)
|
||||
SignJWT(string, string, string) (string, error)
|
||||
}
|
||||
|
||||
// ES256Signer is struct containing the required fields to create a ES256 signed JSON Web Tokens
|
||||
|
@ -18,9 +18,15 @@ type ES256Signer struct {
|
|||
// User (sub) is unique, stable identifier for the user.
|
||||
// Use in place of the x-pomerium-authenticated-user-id header.
|
||||
User string `json:"sub,omitempty"`
|
||||
// Email (sub) is a **private** claim name identifier for the user email address.
|
||||
|
||||
// Email (email) is a **custom** claim name identifier for the user email address.
|
||||
// Use in place of the x-pomerium-authenticated-user-email header.
|
||||
Email string `json:"email,omitempty"`
|
||||
|
||||
// Groups (groups) is a **custom** claim name identifier for the user's groups.
|
||||
// Use in place of the x-pomerium-authenticated-user-groups header.
|
||||
Groups string `json:"groups,omitempty"`
|
||||
|
||||
// Audience (aud) must be the destination of the upstream proxy locations.
|
||||
// e.g. `helloworld.corp.example.com`
|
||||
Audience jwt.Audience `json:"aud,omitempty"`
|
||||
|
@ -68,14 +74,16 @@ func NewES256Signer(privKey []byte, audience string) (*ES256Signer, error) {
|
|||
}, nil
|
||||
}
|
||||
|
||||
// SignJWT creates a signed JWT containing claims for the logged in user id (`sub`) and email (`email`).
|
||||
func (s *ES256Signer) SignJWT(user, email string) (string, error) {
|
||||
// SignJWT creates a signed JWT containing claims for the logged in
|
||||
// user id (`sub`), email (`email`) and groups (`groups`).
|
||||
func (s *ES256Signer) SignJWT(user, email, groups string) (string, error) {
|
||||
s.User = user
|
||||
s.Email = email
|
||||
s.Groups = groups
|
||||
now := time.Now()
|
||||
s.IssuedAt = jwt.NewNumericDate(now)
|
||||
s.Expiry = jwt.NewNumericDate(now.Add(jwt.DefaultLeeway))
|
||||
s.NotBefore = jwt.NewNumericDate(now.Add(-1 * jwt.DefaultLeeway))
|
||||
s.IssuedAt = *jwt.NewNumericDate(now)
|
||||
s.Expiry = *jwt.NewNumericDate(now.Add(jwt.DefaultLeeway))
|
||||
s.NotBefore = *jwt.NewNumericDate(now.Add(-1 * jwt.DefaultLeeway))
|
||||
rawJWT, err := jwt.Signed(s.signer).Claims(s).CompactSerialize()
|
||||
if err != nil {
|
||||
return "", err
|
||||
|
|
|
@ -12,7 +12,7 @@ func TestES256Signer(t *testing.T) {
|
|||
if signer == nil {
|
||||
t.Fatal("signer should not be nil")
|
||||
}
|
||||
rawJwt, err := signer.SignJWT("joe-user", "joe-user@example.com")
|
||||
rawJwt, err := signer.SignJWT("joe-user", "joe-user@example.com", "group1,group2")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
|
|
@ -11,8 +11,6 @@ import (
|
|||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/pomerium/pomerium/internal/log"
|
||||
)
|
||||
|
||||
// ErrTokenRevoked signifies a token revokation or expiration error
|
||||
|
@ -29,12 +27,12 @@ var httpClient = &http.Client{
|
|||
}
|
||||
|
||||
// Client provides a simple helper interface to make HTTP requests
|
||||
func Client(method, endpoint, userAgent string, params url.Values, response interface{}) error {
|
||||
func Client(method, endpoint, userAgent string, headers map[string]string, params url.Values, response interface{}) error {
|
||||
var body io.Reader
|
||||
switch method {
|
||||
case "POST":
|
||||
case http.MethodPost:
|
||||
body = bytes.NewBufferString(params.Encode())
|
||||
case "GET":
|
||||
case http.MethodGet:
|
||||
// error checking skipped because we are just parsing in
|
||||
// order to make a copy of an existing URL
|
||||
u, _ := url.Parse(endpoint)
|
||||
|
@ -49,6 +47,9 @@ func Client(method, endpoint, userAgent string, params url.Values, response inte
|
|||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("User-Agent", userAgent)
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
|
@ -57,12 +58,11 @@ func Client(method, endpoint, userAgent string, params url.Values, response inte
|
|||
|
||||
var respBody []byte
|
||||
respBody, err = ioutil.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
defer resp.Body.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Info().Msgf("%s", respBody)
|
||||
|
||||
// log.Info().Msgf("%s", respBody)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
switch resp.StatusCode {
|
||||
case http.StatusBadRequest:
|
||||
|
|
273
internal/identity/google.go
Normal file
273
internal/identity/google.go
Normal file
|
@ -0,0 +1,273 @@
|
|||
package identity // import "github.com/pomerium/pomerium/internal/identity"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
oidc "github.com/pomerium/go-oidc"
|
||||
"golang.org/x/oauth2"
|
||||
"golang.org/x/oauth2/jwt"
|
||||
admin "google.golang.org/api/admin/directory/v1"
|
||||
|
||||
"github.com/pomerium/pomerium/internal/httputil"
|
||||
"github.com/pomerium/pomerium/internal/log"
|
||||
"github.com/pomerium/pomerium/internal/sessions"
|
||||
"github.com/pomerium/pomerium/internal/version"
|
||||
)
|
||||
|
||||
const defaultGoogleProviderURL = "https://accounts.google.com"
|
||||
|
||||
// JWTTokenURL is Google's OAuth 2.0 token URL to use with the JWT flow.
|
||||
const JWTTokenURL = "https://accounts.google.com/o/oauth2/token"
|
||||
|
||||
// GoogleProvider is an implementation of the Provider interface.
|
||||
type GoogleProvider struct {
|
||||
*Provider
|
||||
// non-standard oidc fields
|
||||
RevokeURL *url.URL
|
||||
apiClient *admin.Service
|
||||
}
|
||||
|
||||
// NewGoogleProvider returns a new GoogleProvider and sets the provider url endpoints.
|
||||
func NewGoogleProvider(p *Provider) (*GoogleProvider, error) {
|
||||
ctx := context.Background()
|
||||
if p.ProviderURL == "" {
|
||||
p.ProviderURL = defaultGoogleProviderURL
|
||||
}
|
||||
var err error
|
||||
p.provider, err = oidc.NewProvider(ctx, p.ProviderURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(p.Scopes) == 0 {
|
||||
p.Scopes = []string{oidc.ScopeOpenID, "profile", "email", "offline_access"}
|
||||
}
|
||||
p.verifier = p.provider.Verifier(&oidc.Config{ClientID: p.ClientID})
|
||||
p.oauth = &oauth2.Config{
|
||||
ClientID: p.ClientID,
|
||||
ClientSecret: p.ClientSecret,
|
||||
Endpoint: p.provider.Endpoint(),
|
||||
RedirectURL: p.RedirectURL.String(),
|
||||
Scopes: p.Scopes,
|
||||
}
|
||||
|
||||
gp := &GoogleProvider{
|
||||
Provider: p,
|
||||
}
|
||||
// google supports a revocation endpoint
|
||||
var claims struct {
|
||||
RevokeURL string `json:"revocation_endpoint"`
|
||||
}
|
||||
|
||||
// build api client to make group membership api calls
|
||||
if err := p.provider.Claims(&claims); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// if service account set, configure admin sdk calls
|
||||
if p.ServiceAccount != "" {
|
||||
apiCreds, err := base64.StdEncoding.DecodeString(p.ServiceAccount)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("identity/google: could not decode service account json %v", err)
|
||||
}
|
||||
// Required scopes for groups api
|
||||
// https://developers.google.com/admin-sdk/directory/v1/reference/groups/list
|
||||
conf, err := JWTConfigFromJSON(apiCreds, admin.AdminDirectoryUserReadonlyScope, admin.AdminDirectoryGroupReadonlyScope)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("identity/google: failed making jwt config from json %v", err)
|
||||
}
|
||||
client := conf.Client(context.TODO())
|
||||
gp.apiClient, err = admin.New(client)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("identity/google: failed creating admin service %v", err)
|
||||
}
|
||||
} else {
|
||||
log.Warn().Msg("identity/google: no service account found, cannot retrieve user groups")
|
||||
}
|
||||
|
||||
gp.RevokeURL, err = url.Parse(claims.RevokeURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return gp, nil
|
||||
}
|
||||
|
||||
// Revoke revokes the access token a given session state.
|
||||
//
|
||||
// https://developers.google.com/identity/protocols/OAuth2WebServer#tokenrevoke
|
||||
func (p *GoogleProvider) Revoke(accessToken string) error {
|
||||
params := url.Values{}
|
||||
params.Add("token", accessToken)
|
||||
err := httputil.Client("POST", p.RevokeURL.String(), version.UserAgent(), nil, params, nil)
|
||||
if err != nil && err != httputil.ErrTokenRevoked {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSignInURL returns a URL to OAuth 2.0 provider's consent page that asks for permissions for
|
||||
// the required scopes explicitly.
|
||||
// Google requires an additional access scope for offline access which is a requirement for any
|
||||
// application that needs to access a Google API when the user is not present.
|
||||
// https://developers.google.com/identity/protocols/OAuth2WebServer#offline
|
||||
func (p *GoogleProvider) GetSignInURL(state string) string {
|
||||
return p.oauth.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.ApprovalForce)
|
||||
}
|
||||
|
||||
// Authenticate creates an identity session with google from a authorization code, and follows up
|
||||
// call to the admin/group api to check what groups the user is in.
|
||||
func (p *GoogleProvider) Authenticate(code string) (*sessions.SessionState, error) {
|
||||
ctx := context.Background()
|
||||
// convert authorization code into a token
|
||||
oauth2Token, err := p.oauth.Exchange(ctx, code)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("identity/google: token exchange failed %v", err)
|
||||
}
|
||||
|
||||
// id_token contains claims about the authenticated user
|
||||
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("identity/google: response did not contain an id_token")
|
||||
}
|
||||
// Parse and verify ID Token payload.
|
||||
idToken, err := p.verifier.Verify(ctx, rawIDToken)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("identity/google: could not verify id_token %v", err)
|
||||
}
|
||||
|
||||
var claims struct {
|
||||
Email string `json:"email"`
|
||||
EmailVerified bool `json:"email_verified"`
|
||||
}
|
||||
// parse claims from the raw, encoded jwt token
|
||||
if err := idToken.Claims(&claims); err != nil {
|
||||
return nil, fmt.Errorf("identity/google: failed to parse id_token claims %v", err)
|
||||
}
|
||||
|
||||
// google requires additional call to retrieve groups.
|
||||
groups, err := p.UserGroups(ctx, claims.Email)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("identity/google: could not retrieve groups %v", err)
|
||||
}
|
||||
|
||||
return &sessions.SessionState{
|
||||
IDToken: rawIDToken,
|
||||
AccessToken: oauth2Token.AccessToken,
|
||||
RefreshToken: oauth2Token.RefreshToken,
|
||||
RefreshDeadline: oauth2Token.Expiry.Truncate(time.Second),
|
||||
LifetimeDeadline: sessions.ExtendDeadline(p.SessionLifetimeTTL),
|
||||
Email: claims.Email,
|
||||
User: idToken.Subject,
|
||||
Groups: groups,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Refresh renews a user's session using an oid refresh token without reprompting the user.
|
||||
// Group membership is also refreshed.
|
||||
// https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens
|
||||
func (p *GoogleProvider) Refresh(ctx context.Context, s *sessions.SessionState) (*sessions.SessionState, error) {
|
||||
if s.RefreshToken == "" {
|
||||
return nil, errors.New("identity: missing refresh token")
|
||||
}
|
||||
t := oauth2.Token{RefreshToken: s.RefreshToken}
|
||||
newToken, err := p.oauth.TokenSource(ctx, &t).Token()
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("identity: refresh failed")
|
||||
return nil, err
|
||||
}
|
||||
s.AccessToken = newToken.AccessToken
|
||||
s.RefreshDeadline = newToken.Expiry.Truncate(time.Second)
|
||||
// validate groups
|
||||
groups, err := p.UserGroups(ctx, s.User)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("identity/google: could not retrieve groups %v", err)
|
||||
}
|
||||
|
||||
log.Info().
|
||||
Str("refresh-token", s.RefreshToken).
|
||||
Str("new-access-token", newToken.AccessToken).
|
||||
Str("new-expiry", time.Until(newToken.Expiry).String()).
|
||||
Strs("Groups", groups).
|
||||
Msg("identity: refresh")
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// UserGroups returns a slice of group names a given user is in
|
||||
// NOTE: groups via Directory API is limited to 1 QPS!
|
||||
// https://developers.google.com/admin-sdk/directory/v1/reference/groups/list
|
||||
// https://developers.google.com/admin-sdk/directory/v1/limits
|
||||
func (p *GoogleProvider) UserGroups(ctx context.Context, user string) ([]string, error) {
|
||||
var groups []string
|
||||
if p.apiClient != nil {
|
||||
req := p.apiClient.Groups.List().UserKey(user).MaxResults(100)
|
||||
resp, err := req.Do()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("identity/google: group api request failed %v", err)
|
||||
}
|
||||
for _, group := range resp.Groups {
|
||||
log.Info().Str("group.Name", group.Name).Msg("sanity check3")
|
||||
groups = append(groups, group.Name)
|
||||
}
|
||||
}
|
||||
return groups, nil
|
||||
}
|
||||
|
||||
// JWTConfigFromJSON uses a Google Developers service account JSON key file to read
|
||||
// the credentials that authorize and authenticate the requests.
|
||||
// Create a service account on "Credentials" for your project at
|
||||
// https://console.developers.google.com to download a JSON key file.
|
||||
func JWTConfigFromJSON(jsonKey []byte, scope ...string) (*jwt.Config, error) {
|
||||
var f credentialsFile
|
||||
if err := json.Unmarshal(jsonKey, &f); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if f.Type != "service_account" {
|
||||
return nil, fmt.Errorf("identity/google: 'type' field is %q (expected %q)", f.Type, "service_account")
|
||||
}
|
||||
// Service account must impersonate a user : https://stackoverflow.com/a/48601364
|
||||
if f.ImpersonateUser == "" {
|
||||
return nil, errors.New("identity/google: impersonate_user not found in json config")
|
||||
}
|
||||
scope = append([]string(nil), scope...) // copy
|
||||
return f.jwtConfig(scope), nil
|
||||
}
|
||||
|
||||
// credentialsFile is the unmarshalled representation of a credentials file.
|
||||
type credentialsFile struct {
|
||||
Type string `json:"type"` // serviceAccountKey or userCredentialsKey
|
||||
|
||||
// Service account must impersonate a user
|
||||
ImpersonateUser string `json:"impersonate_user"`
|
||||
// Service Account fields
|
||||
ClientEmail string `json:"client_email"`
|
||||
PrivateKeyID string `json:"private_key_id"`
|
||||
PrivateKey string `json:"private_key"`
|
||||
TokenURL string `json:"token_uri"`
|
||||
ProjectID string `json:"project_id"`
|
||||
|
||||
// User Credential fields
|
||||
ClientSecret string `json:"client_secret"`
|
||||
ClientID string `json:"client_id"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
}
|
||||
|
||||
func (f *credentialsFile) jwtConfig(scopes []string) *jwt.Config {
|
||||
cfg := &jwt.Config{
|
||||
Subject: f.ImpersonateUser,
|
||||
Email: f.ClientEmail,
|
||||
PrivateKey: []byte(f.PrivateKey),
|
||||
PrivateKeyID: f.PrivateKeyID,
|
||||
Scopes: scopes,
|
||||
TokenURL: f.TokenURL,
|
||||
}
|
||||
if cfg.TokenURL == "" {
|
||||
cfg.TokenURL = JWTTokenURL
|
||||
}
|
||||
return cfg
|
||||
}
|
188
internal/identity/microsoft.go
Normal file
188
internal/identity/microsoft.go
Normal file
|
@ -0,0 +1,188 @@
|
|||
package identity // import "github.com/pomerium/pomerium/internal/identity"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
oidc "github.com/pomerium/go-oidc"
|
||||
"golang.org/x/oauth2"
|
||||
|
||||
"github.com/pomerium/pomerium/internal/httputil"
|
||||
"github.com/pomerium/pomerium/internal/log"
|
||||
"github.com/pomerium/pomerium/internal/sessions"
|
||||
"github.com/pomerium/pomerium/internal/version"
|
||||
)
|
||||
|
||||
// defaultAzureProviderURL Users with both a personal Microsoft
|
||||
// account and a work or school account from Azure Active Directory (Azure AD)
|
||||
// an sign in to the application.
|
||||
const defaultAzureProviderURL = "https://login.microsoftonline.com/common"
|
||||
const defaultAzureGroupURL = "https://graph.microsoft.com/v1.0/me/memberOf"
|
||||
|
||||
// AzureProvider is an implementation of the Provider interface
|
||||
type AzureProvider struct {
|
||||
*Provider
|
||||
// non-standard oidc fields
|
||||
RevokeURL *url.URL
|
||||
}
|
||||
|
||||
// NewAzureProvider returns a new AzureProvider and sets the provider url endpoints.
|
||||
// https://www.pomerium.io/docs/identity-providers.html#azure-active-directory
|
||||
func NewAzureProvider(p *Provider) (*AzureProvider, error) {
|
||||
ctx := context.Background()
|
||||
if p.ProviderURL == "" {
|
||||
p.ProviderURL = defaultAzureProviderURL
|
||||
}
|
||||
var err error
|
||||
p.provider, err = oidc.NewProvider(ctx, p.ProviderURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(p.Scopes) == 0 {
|
||||
p.Scopes = []string{oidc.ScopeOpenID, "profile", "email", "offline_access"}
|
||||
}
|
||||
p.verifier = p.provider.Verifier(&oidc.Config{ClientID: p.ClientID})
|
||||
p.oauth = &oauth2.Config{
|
||||
ClientID: p.ClientID,
|
||||
ClientSecret: p.ClientSecret,
|
||||
Endpoint: p.provider.Endpoint(),
|
||||
RedirectURL: p.RedirectURL.String(),
|
||||
Scopes: p.Scopes,
|
||||
}
|
||||
|
||||
azureProvider := &AzureProvider{
|
||||
Provider: p,
|
||||
}
|
||||
// azure has a "end session endpoint"
|
||||
var claims struct {
|
||||
RevokeURL string `json:"end_session_endpoint"`
|
||||
}
|
||||
if err := p.provider.Claims(&claims); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
azureProvider.RevokeURL, err = url.Parse(claims.RevokeURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return azureProvider, nil
|
||||
}
|
||||
|
||||
// Authenticate creates an identity session with azure from a authorization code, and follows up
|
||||
// call to the groups api to check what groups the user is in.
|
||||
func (p *AzureProvider) Authenticate(code string) (*sessions.SessionState, error) {
|
||||
ctx := context.Background()
|
||||
// convert authorization code into a token
|
||||
oauth2Token, err := p.oauth.Exchange(ctx, code)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("identity/microsoft: token exchange failed %v", err)
|
||||
}
|
||||
|
||||
// id_token contains claims about the authenticated user
|
||||
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("identity/microsoft: response did not contain an id_token")
|
||||
}
|
||||
// Parse and verify ID Token payload.
|
||||
idToken, err := p.verifier.Verify(ctx, rawIDToken)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("identity/microsoft: could not verify id_token %v", err)
|
||||
}
|
||||
|
||||
var claims struct {
|
||||
Email string `json:"email"`
|
||||
EmailVerified bool `json:"email_verified"`
|
||||
}
|
||||
// parse claims from the raw, encoded jwt token
|
||||
if err := idToken.Claims(&claims); err != nil {
|
||||
return nil, fmt.Errorf("identity/microsoft: failed to parse id_token claims %v", err)
|
||||
}
|
||||
|
||||
// google requires additional call to retrieve groups.
|
||||
groups, err := p.UserGroups(ctx, claims.Email)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("identity/microsoft: could not retrieve groups %v", err)
|
||||
}
|
||||
|
||||
return &sessions.SessionState{
|
||||
IDToken: rawIDToken,
|
||||
AccessToken: oauth2Token.AccessToken,
|
||||
RefreshToken: oauth2Token.RefreshToken,
|
||||
RefreshDeadline: oauth2Token.Expiry.Truncate(time.Second),
|
||||
LifetimeDeadline: sessions.ExtendDeadline(p.SessionLifetimeTTL),
|
||||
Email: claims.Email,
|
||||
User: idToken.Subject,
|
||||
Groups: groups,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Revoke revokes the access token a given session state.
|
||||
// https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-protocols-oidc#send-a-sign-out-request
|
||||
func (p *AzureProvider) Revoke(token string) error {
|
||||
params := url.Values{}
|
||||
params.Add("token", token)
|
||||
err := httputil.Client(http.MethodPost, p.RevokeURL.String(), version.UserAgent(), nil, params, nil)
|
||||
if err != nil && err != httputil.ErrTokenRevoked {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSignInURL returns the sign in url with typical oauth parameters
|
||||
func (p *AzureProvider) GetSignInURL(state string) string {
|
||||
return p.oauth.AuthCodeURL(state, oauth2.AccessTypeOffline, oauth2.ApprovalForce)
|
||||
}
|
||||
|
||||
// Refresh renews a user's session using an oid refresh token without reprompting the user.
|
||||
// Group membership is also refreshed.
|
||||
// https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens
|
||||
func (p *AzureProvider) Refresh(ctx context.Context, s *sessions.SessionState) (*sessions.SessionState, error) {
|
||||
if s.RefreshToken == "" {
|
||||
return nil, errors.New("identity/microsoft: missing refresh token")
|
||||
}
|
||||
t := oauth2.Token{RefreshToken: s.RefreshToken}
|
||||
newToken, err := p.oauth.TokenSource(ctx, &t).Token()
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("identity/microsoft: refresh failed")
|
||||
return nil, err
|
||||
}
|
||||
s.AccessToken = newToken.AccessToken
|
||||
s.RefreshDeadline = newToken.Expiry.Truncate(time.Second)
|
||||
s.Groups, err = p.UserGroups(ctx, s.AccessToken)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("identity/microsoft: refresh failed")
|
||||
return nil, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// UserGroups returns a slice of group names a given user is in.
|
||||
// `Directory.Read.All` is required.
|
||||
// https://docs.microsoft.com/en-us/graph/api/resources/directoryobject?view=graph-rest-1.0
|
||||
// https://docs.microsoft.com/en-us/graph/api/user-list-memberof?view=graph-rest-1.0
|
||||
func (p *AzureProvider) UserGroups(ctx context.Context, accessToken string) ([]string, error) {
|
||||
var response struct {
|
||||
Groups []struct {
|
||||
ID string `json:"id"`
|
||||
Description string `json:"description,omitempty"`
|
||||
DisplayName string `json:"displayName"`
|
||||
CreatedDateTime time.Time `json:"createdDateTime,omitempty"`
|
||||
GroupTypes []string `json:"groupTypes,omitempty"`
|
||||
} `json:"value"`
|
||||
}
|
||||
headers := map[string]string{"Authorization": fmt.Sprintf("Bearer %s", accessToken)}
|
||||
err := httputil.Client(http.MethodGet, defaultAzureGroupURL, version.UserAgent(), headers, nil, &response)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var groups []string
|
||||
for _, group := range response.Groups {
|
||||
log.Info().Str("DisplayName", group.DisplayName).Str("ID", group.ID).Msg("identity/microsoft: group")
|
||||
groups = append(groups, group.DisplayName)
|
||||
}
|
||||
return groups, nil
|
||||
}
|
42
internal/identity/mock_provider.go
Normal file
42
internal/identity/mock_provider.go
Normal file
|
@ -0,0 +1,42 @@
|
|||
package identity // import "github.com/pomerium/pomerium/internal/identity"
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pomerium/pomerium/internal/sessions"
|
||||
)
|
||||
|
||||
// MockProvider provides a mocked implementation of the providers interface.
|
||||
type MockProvider struct {
|
||||
AuthenticateResponse sessions.SessionState
|
||||
AuthenticateError error
|
||||
ValidateResponse bool
|
||||
ValidateError error
|
||||
RefreshResponse *sessions.SessionState
|
||||
RefreshError error
|
||||
RevokeError error
|
||||
GetSignInURLResponse string
|
||||
}
|
||||
|
||||
// Authenticate is a mocked providers function.
|
||||
func (mp MockProvider) Authenticate(code string) (*sessions.SessionState, error) {
|
||||
return &mp.AuthenticateResponse, mp.AuthenticateError
|
||||
}
|
||||
|
||||
// Validate is a mocked providers function.
|
||||
func (mp MockProvider) Validate(ctx context.Context, s string) (bool, error) {
|
||||
return mp.ValidateResponse, mp.ValidateError
|
||||
}
|
||||
|
||||
// Refresh is a mocked providers function.
|
||||
func (mp MockProvider) Refresh(ctx context.Context, s *sessions.SessionState) (*sessions.SessionState, error) {
|
||||
return mp.RefreshResponse, mp.RefreshError
|
||||
}
|
||||
|
||||
// Revoke is a mocked providers function.
|
||||
func (mp MockProvider) Revoke(s string) error {
|
||||
return mp.RevokeError
|
||||
}
|
||||
|
||||
// GetSignInURL is a mocked providers function.
|
||||
func (mp MockProvider) GetSignInURL(s string) string { return mp.GetSignInURLResponse }
|
40
internal/identity/oidc.go
Normal file
40
internal/identity/oidc.go
Normal file
|
@ -0,0 +1,40 @@
|
|||
package identity // import "github.com/pomerium/pomerium/internal/identity"
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
oidc "github.com/pomerium/go-oidc"
|
||||
"golang.org/x/oauth2"
|
||||
)
|
||||
|
||||
// OIDCProvider provides a standard, OpenID Connect implementation
|
||||
// of an authorization identity provider.
|
||||
// https://openid.net/specs/openid-connect-core-1_0.html
|
||||
type OIDCProvider struct {
|
||||
*Provider
|
||||
}
|
||||
|
||||
// NewOIDCProvider creates a new instance of an OpenID Connect provider.
|
||||
func NewOIDCProvider(p *Provider) (*OIDCProvider, error) {
|
||||
ctx := context.Background()
|
||||
if p.ProviderURL == "" {
|
||||
return nil, ErrMissingProviderURL
|
||||
}
|
||||
var err error
|
||||
p.provider, err = oidc.NewProvider(ctx, p.ProviderURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(p.Scopes) == 0 {
|
||||
p.Scopes = []string{oidc.ScopeOpenID, "profile", "email", "offline_access"}
|
||||
}
|
||||
p.verifier = p.provider.Verifier(&oidc.Config{ClientID: p.ClientID})
|
||||
p.oauth = &oauth2.Config{
|
||||
ClientID: p.ClientID,
|
||||
ClientSecret: p.ClientSecret,
|
||||
Endpoint: p.provider.Endpoint(),
|
||||
RedirectURL: p.RedirectURL.String(),
|
||||
Scopes: p.Scopes,
|
||||
}
|
||||
return &OIDCProvider{Provider: p}, nil
|
||||
}
|
138
internal/identity/okta.go
Normal file
138
internal/identity/okta.go
Normal file
|
@ -0,0 +1,138 @@
|
|||
package identity // import "github.com/pomerium/pomerium/internal/identity"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
oidc "github.com/pomerium/go-oidc"
|
||||
"golang.org/x/oauth2"
|
||||
|
||||
"github.com/pomerium/pomerium/internal/httputil"
|
||||
"github.com/pomerium/pomerium/internal/log"
|
||||
"github.com/pomerium/pomerium/internal/sessions"
|
||||
"github.com/pomerium/pomerium/internal/version"
|
||||
)
|
||||
|
||||
// OktaProvider represents the Okta Identity Provider
|
||||
//
|
||||
// https://www.pomerium.io/docs/identity-providers.html#okta
|
||||
type OktaProvider struct {
|
||||
*Provider
|
||||
|
||||
RevokeURL *url.URL
|
||||
}
|
||||
|
||||
// NewOktaProvider creates a new instance of Okta as an identity provider.
|
||||
func NewOktaProvider(p *Provider) (*OktaProvider, error) {
|
||||
ctx := context.Background()
|
||||
if p.ProviderURL == "" {
|
||||
return nil, ErrMissingProviderURL
|
||||
}
|
||||
var err error
|
||||
p.provider, err = oidc.NewProvider(ctx, p.ProviderURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(p.Scopes) == 0 {
|
||||
p.Scopes = []string{oidc.ScopeOpenID, "profile", "email", "groups", "offline_access"}
|
||||
}
|
||||
p.verifier = p.provider.Verifier(&oidc.Config{ClientID: p.ClientID})
|
||||
p.oauth = &oauth2.Config{
|
||||
ClientID: p.ClientID,
|
||||
ClientSecret: p.ClientSecret,
|
||||
Endpoint: p.provider.Endpoint(),
|
||||
RedirectURL: p.RedirectURL.String(),
|
||||
Scopes: p.Scopes,
|
||||
}
|
||||
|
||||
// okta supports a revocation endpoint
|
||||
var claims struct {
|
||||
RevokeURL string `json:"revocation_endpoint"`
|
||||
}
|
||||
if err := p.provider.Claims(&claims); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
oktaProvider := OktaProvider{Provider: p}
|
||||
|
||||
oktaProvider.RevokeURL, err = url.Parse(claims.RevokeURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &oktaProvider, nil
|
||||
}
|
||||
|
||||
// Revoke revokes the access token a given session state.
|
||||
// https://developer.okta.com/docs/api/resources/oidc#revoke
|
||||
func (p *OktaProvider) Revoke(token string) error {
|
||||
params := url.Values{}
|
||||
params.Add("client_id", p.ClientID)
|
||||
params.Add("client_secret", p.ClientSecret)
|
||||
params.Add("token", token)
|
||||
params.Add("token_type_hint", "refresh_token")
|
||||
err := httputil.Client(http.MethodPost, p.RevokeURL.String(), version.UserAgent(), nil, params, nil)
|
||||
if err != nil && err != httputil.ErrTokenRevoked {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSignInURL returns the sign in url with typical oauth parameters
|
||||
// Google requires access type offline
|
||||
func (p *OktaProvider) GetSignInURL(state string) string {
|
||||
return p.oauth.AuthCodeURL(state, oauth2.AccessTypeOffline)
|
||||
}
|
||||
|
||||
type accessToken struct {
|
||||
Subject string `json:"sub"`
|
||||
Groups []string `json:"groups"`
|
||||
}
|
||||
|
||||
// Refresh renews a user's session using an oid refresh token without reprompting the user.
|
||||
// Group membership is also refreshed. If configured properly, Okta is we can configure the access token
|
||||
// to include group membership claims which allows us to avoid a follow up oauth2 call.
|
||||
func (p *OktaProvider) Refresh(ctx context.Context, s *sessions.SessionState) (*sessions.SessionState, error) {
|
||||
if s.RefreshToken == "" {
|
||||
return nil, errors.New("identity/okta: missing refresh token")
|
||||
}
|
||||
t := oauth2.Token{RefreshToken: s.RefreshToken}
|
||||
newToken, err := p.oauth.TokenSource(ctx, &t).Token()
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("identity/okta: refresh failed")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
payload, err := parseJWT(newToken.AccessToken)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("identity/okta: malformed access token jwt: %v", err)
|
||||
}
|
||||
var token accessToken
|
||||
if err := json.Unmarshal(payload, &token); err != nil {
|
||||
return nil, fmt.Errorf("identity/okta: failed to unmarshal access token claims: %v", err)
|
||||
}
|
||||
if len(token.Groups) != 0 {
|
||||
s.Groups = token.Groups
|
||||
}
|
||||
|
||||
s.AccessToken = newToken.AccessToken
|
||||
s.RefreshDeadline = newToken.Expiry.Truncate(time.Second)
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func parseJWT(p string) ([]byte, error) {
|
||||
parts := strings.Split(p, ".")
|
||||
if len(parts) < 2 {
|
||||
return nil, fmt.Errorf("oidc: malformed jwt, expected 3 parts got %d", len(parts))
|
||||
}
|
||||
payload, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("oidc: malformed jwt payload: %v", err)
|
||||
}
|
||||
return payload, nil
|
||||
}
|
142
internal/identity/onelogin.go
Normal file
142
internal/identity/onelogin.go
Normal file
|
@ -0,0 +1,142 @@
|
|||
package identity // import "github.com/pomerium/pomerium/internal/identity"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
oidc "github.com/pomerium/go-oidc"
|
||||
"golang.org/x/oauth2"
|
||||
|
||||
"github.com/pomerium/pomerium/internal/httputil"
|
||||
"github.com/pomerium/pomerium/internal/log"
|
||||
"github.com/pomerium/pomerium/internal/sessions"
|
||||
"github.com/pomerium/pomerium/internal/version"
|
||||
)
|
||||
|
||||
// OneLoginProvider provides a standard, OpenID Connect implementation
|
||||
// of an authorization identity provider.
|
||||
type OneLoginProvider struct {
|
||||
*Provider
|
||||
|
||||
// non-standard oidc fields
|
||||
RevokeURL *url.URL
|
||||
AdminCreds *credentialsFile
|
||||
}
|
||||
|
||||
const defaultOneLoginProviderURL = "https://openid-connect.onelogin.com/oidc"
|
||||
|
||||
// NewOneLoginProvider creates a new instance of an OpenID Connect provider.
|
||||
func NewOneLoginProvider(p *Provider) (*OneLoginProvider, error) {
|
||||
ctx := context.Background()
|
||||
if p.ProviderURL == "" {
|
||||
p.ProviderURL = defaultOneLoginProviderURL
|
||||
}
|
||||
var err error
|
||||
p.provider, err = oidc.NewProvider(ctx, p.ProviderURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(p.Scopes) == 0 {
|
||||
p.Scopes = []string{oidc.ScopeOpenID, "profile", "email", "groups", "offline_access"}
|
||||
}
|
||||
p.verifier = p.provider.Verifier(&oidc.Config{ClientID: p.ClientID})
|
||||
p.oauth = &oauth2.Config{
|
||||
ClientID: p.ClientID,
|
||||
ClientSecret: p.ClientSecret,
|
||||
Endpoint: p.provider.Endpoint(),
|
||||
RedirectURL: p.RedirectURL.String(),
|
||||
Scopes: p.Scopes,
|
||||
}
|
||||
|
||||
// okta supports a revocation endpoint
|
||||
var claims struct {
|
||||
RevokeURL string `json:"revocation_endpoint"`
|
||||
}
|
||||
if err := p.provider.Claims(&claims); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
OneLoginProvider := OneLoginProvider{Provider: p}
|
||||
|
||||
OneLoginProvider.RevokeURL, err = url.Parse(claims.RevokeURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &OneLoginProvider, nil
|
||||
}
|
||||
|
||||
// Revoke revokes the access token a given session state.
|
||||
// https://developers.onelogin.com/openid-connect/api/revoke-session
|
||||
func (p *OneLoginProvider) Revoke(token string) error {
|
||||
params := url.Values{}
|
||||
params.Add("client_id", p.ClientID)
|
||||
params.Add("client_secret", p.ClientSecret)
|
||||
params.Add("token", token)
|
||||
params.Add("token_type_hint", "access_token")
|
||||
err := httputil.Client("POST", p.RevokeURL.String(), version.UserAgent(), nil, params, nil)
|
||||
if err != nil && err != httputil.ErrTokenRevoked {
|
||||
log.Error().Err(err).Msg("authenticate/providers: failed to revoke session")
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSignInURL returns the sign in url with typical oauth parameters
|
||||
func (p *OneLoginProvider) GetSignInURL(state string) string {
|
||||
return p.oauth.AuthCodeURL(state, oauth2.AccessTypeOffline)
|
||||
}
|
||||
|
||||
// Refresh renews a user's session using an oid refresh token without reprompting the user.
|
||||
// Group membership is also refreshed.
|
||||
// https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens
|
||||
func (p *OneLoginProvider) Refresh(ctx context.Context, s *sessions.SessionState) (*sessions.SessionState, error) {
|
||||
if s.RefreshToken == "" {
|
||||
return nil, errors.New("identity/microsoft: missing refresh token")
|
||||
}
|
||||
t := oauth2.Token{RefreshToken: s.RefreshToken}
|
||||
newToken, err := p.oauth.TokenSource(ctx, &t).Token()
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("identity/microsoft: refresh failed")
|
||||
return nil, err
|
||||
}
|
||||
s.AccessToken = newToken.AccessToken
|
||||
s.RefreshDeadline = newToken.Expiry.Truncate(time.Second)
|
||||
s.Groups, err = p.UserGroups(ctx, s.AccessToken)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("identity/microsoft: refresh failed")
|
||||
return nil, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
const defaultOneloginGroupURL = "https://openid-connect.onelogin.com/oidc/me"
|
||||
|
||||
// UserGroups returns a slice of group names a given user is in.
|
||||
// https://developers.onelogin.com/openid-connect/api/user-info
|
||||
func (p *OneLoginProvider) UserGroups(ctx context.Context, accessToken string) ([]string, error) {
|
||||
var response struct {
|
||||
User string `json:"sub"`
|
||||
Email string `json:"email"`
|
||||
PreferredUsername string `json:"preferred_username"`
|
||||
Name string `json:"name"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
GivenName string `json:"given_name"`
|
||||
FamilyName string `json:"family_name"`
|
||||
Groups []string `json:"groups"`
|
||||
}
|
||||
headers := map[string]string{"Authorization": fmt.Sprintf("Bearer %s", accessToken)}
|
||||
err := httputil.Client(http.MethodGet, defaultOneloginGroupURL, version.UserAgent(), headers, nil, &response)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var groups []string
|
||||
for _, group := range response.Groups {
|
||||
log.Info().Str("ID", group).Msg("identity/onelogin: group")
|
||||
groups = append(groups, group)
|
||||
}
|
||||
return groups, nil
|
||||
}
|
194
internal/identity/providers.go
Normal file
194
internal/identity/providers.go
Normal file
|
@ -0,0 +1,194 @@
|
|||
//go:generate protoc -I ../../proto/authenticate --go_out=plugins=grpc:../../proto/authenticate ../../proto/authenticate/authenticate.proto
|
||||
|
||||
// Package identity provides support for making OpenID Connect and OAuth2 authorized and
|
||||
// authenticated HTTP requests with third party identity providers.
|
||||
package identity // import "github.com/pomerium/pomerium/internal/identity"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
oidc "github.com/pomerium/go-oidc"
|
||||
"golang.org/x/oauth2"
|
||||
|
||||
"github.com/pomerium/pomerium/internal/log"
|
||||
"github.com/pomerium/pomerium/internal/sessions"
|
||||
)
|
||||
|
||||
const (
|
||||
// AzureProviderName identifies the Azure identity provider
|
||||
AzureProviderName = "azure"
|
||||
// GitlabProviderName identifies the GitLab identity provider
|
||||
GitlabProviderName = "gitlab"
|
||||
// GoogleProviderName identifies the Google identity provider
|
||||
GoogleProviderName = "google"
|
||||
// OIDCProviderName identifies a generic OpenID connect provider
|
||||
OIDCProviderName = "oidc"
|
||||
// OktaProviderName identifies the Okta identity provider
|
||||
OktaProviderName = "okta"
|
||||
// OneLoginProviderName identifies the OneLogin identity provider
|
||||
OneLoginProviderName = "onelogin"
|
||||
)
|
||||
|
||||
// ErrMissingProviderURL is returned when an identity provider requires a provider url
|
||||
// does not receive one.
|
||||
var ErrMissingProviderURL = errors.New("identity: missing provider url")
|
||||
|
||||
// UserGrouper is an interface representing the ability to retrieve group membership information
|
||||
// from an identity provider
|
||||
type UserGrouper interface {
|
||||
// UserGroups returns a slice of group names a given user is in
|
||||
UserGroups(context.Context, string) ([]string, error)
|
||||
}
|
||||
|
||||
// Authenticator is an interface representing the ability to authenticate with an identity provider.
|
||||
type Authenticator interface {
|
||||
Authenticate(string) (*sessions.SessionState, error)
|
||||
Validate(context.Context, string) (bool, error)
|
||||
Refresh(context.Context, *sessions.SessionState) (*sessions.SessionState, error)
|
||||
Revoke(string) error
|
||||
GetSignInURL(state string) string
|
||||
}
|
||||
|
||||
// New returns a new identity provider based given its name.
|
||||
// Returns an error if selected provided not found or if the identity provider is not known.
|
||||
func New(providerName string, p *Provider) (a Authenticator, err error) {
|
||||
switch providerName {
|
||||
case AzureProviderName:
|
||||
a, err = NewAzureProvider(p)
|
||||
case GitlabProviderName:
|
||||
return nil, fmt.Errorf("identity: %s currently not supported", providerName)
|
||||
case GoogleProviderName:
|
||||
a, err = NewGoogleProvider(p)
|
||||
case OIDCProviderName:
|
||||
a, err = NewOIDCProvider(p)
|
||||
case OktaProviderName:
|
||||
a, err = NewOktaProvider(p)
|
||||
case OneLoginProviderName:
|
||||
a, err = NewOneLoginProvider(p)
|
||||
default:
|
||||
return nil, fmt.Errorf("identity: %s provider not known", providerName)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// Provider contains the fields required for an OAuth 2.0 Authorization Request that
|
||||
// requests that the End-User be authenticated by the Authorization Server.
|
||||
// https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest
|
||||
type Provider struct {
|
||||
ProviderName string
|
||||
|
||||
RedirectURL *url.URL
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
ProviderURL string
|
||||
Scopes []string
|
||||
SessionLifetimeTTL time.Duration
|
||||
|
||||
// Some providers, such as google, require additional remote api calls to retrieve
|
||||
// user details like groups. Provider is responsible for parsing.
|
||||
ServiceAccount string
|
||||
|
||||
provider *oidc.Provider
|
||||
verifier *oidc.IDTokenVerifier
|
||||
oauth *oauth2.Config
|
||||
}
|
||||
|
||||
// GetSignInURL returns a URL to OAuth 2.0 provider's consent page
|
||||
// that asks for permissions for the required scopes explicitly.
|
||||
//
|
||||
// State is a token to protect the user from CSRF attacks. You must
|
||||
// always provide a non-empty string and validate that it matches the
|
||||
// the state query parameter on your redirect callback.
|
||||
// See http://tools.ietf.org/html/rfc6749#section-10.12 for more info.
|
||||
func (p *Provider) GetSignInURL(state string) string {
|
||||
return p.oauth.AuthCodeURL(state, oauth2.AccessTypeOffline)
|
||||
}
|
||||
|
||||
// Validate validates a given session's from it's JWT token
|
||||
// The function verifies it's been signed by the provider, preforms
|
||||
// any additional checks depending on the Config, and returns the payload.
|
||||
//
|
||||
// Validate does NOT do nonce validation.
|
||||
// Validate does NOT check if revoked.
|
||||
// https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
|
||||
func (p *Provider) Validate(ctx context.Context, idToken string) (bool, error) {
|
||||
_, err := p.verifier.Verify(ctx, idToken)
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("identity: failed to verify session state")
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Authenticate creates a session with an identity provider from a authorization code
|
||||
func (p *Provider) Authenticate(code string) (*sessions.SessionState, error) {
|
||||
ctx := context.Background()
|
||||
// convert authorization code into a token
|
||||
oauth2Token, err := p.oauth.Exchange(ctx, code)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("identity: failed token exchange: %v", err)
|
||||
}
|
||||
//id_token contains claims about the authenticated user
|
||||
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("token response did not contain an id_token")
|
||||
}
|
||||
// Parse and verify ID Token payload.
|
||||
idToken, err := p.verifier.Verify(ctx, rawIDToken)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("identity: could not verify id_token: %v", err)
|
||||
}
|
||||
|
||||
// Extract id_token which contains claims about the authenticated user
|
||||
var claims struct {
|
||||
Email string `json:"email"`
|
||||
EmailVerified bool `json:"email_verified"`
|
||||
Groups []string `json:"groups"`
|
||||
}
|
||||
// parse claims from the raw, encoded jwt token
|
||||
if err := idToken.Claims(&claims); err != nil {
|
||||
return nil, fmt.Errorf("identity: failed to parse id_token claims: %v", err)
|
||||
}
|
||||
|
||||
return &sessions.SessionState{
|
||||
IDToken: rawIDToken,
|
||||
AccessToken: oauth2Token.AccessToken,
|
||||
RefreshToken: oauth2Token.RefreshToken,
|
||||
RefreshDeadline: oauth2Token.Expiry.Truncate(time.Second),
|
||||
LifetimeDeadline: sessions.ExtendDeadline(p.SessionLifetimeTTL),
|
||||
Email: claims.Email,
|
||||
User: idToken.Subject,
|
||||
Groups: claims.Groups,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Refresh renews a user's session using an oid refresh token without reprompting the user.
|
||||
// Group membership is also refreshed.
|
||||
// https://openid.net/specs/openid-connect-core-1_0.html#RefreshTokens
|
||||
func (p *Provider) Refresh(ctx context.Context, s *sessions.SessionState) (*sessions.SessionState, error) {
|
||||
if s.RefreshToken == "" {
|
||||
return nil, errors.New("identity: missing refresh token")
|
||||
}
|
||||
t := oauth2.Token{RefreshToken: s.RefreshToken}
|
||||
newToken, err := p.oauth.TokenSource(ctx, &t).Token()
|
||||
if err != nil {
|
||||
log.Error().Err(err).Msg("identity: refresh failed")
|
||||
return nil, err
|
||||
}
|
||||
s.AccessToken = newToken.AccessToken
|
||||
s.RefreshDeadline = newToken.Expiry.Truncate(time.Second)
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Revoke enables a user to revoke her token. If the identity provider supports revocation
|
||||
// the endpoint is available, otherwise an error is thrown.
|
||||
func (p *Provider) Revoke(token string) error {
|
||||
return fmt.Errorf("identity: revoke not implemented by %s", p.ProviderName)
|
||||
}
|
|
@ -15,7 +15,7 @@ var Logger = zerolog.New(os.Stdout).With().Timestamp().Logger()
|
|||
// SetDebugMode tells the logger to use standard out and pretty print output.
|
||||
func SetDebugMode() {
|
||||
Logger = Logger.Output(zerolog.ConsoleWriter{Out: os.Stdout})
|
||||
// zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
||||
zerolog.SetGlobalLevel(zerolog.InfoLevel)
|
||||
}
|
||||
|
||||
// With creates a child logger with the field added to its context.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue