|
| 1 | +package cognito |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "io/ioutil" |
| 9 | + "net/http" |
| 10 | + |
| 11 | + "github.com/markbates/goth" |
| 12 | + "golang.org/x/oauth2" |
| 13 | +) |
| 14 | + |
| 15 | +// Provider is the implementation of `goth.Provider` for accessing AWS Cognito. |
| 16 | +// New takes 3 parameters all from the Cognito console: |
| 17 | +// - The client ID |
| 18 | +// - The client secret |
| 19 | +// - The base URL for your service, either a custom domain or cognito pool based URL |
| 20 | +// You need to ensure that the source login URL is whitelisted as a login page in the client configuration in the cognito console. |
| 21 | +// GOTH does not provide a full token logout, to do that you need to do it in your code. |
| 22 | +// If you do not perform a full logout their existing token will be used on a login and the user won't be prompted to login until after expiry. |
| 23 | +// To perform a logout |
| 24 | +// - Destroy your session (or however else you handle the logout internally) |
| 25 | +// - redirect to https://CUSTOM_DOMAIN.auth.us-east-1.amazoncognito.com/logout?client_id=clinet_id&logout_uri=http://localhost:8080/ |
| 26 | +// (or whatever your login/start page is). |
| 27 | +// - Note that this page needs to be white-labeled as a logout page in the cognito console as well. |
| 28 | + |
| 29 | +// This is based upon the implementation for okta |
| 30 | + |
| 31 | +type Provider struct { |
| 32 | + ClientKey string |
| 33 | + Secret string |
| 34 | + CallbackURL string |
| 35 | + HTTPClient *http.Client |
| 36 | + config *oauth2.Config |
| 37 | + providerName string |
| 38 | + issuerURL string |
| 39 | + profileURL string |
| 40 | +} |
| 41 | + |
| 42 | +// New creates a new AWS Cognito provider and sets up important connection details. |
| 43 | +// You should always call `cognito.New` to get a new provider. Never try to |
| 44 | +// create one manually. |
| 45 | +func New(clientID, secret, baseUrl, callbackURL string, scopes ...string) *Provider { |
| 46 | + issuerURL := baseUrl + "/oauth2/default" |
| 47 | + authURL := baseUrl + "/oauth2/authorize" |
| 48 | + tokenURL := baseUrl + "/oauth2/token" |
| 49 | + profileURL := baseUrl + "/oauth2/userInfo" |
| 50 | + return NewCustomisedURL(clientID, secret, callbackURL, authURL, tokenURL, issuerURL, profileURL, scopes...) |
| 51 | +} |
| 52 | + |
| 53 | +// NewCustomisedURL is similar to New(...) but can be used to set custom URLs to connect to |
| 54 | +func NewCustomisedURL(clientID, secret, callbackURL, authURL, tokenURL, issuerURL, profileURL string, scopes ...string) *Provider { |
| 55 | + p := &Provider{ |
| 56 | + ClientKey: clientID, |
| 57 | + Secret: secret, |
| 58 | + CallbackURL: callbackURL, |
| 59 | + providerName: "cognito", |
| 60 | + issuerURL: issuerURL, |
| 61 | + profileURL: profileURL, |
| 62 | + } |
| 63 | + p.config = newConfig(p, authURL, tokenURL, scopes) |
| 64 | + return p |
| 65 | +} |
| 66 | + |
| 67 | +// Name is the name used to retrieve this provider later. |
| 68 | +func (p *Provider) Name() string { |
| 69 | + return p.providerName |
| 70 | +} |
| 71 | + |
| 72 | +// SetName is to update the name of the provider (needed in case of multiple providers of 1 type) |
| 73 | +func (p *Provider) SetName(name string) { |
| 74 | + p.providerName = name |
| 75 | +} |
| 76 | + |
| 77 | +func (p *Provider) Client() *http.Client { |
| 78 | + return goth.HTTPClientWithFallBack(p.HTTPClient) |
| 79 | +} |
| 80 | + |
| 81 | +// Debug is a no-op for the aws package. |
| 82 | +func (p *Provider) Debug(debug bool) { |
| 83 | + if debug { |
| 84 | + fmt.Println("WARNING: Debug request for goth/providers/cognito but no debug is available") |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +// BeginAuth asks AWS for an authentication end-point. |
| 89 | +func (p *Provider) BeginAuth(state string) (goth.Session, error) { |
| 90 | + return &Session{ |
| 91 | + AuthURL: p.config.AuthCodeURL(state), |
| 92 | + }, nil |
| 93 | +} |
| 94 | + |
| 95 | +// FetchUser will go to aws and access basic information about the user. |
| 96 | +func (p *Provider) FetchUser(session goth.Session) (goth.User, error) { |
| 97 | + sess := session.(*Session) |
| 98 | + user := goth.User{ |
| 99 | + AccessToken: sess.AccessToken, |
| 100 | + Provider: p.Name(), |
| 101 | + RefreshToken: sess.RefreshToken, |
| 102 | + ExpiresAt: sess.ExpiresAt, |
| 103 | + UserID: sess.UserID, |
| 104 | + } |
| 105 | + |
| 106 | + if user.AccessToken == "" { |
| 107 | + // data is not yet retrieved since accessToken is still empty |
| 108 | + return user, fmt.Errorf("%s cannot get user information without accessToken", p.providerName) |
| 109 | + } |
| 110 | + |
| 111 | + req, err := http.NewRequest("GET", p.profileURL, nil) |
| 112 | + if err != nil { |
| 113 | + return user, err |
| 114 | + } |
| 115 | + req.Header.Set("Authorization", "Bearer "+sess.AccessToken) |
| 116 | + response, err := p.Client().Do(req) |
| 117 | + if err != nil { |
| 118 | + if response != nil { |
| 119 | + _ = response.Body.Close() |
| 120 | + } |
| 121 | + return user, err |
| 122 | + } |
| 123 | + defer func(Body io.ReadCloser) { |
| 124 | + _ = Body.Close() |
| 125 | + }(response.Body) |
| 126 | + |
| 127 | + if response.StatusCode != http.StatusOK { |
| 128 | + return user, fmt.Errorf("%s responded with a %d trying to fetch user information", p.providerName, response.StatusCode) |
| 129 | + } |
| 130 | + |
| 131 | + bits, err := ioutil.ReadAll(response.Body) |
| 132 | + if err != nil { |
| 133 | + return user, err |
| 134 | + } |
| 135 | + |
| 136 | + err = json.NewDecoder(bytes.NewReader(bits)).Decode(&user.RawData) |
| 137 | + if err != nil { |
| 138 | + return user, err |
| 139 | + } |
| 140 | + |
| 141 | + err = userFromReader(bytes.NewReader(bits), &user) |
| 142 | + |
| 143 | + return user, err |
| 144 | +} |
| 145 | + |
| 146 | +func newConfig(provider *Provider, authURL, tokenURL string, scopes []string) *oauth2.Config { |
| 147 | + c := &oauth2.Config{ |
| 148 | + ClientID: provider.ClientKey, |
| 149 | + ClientSecret: provider.Secret, |
| 150 | + RedirectURL: provider.CallbackURL, |
| 151 | + Endpoint: oauth2.Endpoint{ |
| 152 | + AuthURL: authURL, |
| 153 | + TokenURL: tokenURL, |
| 154 | + }, |
| 155 | + Scopes: []string{}, |
| 156 | + } |
| 157 | + |
| 158 | + if len(scopes) > 0 { |
| 159 | + for _, scope := range scopes { |
| 160 | + c.Scopes = append(c.Scopes, scope) |
| 161 | + } |
| 162 | + } |
| 163 | + return c |
| 164 | +} |
| 165 | + |
| 166 | +// userFromReader |
| 167 | +// These are the standard cognito attributes |
| 168 | +// from: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html |
| 169 | +// all attributes are optional |
| 170 | +// it is possible for there to be custom attributes in cognito, but they don't seem to be passed as in the claims |
| 171 | +// all the standard claims are mapped into the raw data |
| 172 | +func userFromReader(r io.Reader, user *goth.User) error { |
| 173 | + u := struct { |
| 174 | + ID string `json:"sub"` |
| 175 | + Address string `json:"address"` |
| 176 | + Birthdate string `json:"birthdate"` |
| 177 | + Email string `json:"email"` |
| 178 | + EmailVerified string `json:"email_verified"` |
| 179 | + FirstName string `json:"given_name"` |
| 180 | + LastName string `json:"family_name"` |
| 181 | + MiddleName string `json:"middle_name"` |
| 182 | + Name string `json:"name"` |
| 183 | + NickName string `json:"nickname"` |
| 184 | + Locale string `json:"locale"` |
| 185 | + PhoneNumber string `json:"phone_number"` |
| 186 | + PictureURL string `json:"picture"` |
| 187 | + ProfileURL string `json:"profile"` |
| 188 | + Username string `json:"preferred_username"` |
| 189 | + UpdatedAt string `json:"updated_at"` |
| 190 | + WebSite string `json:"website"` |
| 191 | + Zoneinfo string `json:"zoneinfo"` |
| 192 | + }{} |
| 193 | + |
| 194 | + err := json.NewDecoder(r).Decode(&u) |
| 195 | + if err != nil { |
| 196 | + return err |
| 197 | + } |
| 198 | + |
| 199 | + // Ensure all standard claims are in the raw data |
| 200 | + rd := make(map[string]interface{}) |
| 201 | + rd["Address"] = u.Address |
| 202 | + rd["Birthdate"] = u.Birthdate |
| 203 | + rd["Locale"] = u.Locale |
| 204 | + rd["MiddleName"] = u.MiddleName |
| 205 | + rd["PhoneNumber"] = u.PhoneNumber |
| 206 | + rd["PictureURL"] = u.PictureURL |
| 207 | + rd["ProfileURL"] = u.ProfileURL |
| 208 | + rd["UpdatedAt"] = u.UpdatedAt |
| 209 | + rd["Username"] = u.Username |
| 210 | + rd["WebSite"] = u.WebSite |
| 211 | + rd["EmailVerified"] = u.EmailVerified |
| 212 | + |
| 213 | + user.UserID = u.ID |
| 214 | + user.Email = u.Email |
| 215 | + user.Name = u.Name |
| 216 | + user.NickName = u.NickName |
| 217 | + user.FirstName = u.FirstName |
| 218 | + user.LastName = u.LastName |
| 219 | + user.AvatarURL = u.PictureURL |
| 220 | + user.RawData = rd |
| 221 | + |
| 222 | + return nil |
| 223 | +} |
| 224 | + |
| 225 | +// RefreshTokenAvailable refresh token is provided by auth provider or not |
| 226 | +func (p *Provider) RefreshTokenAvailable() bool { |
| 227 | + return true |
| 228 | +} |
| 229 | + |
| 230 | +// RefreshToken get new access token based on the refresh token |
| 231 | +func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) { |
| 232 | + token := &oauth2.Token{RefreshToken: refreshToken} |
| 233 | + ts := p.config.TokenSource(goth.ContextForClient(p.Client()), token) |
| 234 | + newToken, err := ts.Token() |
| 235 | + if err != nil { |
| 236 | + return nil, err |
| 237 | + } |
| 238 | + return newToken, err |
| 239 | +} |
0 commit comments