Skip to content

Commit aab36d0

Browse files
Merge pull request #491 from pilotso11/add-cognito-provider
Add cognito provider
2 parents b5cb5a6 + 44542ce commit aab36d0

File tree

5 files changed

+418
-0
lines changed

5 files changed

+418
-0
lines changed

.github/workflows/ci.yml

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ on:
55
pull_request:
66
branches:
77
- master
8+
workflow_dispatch:
89

910
name: ci
1011

providers/cognito/cognito.go

+239
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,239 @@
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+
}

providers/cognito/cognito_test.go

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package cognito
2+
3+
import (
4+
"os"
5+
"testing"
6+
7+
"github.com/markbates/goth"
8+
"github.com/markbates/goth/providers/okta"
9+
"github.com/stretchr/testify/assert"
10+
)
11+
12+
func Test_New(t *testing.T) {
13+
t.Parallel()
14+
a := assert.New(t)
15+
p := provider()
16+
17+
a.Equal(p.ClientKey, os.Getenv("COGNITO_ID"))
18+
a.Equal(p.Secret, os.Getenv("COGNITO_SECRET"))
19+
a.Equal(p.CallbackURL, "/foo")
20+
}
21+
22+
func Test_NewCustomisedURL(t *testing.T) {
23+
t.Parallel()
24+
a := assert.New(t)
25+
p := urlCustomisedURLProvider()
26+
session, err := p.BeginAuth("test_state")
27+
s := session.(*okta.Session)
28+
a.NoError(err)
29+
a.Contains(s.AuthURL, "http://authURL")
30+
}
31+
32+
func Test_Implements_Provider(t *testing.T) {
33+
t.Parallel()
34+
a := assert.New(t)
35+
a.Implements((*goth.Provider)(nil), provider())
36+
}
37+
38+
func Test_BeginAuth(t *testing.T) {
39+
t.Parallel()
40+
a := assert.New(t)
41+
p := provider()
42+
session, err := p.BeginAuth("test_state")
43+
s := session.(*okta.Session)
44+
a.NoError(err)
45+
a.Contains(s.AuthURL, os.Getenv("COGNITO_ISSUER_URL"))
46+
}
47+
48+
func Test_SessionFromJSON(t *testing.T) {
49+
t.Parallel()
50+
a := assert.New(t)
51+
52+
p := provider()
53+
session, err := p.UnmarshalSession(`{"AuthURL":"` + os.Getenv("COGNITO_ISSUER_URL") + `/oauth2/authorize", "AccessToken":"1234567890"}`)
54+
a.NoError(err)
55+
56+
s := session.(*okta.Session)
57+
a.Equal(s.AuthURL, os.Getenv("COGNITO_ISSUER_URL")+"/oauth2/authorize")
58+
a.Equal(s.AccessToken, "1234567890")
59+
}
60+
61+
func provider() *okta.Provider {
62+
return okta.New(os.Getenv("COGNITO_ID"), os.Getenv("COGNITO_SECRET"), os.Getenv("COGNITO_ISSUER_URL"), "/foo")
63+
}
64+
65+
func urlCustomisedURLProvider() *okta.Provider {
66+
return okta.NewCustomisedURL(os.Getenv("CLIENT_ID"), os.Getenv("CLIENT_SECRET"), "/foo", "http://authURL", "http://tokenURL", "http://issuerURL", "http://profileURL")
67+
}

providers/cognito/session.go

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package cognito
2+
3+
import (
4+
"encoding/json"
5+
"errors"
6+
"strings"
7+
"time"
8+
9+
"github.com/markbates/goth"
10+
)
11+
12+
// Session stores data during the auth process with AWS Cognito.
13+
type Session struct {
14+
AuthURL string
15+
AccessToken string
16+
RefreshToken string
17+
ExpiresAt time.Time
18+
UserID string
19+
}
20+
21+
var _ goth.Session = &Session{}
22+
23+
// GetAuthURL will return the URL set by calling the `BeginAuth` function on the AWS Cognito provider.
24+
func (s Session) GetAuthURL() (string, error) {
25+
if s.AuthURL == "" {
26+
return "", errors.New(goth.NoAuthUrlErrorMessage)
27+
}
28+
return s.AuthURL, nil
29+
}
30+
31+
// Authorize the session with cognito and return the access token to be stored for future use.
32+
func (s *Session) Authorize(provider goth.Provider, params goth.Params) (string, error) {
33+
p := provider.(*Provider)
34+
token, err := p.config.Exchange(goth.ContextForClient(p.Client()), params.Get("code"))
35+
if err != nil {
36+
return "", err
37+
}
38+
39+
if !token.Valid() {
40+
return "", errors.New("invalid token received from provider")
41+
}
42+
43+
s.AccessToken = token.AccessToken
44+
s.RefreshToken = token.RefreshToken
45+
s.ExpiresAt = token.Expiry
46+
return token.AccessToken, err
47+
}
48+
49+
// Marshal the session into a string
50+
func (s Session) Marshal() string {
51+
b, _ := json.Marshal(s)
52+
return string(b)
53+
}
54+
55+
func (s Session) String() string {
56+
return s.Marshal()
57+
}
58+
59+
// UnmarshalSession wil unmarshal a JSON string into a session.
60+
func (p *Provider) UnmarshalSession(data string) (goth.Session, error) {
61+
s := &Session{}
62+
err := json.NewDecoder(strings.NewReader(data)).Decode(s)
63+
return s, err
64+
}

0 commit comments

Comments
 (0)