|
| 1 | +package provider |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/rsa" |
| 6 | + "crypto/sha256" |
| 7 | + "encoding/base64" |
| 8 | + "encoding/json" |
| 9 | + "fmt" |
| 10 | + "net/http" |
| 11 | + |
| 12 | + "github.com/dgrijalva/jwt-go" |
| 13 | + "github.com/lestrrat-go/jwx/jwk" |
| 14 | + "github.com/netlify/gotrue/conf" |
| 15 | + "golang.org/x/oauth2" |
| 16 | +) |
| 17 | + |
| 18 | +const ( |
| 19 | + authEndpoint = "https://appleid.apple.com/auth/authorize" |
| 20 | + tokenEndpoint = "https://appleid.apple.com/auth/token" |
| 21 | + |
| 22 | + ScopeEmail = "email" |
| 23 | + ScopeName = "name" |
| 24 | + |
| 25 | + appleAudOrIss = "https://appleid.apple.com" |
| 26 | + idTokenVerificationKeyEndpoint = "https://appleid.apple.com/auth/keys" |
| 27 | +) |
| 28 | + |
| 29 | +type AppleProvider struct { |
| 30 | + *oauth2.Config |
| 31 | + APIPath string |
| 32 | + httpClient *http.Client |
| 33 | +} |
| 34 | + |
| 35 | +type appleName struct { |
| 36 | + FirstName string `json:"firstName"` |
| 37 | + LastName string `json:"lastName"` |
| 38 | +} |
| 39 | + |
| 40 | +type appleUser struct { |
| 41 | + Name appleName `json:"name"` |
| 42 | + Email string `json:"email"` |
| 43 | +} |
| 44 | + |
| 45 | +type idTokenClaims struct { |
| 46 | + jwt.StandardClaims |
| 47 | + AccessTokenHash string `json:"at_hash"` |
| 48 | + AuthTime int `json:"auth_time"` |
| 49 | + Email string `json:"email"` |
| 50 | + IsPrivateEmail bool `json:"is_private_email,string"` |
| 51 | +} |
| 52 | + |
| 53 | +func NewAppleProvider(ext conf.OAuthProviderConfiguration) (OAuthProvider, error) { |
| 54 | + if err := ext.Validate(); err != nil { |
| 55 | + return nil, err |
| 56 | + } |
| 57 | + |
| 58 | + return &AppleProvider{ |
| 59 | + Config: &oauth2.Config{ |
| 60 | + ClientID: ext.ClientID, |
| 61 | + ClientSecret: ext.Secret, |
| 62 | + Endpoint: oauth2.Endpoint{ |
| 63 | + AuthURL: authEndpoint, |
| 64 | + TokenURL: tokenEndpoint, |
| 65 | + }, |
| 66 | + Scopes: []string{ |
| 67 | + ScopeEmail, |
| 68 | + ScopeName, |
| 69 | + }, |
| 70 | + RedirectURL: ext.RedirectURI, |
| 71 | + }, |
| 72 | + APIPath: "", |
| 73 | + }, nil |
| 74 | +} |
| 75 | + |
| 76 | +func (p AppleProvider) GetOAuthToken(code string) (*oauth2.Token, error) { |
| 77 | + opts := []oauth2.AuthCodeOption{ |
| 78 | + oauth2.SetAuthURLParam("client_id", p.ClientID), |
| 79 | + oauth2.SetAuthURLParam("secret", p.ClientSecret), |
| 80 | + } |
| 81 | + return p.Exchange(oauth2.NoContext, code, opts...) |
| 82 | +} |
| 83 | + |
| 84 | +func (p AppleProvider) GetUserData(ctx context.Context, tok *oauth2.Token) (*UserProvidedData, error) { |
| 85 | + var user *UserProvidedData |
| 86 | + if tok.AccessToken == "" { |
| 87 | + return &UserProvidedData{}, nil |
| 88 | + } |
| 89 | + if idToken := tok.Extra("id_token"); idToken != nil { |
| 90 | + idToken, err := jwt.ParseWithClaims(idToken.(string), &idTokenClaims{}, func(t *jwt.Token) (interface{}, error) { |
| 91 | + kid := t.Header["kid"].(string) |
| 92 | + claims := t.Claims.(*idTokenClaims) |
| 93 | + vErr := new(jwt.ValidationError) |
| 94 | + if !claims.VerifyAudience(p.ClientID, true) { |
| 95 | + vErr.Inner = fmt.Errorf("incorrect audience") |
| 96 | + vErr.Errors |= jwt.ValidationErrorAudience |
| 97 | + } |
| 98 | + if !claims.VerifyIssuer(appleAudOrIss, true) { |
| 99 | + vErr.Inner = fmt.Errorf("incorrect issuer") |
| 100 | + vErr.Errors |= jwt.ValidationErrorIssuer |
| 101 | + } |
| 102 | + if vErr.Errors > 0 { |
| 103 | + return nil, vErr |
| 104 | + } |
| 105 | + |
| 106 | + // per OpenID Connect Core 1.0 §3.2.2.9, Access Token Validation |
| 107 | + hash := sha256.Sum256([]byte(tok.AccessToken)) |
| 108 | + halfHash := hash[0:(len(hash) / 2)] |
| 109 | + encodedHalfHash := base64.RawURLEncoding.EncodeToString(halfHash) |
| 110 | + if encodedHalfHash != claims.AccessTokenHash { |
| 111 | + vErr.Inner = fmt.Errorf(`invalid identity token`) |
| 112 | + vErr.Errors |= jwt.ValidationErrorClaimsInvalid |
| 113 | + return nil, vErr |
| 114 | + } |
| 115 | + |
| 116 | + // get the public key for verifying the identity token signature |
| 117 | + set, err := jwk.FetchHTTP(idTokenVerificationKeyEndpoint, jwk.WithHTTPClient(http.DefaultClient)) |
| 118 | + if err != nil { |
| 119 | + return nil, err |
| 120 | + } |
| 121 | + selectedKey := set.Keys[0] |
| 122 | + for _, key := range set.Keys { |
| 123 | + if key.KeyID() == kid { |
| 124 | + selectedKey = key |
| 125 | + break |
| 126 | + } |
| 127 | + } |
| 128 | + pubKeyIface, _ := selectedKey.Materialize() |
| 129 | + pubKey, ok := pubKeyIface.(*rsa.PublicKey) |
| 130 | + if !ok { |
| 131 | + return nil, fmt.Errorf(`expected RSA public key from %s`, idTokenVerificationKeyEndpoint) |
| 132 | + } |
| 133 | + return pubKey, nil |
| 134 | + }) |
| 135 | + if err != nil { |
| 136 | + return &UserProvidedData{}, err |
| 137 | + } |
| 138 | + user = &UserProvidedData{ |
| 139 | + Emails: []Email{{ |
| 140 | + Email: idToken.Claims.(*idTokenClaims).Email, |
| 141 | + Verified: true, |
| 142 | + Primary: true, |
| 143 | + }}, |
| 144 | + } |
| 145 | + |
| 146 | + } |
| 147 | + return user, nil |
| 148 | +} |
| 149 | + |
| 150 | +func (p AppleProvider) ParseUser(data string) map[string]string { |
| 151 | + userData := &appleUser{} |
| 152 | + err := json.Unmarshal([]byte(data), userData) |
| 153 | + if err != nil { |
| 154 | + return nil |
| 155 | + } |
| 156 | + return map[string]string{ |
| 157 | + "firstName": userData.Name.FirstName, |
| 158 | + "lastName": userData.Name.LastName, |
| 159 | + "email": userData.Email, |
| 160 | + } |
| 161 | +} |
0 commit comments