@aws/nx-plugin-mcp 1.4.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Website Identity Providers
|
|
3
|
+
description: Let users sign in to your website through an external OpenID Connect identity provider such as Okta, Auth0 or Microsoft Entra ID
|
|
4
|
+
generator: ts#website#auth
|
|
5
|
+
when:
|
|
6
|
+
federation: [oidc]
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
import { FileTree } from '@astrojs/starlight/components';
|
|
10
|
+
import Infrastructure from '@components/infrastructure.astro';
|
|
11
|
+
import Link from '@components/link.astro';
|
|
12
|
+
import RunGenerator from '@components/run-generator.astro';
|
|
13
|
+
|
|
14
|
+
<Link path="guides/react-website-auth">Website authentication</Link> creates an Amazon Cognito user pool, and by default only users who have a username and password in that pool can sign in. If your staff or customers already have accounts at an identity provider (IdP), such as Okta, Auth0 or Microsoft Entra ID, they would otherwise need a second account just for your website.
|
|
15
|
+
|
|
16
|
+
Running `ts#website#auth` with `--federation=oidc` lets you add external [OpenID Connect](https://openid.net/developers/how-connect-works/) (OIDC) identity providers to the user pool. You list the identity providers in your infrastructure code: the `oidcIdentityProviders` prop of `UserIdentity` in CDK, or the `oidc_identity_providers` variable of the `user_identity` module in Terraform. The sign-in page then shows a button for each identity provider next to the username and password form.
|
|
17
|
+
|
|
18
|
+
## How this works
|
|
19
|
+
|
|
20
|
+
- Your website still sends users to the Cognito sign-in page. The page now has a button named after each identity provider.
|
|
21
|
+
- A user who chooses a button signs in at that identity provider. The identity provider sends them back to Cognito at its redirect URI, `https://<cognito domain>/oauth2/idpresponse`.
|
|
22
|
+
- Cognito creates a user in your user pool for them, a federated user, and copies the claims you map (for example `email`) into the user's attributes.
|
|
23
|
+
- Cognito then issues the same kind of tokens it issues to a local user. Your APIs, agents and identity pool accept them without any change.
|
|
24
|
+
|
|
25
|
+
Users with a username and password in the pool can still sign in.
|
|
26
|
+
|
|
27
|
+
## Who can sign in
|
|
28
|
+
|
|
29
|
+
Adding an identity provider can let many more people into your website than you expect. The `allowSignup` option of `ts#website#auth` does not apply to federated users. Cognito creates a federated user the first time someone signs in through the identity provider, even when the user pool does not let users sign themselves up. Each federated user also gets the identity pool's authenticated role, so they can call your APIs and agents as any signed-in user can.
|
|
30
|
+
|
|
31
|
+
The identity providers apply to the whole user pool. Every website that uses the pool shows their buttons and accepts their users.
|
|
32
|
+
|
|
33
|
+
The identity provider therefore decides who can sign in. Set it up so that it signs in only the people who need your website:
|
|
34
|
+
|
|
35
|
+
- Microsoft Entra ID: in the application's enterprise application properties, set "Assignment required?" to Yes, and assign only the users or groups who need access. With the default, No, every user in your tenant can sign in.
|
|
36
|
+
- Okta: assign the application only to the groups who need access.
|
|
37
|
+
- Auth0: disable sign-ups on each connection the application uses, and enable for the application only the connections whose users need access. Otherwise anyone who signs up through an enabled connection, for example a social connection, can sign in.
|
|
38
|
+
|
|
39
|
+
## Usage
|
|
40
|
+
|
|
41
|
+
### Add OpenID Connect federation
|
|
42
|
+
|
|
43
|
+
Run the <Link path="guides/react-website-auth">`ts#website#auth`</Link> generator with `--federation=oidc`. You can run it on a website that has no authentication yet, or on a website that already has it. Both give the same result.
|
|
44
|
+
|
|
45
|
+
<RunGenerator generator="ts#website#auth" requiredParameters={{ federation: 'oidc' }} />
|
|
46
|
+
|
|
47
|
+
The generator adds no identity provider. The list starts empty, so sign-in works as before until you add an entry. You add identity providers to your infrastructure code, so adding a second one does not need another generator run.
|
|
48
|
+
|
|
49
|
+
Running the generator again with `--federation=oidc` changes no file. Running it with `--federation=none`, or without `--federation`, keeps the federation that is already there.
|
|
50
|
+
|
|
51
|
+
### Add identity providers
|
|
52
|
+
|
|
53
|
+
Add an entry for each identity provider, then deploy. The client secret never goes into your code. You store it in AWS Secrets Manager and give its name, as [Set up your identity provider](#set-up-your-identity-provider) describes.
|
|
54
|
+
|
|
55
|
+
<Infrastructure>
|
|
56
|
+
<Fragment slot="cdk">
|
|
57
|
+
Pass the identity providers to `UserIdentity` in your stack:
|
|
58
|
+
|
|
59
|
+
```ts title="packages/infra/src/stacks/application-stack.ts"
|
|
60
|
+
import { MyWebsite, UserIdentity } from '@my-scope/common-constructs';
|
|
61
|
+
|
|
62
|
+
const identity = new UserIdentity(this, 'Identity', {
|
|
63
|
+
oidcIdentityProviders: [
|
|
64
|
+
{
|
|
65
|
+
name: 'Okta',
|
|
66
|
+
issuerUrl: 'https://example.okta.com',
|
|
67
|
+
clientId: '0oa1example',
|
|
68
|
+
clientSecretName: 'okta-oidc-client-secret',
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
name: 'Entra',
|
|
72
|
+
issuerUrl: 'https://login.microsoftonline.com/<tenant-id>/v2.0',
|
|
73
|
+
clientId: '11111111-2222-3333-4444-555555555555',
|
|
74
|
+
clientSecretName: 'entra-oidc-client-secret',
|
|
75
|
+
identifiers: ['example.com'],
|
|
76
|
+
},
|
|
77
|
+
],
|
|
78
|
+
});
|
|
79
|
+
new MyWebsite(this, 'MyWebsite');
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
`OidcIdentityProviderProps`, the type of each entry, is exported from your shared constructs package, so you can build the list elsewhere and import the type.
|
|
83
|
+
</Fragment>
|
|
84
|
+
<Fragment slot="terraform">
|
|
85
|
+
Pass the identity providers to the `user_identity` module in your root module, and add an output for the redirect URI:
|
|
86
|
+
|
|
87
|
+
```hcl title="packages/infra/src/main.tf"
|
|
88
|
+
module "user_identity" {
|
|
89
|
+
source = "../../common/terraform/src/core/user-identity"
|
|
90
|
+
|
|
91
|
+
oidc_identity_providers = [
|
|
92
|
+
{
|
|
93
|
+
name = "Okta"
|
|
94
|
+
issuer_url = "https://example.okta.com"
|
|
95
|
+
client_id = "0oa1example"
|
|
96
|
+
client_secret_name = "okta-oidc-client-secret"
|
|
97
|
+
},
|
|
98
|
+
]
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
output "idp_redirect_uri" {
|
|
102
|
+
value = module.user_identity.idp_redirect_uri
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
To use different identity providers in each environment, declare a root variable and set it in each environment's `.tfvars` file. The root variable has `type = any`, because the module's variable checks the type:
|
|
107
|
+
|
|
108
|
+
```hcl
|
|
109
|
+
# packages/infra/src/variables.tf
|
|
110
|
+
variable "oidc_identity_providers" {
|
|
111
|
+
type = any
|
|
112
|
+
default = []
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
# packages/infra/src/env/dev.tfvars
|
|
116
|
+
oidc_identity_providers = [
|
|
117
|
+
{ name = "Okta", issuer_url = "https://example.okta.com", client_id = "0oa1example", client_secret_name = "okta-oidc-client-secret" },
|
|
118
|
+
]
|
|
119
|
+
|
|
120
|
+
# packages/infra/src/main.tf, in module "user_identity"
|
|
121
|
+
oidc_identity_providers = var.oidc_identity_providers
|
|
122
|
+
```
|
|
123
|
+
</Fragment>
|
|
124
|
+
</Infrastructure>
|
|
125
|
+
|
|
126
|
+
### Options
|
|
127
|
+
|
|
128
|
+
Each identity provider in the list has these properties. The generator options are described in <Link path="guides/react-website-auth">website authentication</Link>.
|
|
129
|
+
|
|
130
|
+
| CDK prop | Terraform attribute | Required | Default | Description |
|
|
131
|
+
|---|---|---|---|---|
|
|
132
|
+
| `name` | `name` | Yes | | Shown on the sign-in button. Cognito prefixes federated usernames with it in lower case (`<name>_<sub>`). 3-32 letters, digits and hyphens, starting with a letter. Not `COGNITO`. Unique in the list, ignoring case. In CDK it must be a literal string, not a token. |
|
|
133
|
+
| `issuerUrl` | `issuer_url` | Yes | | The issuer exactly as it appears in the `iss` claim of the identity provider's tokens. Must use `https://`. |
|
|
134
|
+
| `clientId` | `client_id` | Yes | | Client ID of the application registered at the identity provider. |
|
|
135
|
+
| `clientSecretName` | `client_secret_name` | Yes | | Name of the Secrets Manager secret that holds the client secret as a plain string. A name, not an ARN. |
|
|
136
|
+
| `scopes` | `scopes` | No | `openid`, `email`, `profile` | OAuth scopes to request. Must include `openid`. |
|
|
137
|
+
| `attributeMapping` | `attribute_mapping` | No | `email`, `given_name` and `family_name`, each to the claim with the same name | User pool attribute to identity provider claim. See [Attribute mapping](#attribute-mapping). |
|
|
138
|
+
| `identifiers` | `identifiers` | No | None | Identifiers, such as email domains, that Cognito can use to send a user to this identity provider. |
|
|
139
|
+
|
|
140
|
+
### Validation
|
|
141
|
+
|
|
142
|
+
The vended code checks each entry before anything is deployed:
|
|
143
|
+
|
|
144
|
+
<Infrastructure>
|
|
145
|
+
<Fragment slot="cdk">
|
|
146
|
+
`UserIdentity` throws when you create it with an entry that breaks a rule, so `cdk synth` fails. The infra project's build runs `cdk synth`. The message names the entry, for example `UserIdentity: oidcIdentityProviders[1] (Entra): Microsoft Entra ID issuers have no trailing slash. Use https://login.microsoftonline.com/<tenant-id>/v2.0`.
|
|
147
|
+
|
|
148
|
+
A value that is a token, for example one read from AWS Systems Manager Parameter Store, is not checked. A wrong value then fails the deploy instead of the synth. `name` must not be a token.
|
|
149
|
+
</Fragment>
|
|
150
|
+
<Fragment slot="terraform">
|
|
151
|
+
The module's `oidc_identity_providers` variable has one `validation` block for each rule. Its error messages do not name the entry that breaks the rule.
|
|
152
|
+
|
|
153
|
+
When you write the list as a literal in the `user_identity` module block, `terraform validate` checks it. The project's `validate` target runs `terraform validate`. When the list comes from a root variable, as in the `.tfvars` pattern above, `terraform plan` checks it instead.
|
|
154
|
+
</Fragment>
|
|
155
|
+
</Infrastructure>
|
|
156
|
+
|
|
157
|
+
The rules:
|
|
158
|
+
|
|
159
|
+
- `name`: 3-32 letters, digits and hyphens, starting with a letter. Not `COGNITO` in any case, because Cognito reserves it for sign-in with the user pool itself.
|
|
160
|
+
- Names are unique in the list, ignoring case, because Cognito prefixes federated usernames with the lower-case name. For example, `Okta` and `OKTA` cannot both be in the list. `test-idp` and `testidp` can, because their prefixes differ.
|
|
161
|
+
- The issuer uses `https://` and has no query, fragment, user name, password or whitespace. In CDK it must also parse as a URL. In Terraform a regular expression checks it, which accepts a few malformed URLs that CDK refuses.
|
|
162
|
+
- Microsoft Entra ID: the multi-tenant issuers (`common`, `organizations`, `consumers` and `9188040d-6c67-4c5b-b112-36a304b66dad`) are refused, and the issuer must not end with a slash.
|
|
163
|
+
- Auth0: an issuer on `*.auth0.com` must end with a slash.
|
|
164
|
+
- The client ID is not empty.
|
|
165
|
+
- The secret name is 1-512 letters, digits and `/ _ + = . @ -`. These are the Secrets Manager naming rules, so an ARN is refused.
|
|
166
|
+
- The scopes include `openid`. In CDK each scope must also be non-empty and have no whitespace.
|
|
167
|
+
- The attribute mapping keys and values follow the rules in [Attribute mapping](#attribute-mapping).
|
|
168
|
+
- At most 50 identifiers. Each is 1-40 letters, digits, spaces or `_ + = . @ -`.
|
|
169
|
+
|
|
170
|
+
## Generator Output
|
|
171
|
+
|
|
172
|
+
With `--federation=oidc` the generator adds these files and edits for your selected `iac` provider:
|
|
173
|
+
|
|
174
|
+
<Infrastructure>
|
|
175
|
+
<Fragment slot="cdk">
|
|
176
|
+
<FileTree>
|
|
177
|
+
- packages/common/constructs/src/core
|
|
178
|
+
- oidc-identity-providers.ts The `OidcIdentityProviders` construct, its props and the validation
|
|
179
|
+
- index.ts Now exports `oidc-identity-providers.ts`
|
|
180
|
+
- user-identity.ts Now has the `oidcIdentityProviders` prop and creates the identity providers
|
|
181
|
+
</FileTree>
|
|
182
|
+
</Fragment>
|
|
183
|
+
<Fragment slot="terraform">
|
|
184
|
+
<FileTree>
|
|
185
|
+
- packages/common/terraform/src/core/user-identity
|
|
186
|
+
- oidc-identity-providers.tf The `oidc_identity_providers` variable with its validation, and the `idp_redirect_uri` output
|
|
187
|
+
- main.tf Now passes the variable to the identity module
|
|
188
|
+
- identity
|
|
189
|
+
- oidc-identity-providers.tf The identity providers, the data source that reads each client secret, and the `idp_redirect_uri` output
|
|
190
|
+
- identity.tf Now lists the identity providers on the web client
|
|
191
|
+
</FileTree>
|
|
192
|
+
</Fragment>
|
|
193
|
+
</Infrastructure>
|
|
194
|
+
|
|
195
|
+
The edits let the user pool's web client, the Cognito app client your website signs in through, accept the identity providers:
|
|
196
|
+
|
|
197
|
+
<Infrastructure>
|
|
198
|
+
<Fragment slot="cdk">
|
|
199
|
+
```diff lang="ts" title="packages/common/constructs/src/core/user-identity.ts"
|
|
200
|
+
+import {
|
|
201
|
+
+ OidcIdentityProviders,
|
|
202
|
+
+ type OidcIdentityProviderProps,
|
|
203
|
+
+} from './oidc-identity-providers.js';
|
|
204
|
+
readonly mfaSecondFactor?: MfaSecondFactor;
|
|
205
|
+
+
|
|
206
|
+
+ /**
|
|
207
|
+
+ * OpenID Connect identity providers users can sign in through, next to the user pool's own sign-in.
|
|
208
|
+
+ * Applies to every website that uses this user pool.
|
|
209
|
+
+ * ...
|
|
210
|
+
+ */
|
|
211
|
+
+ readonly oidcIdentityProviders?: OidcIdentityProviderProps[];
|
|
212
|
+
}
|
|
213
|
+
mfaSecondFactor = { sms: true, otp: true },
|
|
214
|
+
+ oidcIdentityProviders = [],
|
|
215
|
+
}: UserIdentityProps = {},
|
|
216
|
+
this.userPoolDomain = this.createUserPoolDomain(this.userPool);
|
|
217
|
+
+ new OidcIdentityProviders(this, 'OidcIdentityProviders', {
|
|
218
|
+
+ userPool: this.userPool,
|
|
219
|
+
+ userPoolDomain: this.userPoolDomain,
|
|
220
|
+
+ providers: oidcIdentityProviders,
|
|
221
|
+
+ });
|
|
222
|
+
this.userPoolClient = this.createUserPoolClient(this.userPool);
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
`UserIdentity` creates the identity providers before the web client, so the web client lists them, followed by `COGNITO`.
|
|
226
|
+
</Fragment>
|
|
227
|
+
<Fragment slot="terraform">
|
|
228
|
+
```diff lang="hcl" title="packages/common/terraform/src/core/user-identity/main.tf"
|
|
229
|
+
mfa_second_factor_sms = var.mfa_second_factor_sms
|
|
230
|
+
+ oidc_identity_providers = var.oidc_identity_providers
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
```diff lang="hcl" title="packages/common/terraform/src/core/user-identity/identity/identity.tf"
|
|
234
|
+
- supported_identity_providers = ["COGNITO"]
|
|
235
|
+
+ supported_identity_providers = concat(["COGNITO"], [for p in aws_cognito_identity_provider.oidc : p.provider_name])
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
Each identity provider is a `for_each` instance keyed by its name, for example `aws_cognito_identity_provider.oidc["Okta"]`. Renaming an entry therefore replaces that identity provider.
|
|
239
|
+
</Fragment>
|
|
240
|
+
</Infrastructure>
|
|
241
|
+
|
|
242
|
+
The generator does not overwrite your edits to the new files. If you have changed `user-identity.ts`, or `main.tf` or `identity.tf`, so that the generator no longer recognizes it, the generator leaves those files unchanged. It still adds the new files, and prints the lines to add by hand.
|
|
243
|
+
|
|
244
|
+
## Set up your identity provider
|
|
245
|
+
|
|
246
|
+
The deploy that adds an identity provider reads its client secret from Secrets Manager. If the secret does not exist, the deploy fails.
|
|
247
|
+
|
|
248
|
+
<Infrastructure>
|
|
249
|
+
<Fragment slot="cdk">
|
|
250
|
+
CloudFormation reads the secret with the stack's execution role, by default `cdk-hnb659fds-cfn-exec-role-<account>-<region>`. That role needs `secretsmanager:GetSecretValue` on the secret, plus `kms:Decrypt` on the key if the secret is encrypted with a customer managed AWS KMS key.
|
|
251
|
+
</Fragment>
|
|
252
|
+
<Fragment slot="terraform">
|
|
253
|
+
The identity that runs `terraform apply` reads the secret. It needs `secretsmanager:GetSecretValue` on the secret, plus `kms:Decrypt` on the key if the secret is encrypted with a customer managed AWS KMS key.
|
|
254
|
+
</Fragment>
|
|
255
|
+
</Infrastructure>
|
|
256
|
+
|
|
257
|
+
Follow these steps in this order. The generator also prints them when it finishes.
|
|
258
|
+
|
|
259
|
+
1. Run `ts#website#auth` with `--federation=oidc`, and deploy once.
|
|
260
|
+
2. Find the redirect URI of your user pool. All identity providers of the pool use the same one.
|
|
261
|
+
|
|
262
|
+
<Infrastructure>
|
|
263
|
+
<Fragment slot="cdk">
|
|
264
|
+
The stack that contains `UserIdentity` has an output whose key starts with `<id>OidcIdentityProvidersIdpRedirectUri`, where `<id>` is the construct ID you gave `UserIdentity`, for example `IdentityOidcIdentityProvidersIdpRedirectUri`. You can also work it out before you deploy, from the `cognitoDomain` you chose for `ts#website#auth`, your AWS account ID and your region:
|
|
265
|
+
|
|
266
|
+
```
|
|
267
|
+
https://<cognitoDomain>-<account>.auth.<region>.amazoncognito.com/oauth2/idpresponse
|
|
268
|
+
```
|
|
269
|
+
</Fragment>
|
|
270
|
+
<Fragment slot="terraform">
|
|
271
|
+
The Cognito domain has a random suffix, so the redirect URI is known only after the deploy. The `user_identity` module outputs it as `idp_redirect_uri`. To see it, add an output to your root module, for example `packages/infra/src/main.tf`:
|
|
272
|
+
|
|
273
|
+
```hcl
|
|
274
|
+
output "idp_redirect_uri" { value = module.user_identity.idp_redirect_uri }
|
|
275
|
+
```
|
|
276
|
+
</Fragment>
|
|
277
|
+
</Infrastructure>
|
|
278
|
+
|
|
279
|
+
3. Register an application at the identity provider with that redirect URI, and note its client ID and client secret. Register only this `/oauth2/idpresponse` URI at the identity provider. Your website's own URLs are registered with Cognito, not with the identity provider.
|
|
280
|
+
4. Store the client secret in Secrets Manager. Pass it in a file, not as a command-line argument. An argument stays in your shell history, and other users of the same computer can see it in the process list while the command runs:
|
|
281
|
+
|
|
282
|
+
```bash
|
|
283
|
+
(
|
|
284
|
+
umask 077
|
|
285
|
+
d=$(mktemp -d) || exit
|
|
286
|
+
trap 'rm -rf "$d"' EXIT
|
|
287
|
+
trap 'exit 1' HUP INT TERM
|
|
288
|
+
unset CLIENT_SECRET
|
|
289
|
+
IFS= read -rs CLIENT_SECRET || exit 1
|
|
290
|
+
printf '%s' "$CLIENT_SECRET" > "$d/secret" || exit 1
|
|
291
|
+
unset CLIENT_SECRET
|
|
292
|
+
aws secretsmanager create-secret --name okta-oidc-client-secret --secret-string "file://$d/secret" --region <region>
|
|
293
|
+
)
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
The commands run in a subshell, between the parentheses. `read` waits for you to paste the client secret and press Enter, and does not show it. The two `unset` commands keep the secret out of the `aws` command's environment, even if you exported `CLIENT_SECRET` earlier. `IFS=` and `-r` keep the secret exactly as you paste it, including spaces at either end and backslashes. `mktemp -d` creates a new directory that only you can open (mode 700), and `printf` writes the secret into it without a newline at the end. The AWS CLI reads the value of `--secret-string` from the file named after `file://` and passes it unchanged, so a newline at the end of the file would become part of the secret. When the subshell ends, the `trap` commands delete the directory. They also do this if the `aws` command fails or you press Ctrl-C. The commands work in bash and zsh, the default shells on Linux and macOS. For Windows, see [Mitigate the risks of using the AWS CLI to store your AWS Secrets Manager secrets](https://docs.aws.amazon.com/secretsmanager/latest/userguide/security_cli-exposure-risks.html).
|
|
297
|
+
|
|
298
|
+
Set `--region` to your stack's region. The secret must exist in that region before the deploy that adds the identity provider. Store the secret as a plain string, not JSON, because Cognito receives the whole secret value as the client secret. In the Secrets Manager console, choose Plaintext, not Key/value.
|
|
299
|
+
|
|
300
|
+
5. Add the identity provider to the list, with the secret's name as `clientSecretName` (`client_secret_name` in Terraform), as [Add identity providers](#add-identity-providers) shows. Then deploy.
|
|
301
|
+
|
|
302
|
+
## Attribute mapping
|
|
303
|
+
|
|
304
|
+
The generated user pool requires the `email`, `given_name` and `family_name` attributes. Cognito fills them from the identity provider's claims on every sign-in. If the identity provider does not send one of them, the user's first sign-in fails. `UserIdentity` and the Terraform variable therefore refuse an attribute mapping that leaves out any of the three.
|
|
305
|
+
|
|
306
|
+
`attributeMapping` (`attribute_mapping` in Terraform) maps user pool attributes to claims. Each key is a user pool attribute, and each value is the name of the identity provider's claim, 1-128 characters long. A mapping you give replaces the default. The default maps each required attribute to the claim with the same name:
|
|
307
|
+
|
|
308
|
+
<Infrastructure>
|
|
309
|
+
<Fragment slot="cdk">
|
|
310
|
+
```ts
|
|
311
|
+
attributeMapping: { email: 'email', given_name: 'given_name', family_name: 'family_name' },
|
|
312
|
+
```
|
|
313
|
+
</Fragment>
|
|
314
|
+
<Fragment slot="terraform">
|
|
315
|
+
```hcl
|
|
316
|
+
attribute_mapping = { email = "email", given_name = "given_name", family_name = "family_name" }
|
|
317
|
+
```
|
|
318
|
+
</Fragment>
|
|
319
|
+
</Infrastructure>
|
|
320
|
+
|
|
321
|
+
- A key can be any [standard attribute](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html#cognito-user-pools-standard-attributes), such as `name` or `phone_number`, `phone_number_verified`, or a custom attribute such as `custom:department` (up to 20 letters, digits or underscores after `custom:`). Keys use the Cognito attribute names in both CDK and Terraform. `username` is refused.
|
|
322
|
+
- Cognito treats a mapped email address as unverified. Map `email_verified` only from an identity provider that verifies email addresses itself. Otherwise a user could set someone else's address at the identity provider and have it marked as verified in your pool.
|
|
323
|
+
- If a user's email address changes at the identity provider, Cognito writes the new address to the user pool at the user's next sign-in. `email_verified` stays `false`.
|
|
324
|
+
- A custom attribute must already exist in the user pool, and it must be mutable.
|
|
325
|
+
|
|
326
|
+
The Terraform identity provider resource, in `identity/oidc-identity-providers.tf`, also sets two values that Cognito adds when it returns the identity provider: `username = "sub"` in `attribute_mapping` and `attributes_url_add_attributes = "false"` in `provider_details`. Because the file sets them, a second `terraform plan` after the first deploy shows no change to the identity provider. If a second plan still shows a change in `provider_details` with another identity provider, add that key to the file with the value the plan shows Cognito returning.
|
|
327
|
+
|
|
328
|
+
## Identity provider notes
|
|
329
|
+
|
|
330
|
+
The settings below come from each vendor's documentation. Okta has been tested on AWS with both CDK and Terraform. The Auth0 and Microsoft Entra ID settings were checked against each vendor's published OpenID discovery document, but not with a live sign-in.
|
|
331
|
+
|
|
332
|
+
### Okta
|
|
333
|
+
|
|
334
|
+
Tested on AWS with CDK and Terraform. Create an OIDC Web Application in Okta, with the Authorization Code grant and a client secret. Set its sign-in redirect URI to the `/oauth2/idpresponse` redirect URI from step 2 of [Set up your identity provider](#set-up-your-identity-provider). It needs no sign-out redirect URI. The issuer is your Okta domain, `https://<your-org>.okta.com`, which is the form that was tested. A custom authorization server, such as `https://<your-org>.okta.com/oauth2/default`, also has an issuer, but that form has not been tested. The default scopes, `openid email profile`, return `email`, `given_name` and `family_name`, so the default mapping works. Each user needs an email, a first name and a last name set in Okta. Assign the application only to the users or groups who need access.
|
|
335
|
+
|
|
336
|
+
### Auth0
|
|
337
|
+
|
|
338
|
+
Checked against Auth0's discovery document, not tested with a live sign-in. Create a Regular Web Application in Auth0. The issuer is `https://<your-tenant>.auth0.com/`, including the trailing slash.
|
|
339
|
+
|
|
340
|
+
:::caution
|
|
341
|
+
The `iss` claim in Auth0 tokens ends with a slash, so an issuer without it makes sign-in fail. The vended code refuses an issuer on `*.auth0.com` without the slash. It cannot recognize an Auth0 custom domain, so check the slash yourself when you use one.
|
|
342
|
+
:::
|
|
343
|
+
|
|
344
|
+
Auth0 returns `given_name` and `family_name` only when the user's connection provides them. Users of a connection without them cannot sign in until you map other claims.
|
|
345
|
+
|
|
346
|
+
### Microsoft Entra ID
|
|
347
|
+
|
|
348
|
+
Checked against Microsoft's discovery document, not tested with a live sign-in. Register a single-tenant application in Entra ID. The issuer is `https://login.microsoftonline.com/<tenant-id>/v2.0`. The vended code refuses the multi-tenant issuers (`common`, `organizations` and `consumers`), because they accept users from any Entra ID tenant. It also refuses the tenant `9188040d-6c67-4c5b-b112-36a304b66dad`, which accepts any personal Microsoft account.
|
|
349
|
+
|
|
350
|
+
The issuer must not end with a slash: use `/v2.0`, not `/v2.0/`. The `iss` claim in Entra ID tokens has no slash, so sign-in would fail. The vended code refuses the form with the slash.
|
|
351
|
+
|
|
352
|
+
Add `email`, `given_name` and `family_name` as optional claims to the application's ID token. Entra ID sends them only if you do. Each user needs the Mail field set. Otherwise the `email` claim is empty, and the user's first sign-in fails, because the user pool requires `email`. Entra ID's `email` claim is not verified, so do not map `email_verified` from Entra ID.
|
|
353
|
+
|
|
354
|
+
### Cognito user pool
|
|
355
|
+
|
|
356
|
+
To test with another Cognito user pool as the identity provider, use the issuer `https://cognito-idp.<region>.amazonaws.com/<user pool id>`. Give its app client a client secret, the authorization code grant and the scopes `openid email profile`.
|
|
357
|
+
|
|
358
|
+
## Security
|
|
359
|
+
|
|
360
|
+
- Identify users by the `sub` claim (the user's unique ID in your user pool), never by `email`. A federated user is a new user in your pool with their own `sub`, even when their email matches a local user. The code the plugin generates uses `sub`.
|
|
361
|
+
- Use a single-tenant issuer. A multi-tenant issuer lets users from any organization sign in.
|
|
362
|
+
- Remove the `http://localhost` callback URLs from production stages, as <Link path="guides/react-website-auth">website authentication</Link> describes. Federation adds no callback URL.
|
|
363
|
+
|
|
364
|
+
## What federation does not do
|
|
365
|
+
|
|
366
|
+
- MFA (multi-factor authentication) required in your user pool does not apply to federated users. Cognito leaves their authentication to the identity provider, so enforce MFA at the identity provider.
|
|
367
|
+
- Signing out of your website ends the Cognito session only. It does not end the user's session at an OIDC identity provider, so the next sign-in through the button can complete without a password. On a shared computer, users must also sign out at the identity provider.
|
|
368
|
+
- The user menu shows the Cognito username. For a federated user it is the identity provider name, an underscore and the user's `sub` at the identity provider, in lowercase, for example `okta_00u1abcd`.
|
|
369
|
+
- Removing or disabling a user at the identity provider stops only their next sign-in through it. Cognito renews tokens with its own refresh token and does not ask the identity provider, and the website renews tokens without the user noticing. The user can therefore keep access until the refresh token expires, up to 30 days after their last sign-in. To stop the user getting new tokens, also sign them out of every session and disable them in the user pool. Their username is `<identity provider name in lowercase>_<sub>`:
|
|
370
|
+
|
|
371
|
+
```bash
|
|
372
|
+
aws cognito-idp admin-user-global-sign-out --user-pool-id <user pool id> --username okta_<sub>
|
|
373
|
+
aws cognito-idp admin-disable-user --user-pool-id <user pool id> --username okta_<sub>
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
This has been tested on AWS. After `admin-user-global-sign-out` and `admin-disable-user`, the identity provider still signs the user in, but Cognito refuses them.
|
|
377
|
+
|
|
378
|
+
These commands do not end access that the user already has. [`admin-user-global-sign-out`](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUserGlobalSignOut.html) revokes the user's refresh tokens, so the website cannot get new tokens for them, and `admin-disable-user` stops their next sign-in. ID and access tokens that Cognito has already issued stay valid until they expire, by default one hour after they were issued ([ID and access token validity](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_CreateUserPoolClient.html#CognitoUserPools-CreateUserPoolClient-request-IdTokenValidity)). The AWS credentials that the identity pool has already given the website also stay valid until they expire, one hour after they were issued ([identity pools authentication flow](https://docs.aws.amazon.com/cognito/latest/developerguide/concepts.html#authentication-flow-enhanced)). Until they expire, the user can still use the website and the identity pool's authenticated role.
|
|
379
|
+
|
|
380
|
+
A shorter refresh token validity on the web client (`refreshTokenValidity` in CDK, `refresh_token_validity` in Terraform) shortens the time a removed user keeps access if you do not run these commands. A shorter ID and access token validity (`idTokenValidity` and `accessTokenValidity` in CDK, `id_token_validity` and `access_token_validity` in Terraform) shortens the time that tokens already issued stay valid after you run the commands, but some time always remains. Neither has been tested on AWS.
|
|
381
|
+
|
|
382
|
+
## The client secret
|
|
383
|
+
|
|
384
|
+
Cognito holds the client secret in the identity provider's settings. Anyone allowed to call `cognito-idp:DescribeIdentityProvider` on your user pool can read it. This is how Cognito works, whichever IaC provider you use.
|
|
385
|
+
|
|
386
|
+
<Infrastructure>
|
|
387
|
+
<Fragment slot="cdk">
|
|
388
|
+
The construct passes the secret to CloudFormation as a [dynamic reference](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references-secretsmanager.html), `{{resolve:secretsmanager:<clientSecretName>:SecretString:::}}`. The synthesized template contains only that reference. CloudFormation reads the secret when it creates or updates the identity provider. If you rotate the secret, Cognito gets the new value only when the identity provider resource changes in a later deploy.
|
|
389
|
+
|
|
390
|
+
CloudFormation resolves the reference inside the identity provider's settings (`ProviderDetails`), so federated sign-in works with the stored secret, and the deployed template still holds only the reference. After a rotation, a deploy with no other change leaves the old secret in Cognito. Both have been checked on AWS.
|
|
391
|
+
</Fragment>
|
|
392
|
+
<Fragment slot="terraform">
|
|
393
|
+
The module reads the secret with a `data "aws_secretsmanager_secret_version"` data source, so `terraform plan` shows it as `(sensitive value)`. Terraform state still holds the secret in plain text, once for the data source and once for the identity provider. Anyone who can read the state object in your state bucket can read the secret. Limit read access to the state bucket accordingly.
|
|
394
|
+
|
|
395
|
+
A saved plan file, for example from `terraform plan -out`, also holds the secret in plain text. If your state bucket has versioning turned on, old versions of the state keep the secret after `terraform destroy`. Delete those versions too when you remove the stack. After a test, rotate the client secret at the identity provider.
|
|
396
|
+
</Fragment>
|
|
397
|
+
</Infrastructure>
|
|
398
|
+
|
|
399
|
+
To send a rotated secret to Cognito:
|
|
400
|
+
|
|
401
|
+
<Infrastructure>
|
|
402
|
+
<Fragment slot="cdk">
|
|
403
|
+
Change the identity provider resource in the deploy that follows the rotation. One way is to store the rotated secret under a new name and set `clientSecretName` to that name. The reference in the template then changes, so CloudFormation updates the identity provider and reads the new secret. Delete the old secret afterwards. This follows the CloudFormation documentation for dynamic references and has not been tested on AWS.
|
|
404
|
+
</Fragment>
|
|
405
|
+
<Fragment slot="terraform">
|
|
406
|
+
Run `terraform plan` and `terraform apply` after the rotation. The data source reads the current version of the secret at every plan, so the plan shows an in-place update of the identity provider, and `apply` sends the new secret to Cognito. In the `hashicorp/aws` provider source, a change to `provider_details` updates the identity provider in place and does not replace it. This has not been tested on AWS.
|
|
407
|
+
</Fragment>
|
|
408
|
+
</Infrastructure>
|
|
409
|
+
|
|
410
|
+
## Other app clients
|
|
411
|
+
|
|
412
|
+
An app client is the Cognito configuration that an application signs in through. The generator adds the identity providers to the website's app client, the web client, only. Another app client in the same user pool accepts federated users only if it lists the identity providers too. For example, the app client you create for a <Link path="guides/ts-dcr-proxy">DCR proxy</Link> (which lets MCP clients, the AI tools that use the Model Context Protocol, sign in through Cognito) needs them. Otherwise federated users cannot sign in to your MCP server.
|
|
413
|
+
|
|
414
|
+
<Infrastructure>
|
|
415
|
+
<Fragment slot="cdk">
|
|
416
|
+
An app client you create with `identity.userPool.addClient(...)` after `UserIdentity`, without `supportedIdentityProviders`, lists every identity provider of the pool and `COGNITO`. The DCR proxy example does this. If your app client sets `supportedIdentityProviders`, add the pool's identity providers to it:
|
|
417
|
+
|
|
418
|
+
```ts
|
|
419
|
+
import { UserPoolClientIdentityProvider } from 'aws-cdk-lib/aws-cognito';
|
|
420
|
+
|
|
421
|
+
supportedIdentityProviders: [
|
|
422
|
+
UserPoolClientIdentityProvider.COGNITO,
|
|
423
|
+
...identity.userPool.identityProviders.map((p) =>
|
|
424
|
+
UserPoolClientIdentityProvider.custom(p.providerName),
|
|
425
|
+
),
|
|
426
|
+
],
|
|
427
|
+
```
|
|
428
|
+
</Fragment>
|
|
429
|
+
<Fragment slot="terraform">
|
|
430
|
+
Add the `name` of each identity provider to the app client's `supported_identity_providers`, and make the app client depend on `module.user_identity`, so the identity providers exist first.
|
|
431
|
+
</Fragment>
|
|
432
|
+
</Infrastructure>
|
|
433
|
+
|
|
434
|
+
## Tokens for the agent chat
|
|
435
|
+
|
|
436
|
+
The `<agent>-chat` target of a <Link path="guides/ts-agent">TypeScript agent</Link> with Cognito authentication reads a Cognito access token from the `AGENT_ACCESS_TOKEN` environment variable. A federated user has no Cognito password, so `admin-initiate-auth` does not work for them. Instead, sign in to your website, open the browser's developer tools, and copy `access_token` from the `oidc.user:...` entry in session storage.
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
title: React Website Authentication
|
|
3
3
|
description: Reference documentation for React Website Authentication
|
|
4
4
|
generator: ts#website#auth
|
|
5
|
+
when:
|
|
6
|
+
federation: [none, oidc]
|
|
5
7
|
---
|
|
6
8
|
import { FileTree } from '@astrojs/starlight/components';
|
|
7
9
|
import Link from '@components/link.astro';
|
|
@@ -16,6 +18,8 @@ The React Website Authentication generator adds authentication to your React web
|
|
|
16
18
|
|
|
17
19
|
This generator configures the CDK or Terraform infrastructure to create a Cognito User Pool and associated Identity Pool, as well as a hosted UI for handling user login flows, and its integration with your React website.
|
|
18
20
|
|
|
21
|
+
To let users sign in through an external OpenID Connect identity provider such as Okta, Auth0 or Microsoft Entra ID, run this generator with `--federation=oidc` and list the providers on `UserIdentity`, as <Link path="guides/react-website-auth-idp">Website Identity Providers</Link> describes.
|
|
22
|
+
|
|
19
23
|
## Usage
|
|
20
24
|
|
|
21
25
|
### Add Authentication to your React Website
|
|
@@ -150,6 +154,10 @@ module "user_identity" {
|
|
|
150
154
|
This rule flags loopback addresses in query arguments as [SSRF](https://docs.aws.amazon.com/waf/latest/developerguide/aws-managed-rule-groups-list.html) attempts, which would block local sign-in since the Hosted UI receives a `localhost` `redirect_uri`. It is therefore set to [Count](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-rule-action.html#web-acl-rule-action-count) while local callback URLs are configured — matches are still logged, and every other rule blocks. Remove the local callback URLs to restore it to Block.
|
|
151
155
|
:::
|
|
152
156
|
|
|
157
|
+
#### Identity providers
|
|
158
|
+
|
|
159
|
+
To let users sign in through external OpenID Connect identity providers, run this generator with `--federation=oidc`. Then list the providers in the `oidcIdentityProviders` prop of `UserIdentity` (CDK) or the `oidc_identity_providers` variable of the `user_identity` module (Terraform), as <Link path="guides/react-website-auth-idp">Website Identity Providers</Link> describes.
|
|
160
|
+
|
|
153
161
|
## Infrastructure Usage
|
|
154
162
|
|
|
155
163
|
<Infrastructure>
|
package/generators.json
CHANGED
|
@@ -327,7 +327,7 @@
|
|
|
327
327
|
"schema": "./src/ts/website/auth/schema.json",
|
|
328
328
|
"description": "Adds auth to an existing website",
|
|
329
329
|
"metric": "g44",
|
|
330
|
-
"guidePages": ["react-website-auth"]
|
|
330
|
+
"guidePages": ["react-website-auth", "react-website-auth-idp"]
|
|
331
331
|
},
|
|
332
332
|
"ts#react-website": {
|
|
333
333
|
"factory": "./src/ts/react-website/app/generator",
|
package/package.json
CHANGED
|
@@ -45,6 +45,12 @@
|
|
|
45
45
|
"type": "boolean",
|
|
46
46
|
"description": "Whether to prefer installing dependencies after the generator runs. Set to false to defer installing when batching multiple generators (an install still runs if needed so subsequent generators can compute the Nx project graph); install once at the end.",
|
|
47
47
|
"default": true
|
|
48
|
+
},
|
|
49
|
+
"federation": {
|
|
50
|
+
"type": "string",
|
|
51
|
+
"description": "Let users sign in through external identity providers next to the user pool's own sign-in. oidc vends OpenID Connect federation; you then list the identity providers in your infrastructure code. none adds no federation, and does not remove federation that is already there.",
|
|
52
|
+
"enum": ["none", "oidc"],
|
|
53
|
+
"default": "none"
|
|
48
54
|
}
|
|
49
55
|
},
|
|
50
56
|
"required": ["project"]
|