added option to retrieve the OIDC user info from the id_token payload

This commit is contained in:
Gani Georgiev
2024-10-12 10:16:01 +03:00
parent 95d5ee40b0
commit 3c87df9e55
40 changed files with 465 additions and 218 deletions
+12 -100
View File
@@ -2,14 +2,8 @@ package auth
import (
"context"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"net/http"
"strings"
"github.com/golang-jwt/jwt/v4"
@@ -129,8 +123,6 @@ func (p *Apple) FetchRawUserInfo(token *oauth2.Token) ([]byte, error) {
return json.Marshal(claims)
}
// -------------------------------------------------------------------
func (p *Apple) parseAndVerifyIdToken(idToken string) (jwt.MapClaims, error) {
if idToken == "" {
return nil, errors.New("empty id_token")
@@ -146,6 +138,11 @@ func (p *Apple) parseAndVerifyIdToken(idToken string) (jwt.MapClaims, error) {
// validate common claims per https://developer.apple.com/documentation/sign_in_with_apple/sign_in_with_apple_rest_api/verifying_a_user#3383769
// ---
err = claims.Valid() // exp, iat, etc.
if err != nil {
return nil, err
}
if !claims.VerifyIssuer("https://appleid.apple.com", true) {
return nil, errors.New("iss must be https://appleid.apple.com")
}
@@ -154,102 +151,17 @@ func (p *Apple) parseAndVerifyIdToken(idToken string) (jwt.MapClaims, error) {
return nil, errors.New("aud must be the developer's client_id")
}
// fetch the public key set
// validate id_token signature
//
// note: this step could be technically considered optional because we trust
// the token which is a result of direct TLS communication with the provider
// (see also https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation)
// ---
kid, _ := t.Header["kid"].(string)
if kid == "" {
return nil, errors.New("missing kid header value")
}
key, err := p.fetchJWK(kid)
err = validateIdTokenSignature(p.ctx, idToken, p.jwksURL, kid)
if err != nil {
return nil, err
}
// decode the key params per RFC 7518 (https://tools.ietf.org/html/rfc7518#section-6.3)
// and construct a valid publicKey from them
// ---
exponent, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(key.E, "="))
if err != nil {
return nil, err
}
modulus, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(key.N, "="))
if err != nil {
return nil, err
}
publicKey := &rsa.PublicKey{
// https://tools.ietf.org/html/rfc7517#appendix-A.1
E: int(big.NewInt(0).SetBytes(exponent).Uint64()),
N: big.NewInt(0).SetBytes(modulus),
}
// verify the id_token
// ---
parser := jwt.NewParser(jwt.WithValidMethods([]string{key.Alg}))
parsedToken, err := parser.Parse(idToken, func(t *jwt.Token) (any, error) {
return publicKey, nil
})
if err != nil {
return nil, err
}
if claims, ok := parsedToken.Claims.(jwt.MapClaims); ok && parsedToken.Valid {
return claims, nil
}
return nil, errors.New("the parsed id_token is invalid")
}
type jwk struct {
Kty string
Kid string
Use string
Alg string
N string
E string
}
func (p *Apple) fetchJWK(kid string) (*jwk, error) {
req, err := http.NewRequestWithContext(p.ctx, "GET", p.jwksURL, nil)
if err != nil {
return nil, err
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
rawBody, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
// http.Client.Get doesn't treat non 2xx responses as error
if res.StatusCode >= 400 {
return nil, fmt.Errorf(
"failed to verify the provided id_token (%d):\n%s",
res.StatusCode,
string(rawBody),
)
}
jwks := struct {
Keys []*jwk
}{}
if err := json.Unmarshal(rawBody, &jwks); err != nil {
return nil, err
}
for _, key := range jwks.Keys {
if key.Kid == kid {
return key, nil
}
}
return nil, fmt.Errorf("jwk with kid %q was not found", kid)
return claims, nil
}
+7
View File
@@ -92,6 +92,13 @@ type Provider interface {
// SetUserInfoURL sets the provider's UserInfoURL.
SetUserInfoURL(url string)
// Extra returns a shallow copy of any custom config data
// that the provider may be need.
Extra() map[string]any
// SetExtra updates the provider's custom config data.
SetExtra(data map[string]any)
// Client returns an http client using the provided token.
Client(token *oauth2.Token) *http.Client
+12
View File
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"io"
"maps"
"net/http"
"golang.org/x/oauth2"
@@ -21,6 +22,7 @@ type BaseProvider struct {
userInfoURL string
scopes []string
pkce bool
extra map[string]any
}
// Context implements Provider.Context() interface method.
@@ -123,6 +125,16 @@ func (p *BaseProvider) SetUserInfoURL(url string) {
p.userInfoURL = url
}
// Extra implements Provider.Extra() interface method.
func (p *BaseProvider) Extra() map[string]any {
return maps.Clone(p.extra)
}
// SetExtra implements Provider.SetExtra() interface method.
func (p *BaseProvider) SetExtra(data map[string]any) {
p.extra = data
}
// BuildAuthURL implements Provider.BuildAuthURL() interface method.
func (p *BaseProvider) BuildAuthURL(state string, opts ...oauth2.AuthCodeOption) string {
return p.oauth2Config().AuthCodeURL(state, opts...)
+37
View File
@@ -1,7 +1,9 @@
package auth
import (
"bytes"
"context"
"encoding/json"
"testing"
"golang.org/x/oauth2"
@@ -167,6 +169,41 @@ func TestUserInfoURL(t *testing.T) {
}
}
func TestExtra(t *testing.T) {
b := BaseProvider{}
before := b.Extra()
if before != nil {
t.Fatalf("Expected extra to be empty, got %v", before)
}
extra := map[string]any{"a": 1, "b": 2}
b.SetExtra(extra)
after := b.Extra()
rawExtra, err := json.Marshal(extra)
if err != nil {
t.Fatal(err)
}
rawAfter, err := json.Marshal(after)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(rawExtra, rawAfter) {
t.Fatalf("Expected extra to be\n%s\ngot\n%s", rawExtra, rawAfter)
}
// ensure that it was shallow copied
after["b"] = 3
if d := b.Extra(); d["b"] != 2 {
t.Fatalf("Expected extra to remain unchanged, got\n%v", d)
}
}
func TestBuildAuthURL(t *testing.T) {
b := BaseProvider{
authURL: "authURL_test",
+1 -1
View File
@@ -90,7 +90,7 @@ func (p *Notion) FetchAuthUser(token *oauth2.Token) (*AuthUser, error) {
return user, nil
}
// FetchRawUserInfo implements Provider.FetchRawUserInfo interface.
// FetchRawUserInfo implements Provider.FetchRawUserInfo interface method.
//
// This differ from BaseProvider because Notion requires a version header for all requests
// (https://developers.notion.com/reference/versioning).
+190 -2
View File
@@ -2,9 +2,19 @@ package auth
import (
"context"
"crypto/rsa"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"net/http"
"strings"
"github.com/golang-jwt/jwt/v4"
"github.com/pocketbase/pocketbase/tools/types"
"github.com/spf13/cast"
"golang.org/x/oauth2"
)
@@ -20,6 +30,13 @@ var _ Provider = (*OIDC)(nil)
const NameOIDC string = "oidc"
// OIDC allows authentication via OpenID Connect (OIDC) OAuth2 provider.
//
// If specified the user data is fetched from the userInfoURL.
// Otherwise - from the id_token payload.
//
// The provider support the following Extra config options:
// - "jwksURL" - url to the keys to validate the id_token signature (optional and used only when reading the user data from the id_token)
// - "issuers" - list of valid issuers for the iss id_token claim (optioanl and used only when reading the user data from the id_token)
type OIDC struct {
BaseProvider
}
@@ -41,8 +58,6 @@ func NewOIDCProvider() *OIDC {
// FetchAuthUser returns an AuthUser instance based the provider's user api.
//
// API reference: https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims
//
// @todo consider adding support for reading the user data from the id_token.
func (p *OIDC) FetchAuthUser(token *oauth2.Token) (*AuthUser, error) {
data, err := p.FetchRawUserInfo(token)
if err != nil {
@@ -84,3 +99,176 @@ func (p *OIDC) FetchAuthUser(token *oauth2.Token) (*AuthUser, error) {
return user, nil
}
// FetchRawUserInfo implements Provider.FetchRawUserInfo interface method.
//
// It either fetch the data from p.userInfoURL, or if not set - returns the id_token claims.
func (p *OIDC) FetchRawUserInfo(token *oauth2.Token) ([]byte, error) {
if p.userInfoURL != "" {
return p.BaseProvider.FetchRawUserInfo(token)
}
claims, err := p.parseIdToken(token)
if err != nil {
return nil, err
}
return json.Marshal(claims)
}
func (p *OIDC) parseIdToken(token *oauth2.Token) (jwt.MapClaims, error) {
idToken := token.Extra("id_token").(string)
if idToken == "" {
return nil, errors.New("empty id_token")
}
claims := jwt.MapClaims{}
t, _, err := jwt.NewParser().ParseUnverified(idToken, claims)
if err != nil {
return nil, err
}
// validate common claims like exp, iat, etc.
err = claims.Valid()
if err != nil {
return nil, err
}
// validate aud
if !claims.VerifyAudience(p.clientId, true) {
return nil, errors.New("aud must be the developer's client_id")
}
// validate iss (if "issuers" extra config is set)
issuers := cast.ToStringSlice(p.Extra()["issuers"])
if len(issuers) > 0 {
var isIssValid bool
for _, issuer := range issuers {
if claims.VerifyIssuer(issuer, true) {
isIssValid = true
break
}
}
if !isIssValid {
return nil, fmt.Errorf("iss must be one of %v, got %#v", issuers, claims["iss"])
}
}
// validate signature (if "jwksURL" extra config is set)
//
// note: this step could be technically considered optional because we trust
// the token which is a result of direct TLS communication with the provider
// (see also https://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation)
jwksURL := cast.ToString(p.Extra()["jwksURL"])
if jwksURL != "" {
kid, _ := t.Header["kid"].(string)
err = validateIdTokenSignature(p.ctx, idToken, jwksURL, kid)
if err != nil {
return nil, err
}
}
return claims, nil
}
func validateIdTokenSignature(ctx context.Context, idToken string, jwksURL string, kid string) error {
// fetch the public key set
// ---
if kid == "" {
return errors.New("missing kid header value")
}
key, err := fetchJWK(ctx, jwksURL, kid)
if err != nil {
return err
}
// decode the key params per RFC 7518 (https://tools.ietf.org/html/rfc7518#section-6.3)
// and construct a valid publicKey from them
// ---
exponent, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(key.E, "="))
if err != nil {
return err
}
modulus, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(key.N, "="))
if err != nil {
return err
}
publicKey := &rsa.PublicKey{
// https://tools.ietf.org/html/rfc7517#appendix-A.1
E: int(big.NewInt(0).SetBytes(exponent).Uint64()),
N: big.NewInt(0).SetBytes(modulus),
}
// verify the signiture
// ---
parser := jwt.NewParser(jwt.WithValidMethods([]string{key.Alg}))
parsedToken, err := parser.Parse(idToken, func(t *jwt.Token) (any, error) {
return publicKey, nil
})
if err != nil {
return err
}
if !parsedToken.Valid {
return errors.New("the parsed id_token is invalid")
}
return nil
}
type jwk struct {
Kty string
Kid string
Use string
Alg string
N string
E string
}
func fetchJWK(ctx context.Context, jwksURL string, kid string) (*jwk, error) {
req, err := http.NewRequestWithContext(ctx, "GET", jwksURL, nil)
if err != nil {
return nil, err
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
rawBody, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
// http.Client.Get doesn't treat non 2xx responses as error
if res.StatusCode >= 400 {
return nil, fmt.Errorf(
"failed to verify the provided id_token (%d):\n%s",
res.StatusCode,
string(rawBody),
)
}
jwks := struct {
Keys []*jwk
}{}
if err := json.Unmarshal(rawBody, &jwks); err != nil {
return nil, err
}
for _, key := range jwks.Keys {
if key.Kid == kid {
return key, nil
}
}
return nil, fmt.Errorf("jwk with kid %q was not found", kid)
}
+1 -1
View File
@@ -85,7 +85,7 @@ func (p *Twitch) FetchAuthUser(token *oauth2.Token) (*AuthUser, error) {
return user, nil
}
// FetchRawUserInfo implements Provider.FetchRawUserInfo interface.
// FetchRawUserInfo implements Provider.FetchRawUserInfo interface method.
//
// This differ from BaseProvider because Twitch requires the Client-Id header.
func (p *Twitch) FetchRawUserInfo(token *oauth2.Token) ([]byte, error) {