/
cognito.go
199 lines (168 loc) · 5.93 KB
/
cognito.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
// This package provides a function which authenticates a user against Cognito and returns the AWS config and IDP tokens.
package cognito
import (
"context"
"fmt"
"time"
cognitosrp "github.com/alexrudd/cognito-srp/v4"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
"github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
"github.com/aws/smithy-go/logging"
)
type CognitoIdentityProviderClient interface {
InitiateAuth(ctx context.Context, params *cognitoidentityprovider.InitiateAuthInput, optFns ...func(*cognitoidentityprovider.Options)) (*cognitoidentityprovider.InitiateAuthOutput, error)
RespondToAuthChallenge(ctx context.Context, params *cognitoidentityprovider.RespondToAuthChallengeInput, optFns ...func(*cognitoidentityprovider.Options)) (*cognitoidentityprovider.RespondToAuthChallengeOutput, error)
}
type CognitoSRP interface {
GetClientId() string
GetAuthParams() map[string]string
PasswordVerifierChallenge(challengeParms map[string]string, ts time.Time) (map[string]string, error)
}
// AuthCognitoResult auth config results.
type AuthResult struct {
IDPTokens *IDPTokens
AWSConfig aws.Config
}
// IDPTokens contains the cognito "oidc" tokens.
type IDPTokens struct {
// The access token.
AccessToken *string
// The expiration period of the authentication result in seconds.
ExpiresIn int32
// The ID token.
IdToken *string
// The refresh token.
RefreshToken *string
// The token type.
TokenType *string
}
type CognitoConfig struct {
region string
userPoolID string
userPoolWebClientID string
username, password string
cipsvc CognitoIdentityProviderClient
csrp CognitoSRP
logger logging.Logger
}
// AuthCognitoOption configures the AuthCognito function.
type AuthOption func(*CognitoConfig)
// WithRegion sets the AWS region.
func WithRegion(region string) AuthOption {
return func(cfg *CognitoConfig) {
cfg.region = region
}
}
// WithUserPoolID sets the Cognito user pool ID and the Cognito user pool web client ID.
func WithUserPool(userPoolID string, userPoolWebClientID string) AuthOption {
return func(cfg *CognitoConfig) {
cfg.userPoolID = userPoolID
cfg.userPoolWebClientID = userPoolWebClientID
}
}
// WithUsername sets the username and password.
func WithUsernamePassword(username, password string) AuthOption {
return func(cfg *CognitoConfig) {
cfg.username = username
cfg.password = password
}
}
// WithCognitoIdentityProviderClient sets the CognitoIdentityProvider client.
func WithCognitoIdentityProviderClient(cipsvc CognitoIdentityProviderClient) AuthOption {
return func(cfg *CognitoConfig) {
cfg.cipsvc = cipsvc
}
}
func WithCognitoSRP(csrp CognitoSRP) AuthOption {
return func(cfg *CognitoConfig) {
cfg.csrp = csrp
}
}
func WithLogger(logger logging.Logger) AuthOption {
return func(cfg *CognitoConfig) {
cfg.logger = logger
}
}
// Auth authenticates a user against Cognito and returns the AWS config and IDP tokens.
//
// opts are the configuration options for the authentication.
//
// cfg is the CognitoConfig which is populated from the opts.
//
// awscfg is the default AWS config loaded with anonymous credentials. It is used to construct clients if not provided in opts.
//
// cipsvc is the CognitoIdentityProvider client. If not provided in opts, it is constructed from the awscfg.
//
// csrp is the CognitoSRP client used to handle the SRP auth flow. If not provided in opts, it is constructed.
//
// resp is the response from initiating the auth flow. It will contain a "PasswordVerifier" challenge.
//
// challengeResponses are the responses to the "PasswordVerifier" challenge generated by the csrp.
//
// authResp is the response from responding to the "PasswordVerifier" challenge. It will contain the authentication result with tokens.
//
// The AuthResult contains the AWS config and IDP tokens from the successful authentication.
func Auth(ctx context.Context, opts ...AuthOption) (*AuthResult, error) {
cfg := CognitoConfig{}
for _, opt := range opts {
opt(&cfg)
}
if cfg.logger == nil {
cfg.logger = logging.Nop{}
}
awscfg, err := config.LoadDefaultConfig(
ctx,
config.WithRegion(cfg.region),
config.WithCredentialsProvider(aws.AnonymousCredentials{}),
config.WithLogger(cfg.logger),
config.WithClientLogMode(aws.LogRetries|aws.LogRequest),
)
if err != nil {
return nil, err
}
if cfg.cipsvc == nil {
cfg.cipsvc = cognitoidentityprovider.NewFromConfig(awscfg)
}
if cfg.csrp == nil {
csrp, err := cognitosrp.NewCognitoSRP(cfg.username, cfg.password, cfg.userPoolID, cfg.userPoolWebClientID, nil)
if err != nil {
return nil, err
}
cfg.csrp = csrp
}
resp, err := cfg.cipsvc.InitiateAuth(ctx, &cognitoidentityprovider.InitiateAuthInput{
AuthFlow: types.AuthFlowTypeUserSrpAuth,
ClientId: aws.String(cfg.csrp.GetClientId()),
AuthParameters: cfg.csrp.GetAuthParams(),
})
if err != nil {
return nil, err
}
if resp.ChallengeName != types.ChallengeNameTypePasswordVerifier {
return nil, fmt.Errorf("failed authentication, unhandled challenge: %s", resp.ChallengeName)
}
challengeResponses, err := cfg.csrp.PasswordVerifierChallenge(resp.ChallengeParameters, time.Now())
if err != nil {
return nil, err
}
authResp, err := cfg.cipsvc.RespondToAuthChallenge(ctx, &cognitoidentityprovider.RespondToAuthChallengeInput{
ChallengeName: types.ChallengeNameTypePasswordVerifier,
ChallengeResponses: challengeResponses,
ClientId: aws.String(cfg.csrp.GetClientId()),
})
if err != nil {
return nil, err
}
return &AuthResult{
AWSConfig: awscfg,
IDPTokens: &IDPTokens{
IdToken: authResp.AuthenticationResult.IdToken,
AccessToken: authResp.AuthenticationResult.AccessToken,
RefreshToken: authResp.AuthenticationResult.RefreshToken,
ExpiresIn: authResp.AuthenticationResult.ExpiresIn,
TokenType: authResp.AuthenticationResult.TokenType,
},
}, nil
}