├── .gitattributes
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── screenshot.png
├── src
├── CognitoAuthenticationFlows.sln
├── CustomAuthLambdas
│ ├── CustomAuthLambdas.csproj
│ ├── Functions.cs
│ ├── Properties
│ │ └── launchSettings.json
│ ├── Startup.cs
│ └── aws-lambda-tools-defaults.json
└── TestClient
│ ├── AuthenticationFlows
│ ├── AdminUserPasswordAuthenticator.cs
│ ├── AuthenticatorBase.cs
│ ├── CustomAuthenticator.cs
│ ├── UserPasswordAuthenticator.cs
│ ├── UserSrpAuthenticator.cs
│ └── UserSrpCustomAuthenticator.cs
│ ├── Program.cs
│ └── TestClient.csproj
└── template.yaml
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Oo]ut/
33 | [Ll]og/
34 | [Ll]ogs/
35 |
36 | # Visual Studio 2015/2017 cache/options directory
37 | .vs/
38 | # Uncomment if you have tasks that create the project's static files in wwwroot
39 | #wwwroot/
40 |
41 | # Visual Studio 2017 auto generated files
42 | Generated\ Files/
43 |
44 | # MSTest test Results
45 | [Tt]est[Rr]esult*/
46 | [Bb]uild[Ll]og.*
47 |
48 | # NUnit
49 | *.VisualState.xml
50 | TestResult.xml
51 | nunit-*.xml
52 |
53 | # Build Results of an ATL Project
54 | [Dd]ebugPS/
55 | [Rr]eleasePS/
56 | dlldata.c
57 |
58 | # Benchmark Results
59 | BenchmarkDotNet.Artifacts/
60 |
61 | # .NET Core
62 | project.lock.json
63 | project.fragment.lock.json
64 | artifacts/
65 |
66 | # ASP.NET Scaffolding
67 | ScaffoldingReadMe.txt
68 |
69 | # StyleCop
70 | StyleCopReport.xml
71 |
72 | # Files built by Visual Studio
73 | *_i.c
74 | *_p.c
75 | *_h.h
76 | *.ilk
77 | *.meta
78 | *.obj
79 | *.iobj
80 | *.pch
81 | *.pdb
82 | *.ipdb
83 | *.pgc
84 | *.pgd
85 | *.rsp
86 | *.sbr
87 | *.tlb
88 | *.tli
89 | *.tlh
90 | *.tmp
91 | *.tmp_proj
92 | *_wpftmp.csproj
93 | *.log
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio LightSwitch build output
298 | **/*.HTMLClient/GeneratedArtifacts
299 | **/*.DesktopClient/GeneratedArtifacts
300 | **/*.DesktopClient/ModelManifest.xml
301 | **/*.Server/GeneratedArtifacts
302 | **/*.Server/ModelManifest.xml
303 | _Pvt_Extensions
304 |
305 | # Paket dependency manager
306 | .paket/paket.exe
307 | paket-files/
308 |
309 | # FAKE - F# Make
310 | .fake/
311 |
312 | # CodeRush personal settings
313 | .cr/personal
314 |
315 | # Python Tools for Visual Studio (PTVS)
316 | __pycache__/
317 | *.pyc
318 |
319 | # Cake - Uncomment if you are using it
320 | # tools/**
321 | # !tools/packages.config
322 |
323 | # Tabs Studio
324 | *.tss
325 |
326 | # Telerik's JustMock configuration file
327 | *.jmconfig
328 |
329 | # BizTalk build output
330 | *.btp.cs
331 | *.btm.cs
332 | *.odx.cs
333 | *.xsd.cs
334 |
335 | # OpenCover UI analysis results
336 | OpenCover/
337 |
338 | # Azure Stream Analytics local run output
339 | ASALocalRun/
340 |
341 | # MSBuild Binary and Structured Log
342 | *.binlog
343 |
344 | # NVidia Nsight GPU debugger configuration file
345 | *.nvuser
346 |
347 | # MFractors (Xamarin productivity tool) working folder
348 | .mfractor/
349 |
350 | # Local History for Visual Studio
351 | .localhistory/
352 |
353 | # BeatPulse healthcheck temp database
354 | healthchecksdb
355 |
356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
357 | MigrationBackup/
358 |
359 | # Ionide (cross platform F# VS Code tools) working folder
360 | .ionide/
361 |
362 | # Fody - auto-generated XML schema
363 | FodyWeavers.xsd
364 |
365 | # SAM default build folder
366 | .aws-sam/
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | ## Code of Conduct
2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
4 | opensource-codeofconduct@amazon.com with any additional questions or comments.
5 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing Guidelines
2 |
3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional
4 | documentation, we greatly value feedback and contributions from our community.
5 |
6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary
7 | information to effectively respond to your bug report or contribution.
8 |
9 |
10 | ## Reporting Bugs/Feature Requests
11 |
12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features.
13 |
14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already
15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful:
16 |
17 | * A reproducible test case or series of steps
18 | * The version of our code being used
19 | * Any modifications you've made relevant to the bug
20 | * Anything unusual about your environment or deployment
21 |
22 |
23 | ## Contributing via Pull Requests
24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that:
25 |
26 | 1. You are working against the latest source on the *main* branch.
27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already.
28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted.
29 |
30 | To send us a pull request, please:
31 |
32 | 1. Fork the repository.
33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change.
34 | 3. Ensure local tests pass.
35 | 4. Commit to your fork using clear commit messages.
36 | 5. Send us a pull request, answering any default questions in the pull request interface.
37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation.
38 |
39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and
40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/).
41 |
42 |
43 | ## Finding contributions to work on
44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start.
45 |
46 |
47 | ## Code of Conduct
48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
50 | opensource-codeofconduct@amazon.com with any additional questions or comments.
51 |
52 |
53 | ## Security issue notifications
54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue.
55 |
56 |
57 | ## Licensing
58 |
59 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution.
60 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT No Attribution
2 |
3 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | this software and associated documentation files (the "Software"), to deal in
7 | the Software without restriction, including without limitation the rights to
8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | the Software, and to permit persons to whom the Software is furnished to do so.
10 |
11 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
13 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
14 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
15 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
16 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
17 |
18 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/authentication-flow-examples-with-dotnet-for-amazon-cognito/9c7475cc256e80e23905def956cb87d04153965b/README.md
--------------------------------------------------------------------------------
/screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws-samples/authentication-flow-examples-with-dotnet-for-amazon-cognito/9c7475cc256e80e23905def956cb87d04153965b/screenshot.png
--------------------------------------------------------------------------------
/src/CognitoAuthenticationFlows.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.8.34309.116
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CustomAuthLambdas", "CustomAuthLambdas\CustomAuthLambdas.csproj", "{832CE4B4-205C-4E33-B68B-53F86812F442}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestClient", "TestClient\TestClient.csproj", "{D9821C0A-DCD4-40AD-BE31-57228AA15638}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Release|Any CPU = Release|Any CPU
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {832CE4B4-205C-4E33-B68B-53F86812F442}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {832CE4B4-205C-4E33-B68B-53F86812F442}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {832CE4B4-205C-4E33-B68B-53F86812F442}.Release|Any CPU.ActiveCfg = Release|Any CPU
19 | {832CE4B4-205C-4E33-B68B-53F86812F442}.Release|Any CPU.Build.0 = Release|Any CPU
20 | {D9821C0A-DCD4-40AD-BE31-57228AA15638}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {D9821C0A-DCD4-40AD-BE31-57228AA15638}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {D9821C0A-DCD4-40AD-BE31-57228AA15638}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {D9821C0A-DCD4-40AD-BE31-57228AA15638}.Release|Any CPU.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | SolutionGuid = {CF330DFE-9E91-401C-B8F3-846CE4FE26FF}
30 | EndGlobalSection
31 | EndGlobal
32 |
--------------------------------------------------------------------------------
/src/CustomAuthLambdas/CustomAuthLambdas.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | Library
4 | enable
5 | net8.0
6 |
7 | true
8 | Lambda
9 |
10 | true
11 |
12 | true
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/src/CustomAuthLambdas/Functions.cs:
--------------------------------------------------------------------------------
1 | using Amazon.Lambda.Annotations;
2 | using Amazon.Lambda.CognitoEvents;
3 | using Amazon.Lambda.Core;
4 | using AWS.Lambda.Powertools.Logging;
5 |
6 | [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
7 |
8 | namespace CustomAuthLambdas;
9 |
10 | public class Functions
11 | {
12 |
13 | /* ======== CUSTOM_AUTH references ===========
14 | / https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-lambda-challenge.html
15 | / https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-authentication-flow.html#Using-SRP-password-verification-in-custom-authentication-flow
16 | */
17 |
18 | ///
19 | /// Constant PASSWORD_VERIFIER for ChallengeNameType
20 | ///
21 | const string PASSWORD_VERIFIER = "PASSWORD_VERIFIER";
22 |
23 | ///
24 | /// Constant CUSTOM_CHALLENGE for ChallengeNameType
25 | ///
26 | const string CUSTOM_CHALLENGE = "CUSTOM_CHALLENGE";
27 |
28 | ///
29 | /// This is the decider function that manages the authentication flow.
30 | /// In the session array that's provided to this Lambda function (event.request.session), the entire state of the authentication flow is present.
31 | ///
32 | /// If it's empty, the custom authentication flow just started. If it has items, the custom authentication flow is underway,
33 | /// a challenge was presented to the user, the user provided an answer, and it was verified to be right or wrong.
34 | /// In either case, the decider function has to decide what to do next.
35 | ///
36 | [Logging(LogEvent = true)]
37 | [LambdaFunction(MemorySize = 1024, PackageType = LambdaPackageType.Zip, ResourceName = "DefineAuthChallenge")]
38 | public CognitoDefineAuthChallengeEvent DefineAuthChallenge(CognitoDefineAuthChallengeEvent challengeEvent)
39 | {
40 | try
41 | {
42 | var previousChallenges = challengeEvent.Request.Session ?? new List();
43 |
44 | #region To support SRP_A password verification with CUSTOM_AUTH flow
45 |
46 | if (previousChallenges.Count == 1 && previousChallenges[0].ChallengeName == "SRP_A")
47 | {
48 | challengeEvent.Response.ChallengeName = PASSWORD_VERIFIER;
49 | challengeEvent.Response.IssueTokens = false;
50 | challengeEvent.Response.FailAuthentication = false;
51 |
52 | return challengeEvent;
53 | }
54 |
55 | if (previousChallenges.Count == 2 && previousChallenges[1].ChallengeName == PASSWORD_VERIFIER)
56 | {
57 | //kick-off custom flow
58 | challengeEvent.Response.ChallengeName = CUSTOM_CHALLENGE;
59 | challengeEvent.Response.IssueTokens = false;
60 | challengeEvent.Response.FailAuthentication = false;
61 |
62 | return challengeEvent;
63 | }
64 |
65 | #endregion
66 |
67 | int maxChallengesAllowed = 3;
68 | if (previousChallenges.Count >= 2 && previousChallenges[1].ChallengeName == PASSWORD_VERIFIER)
69 | {
70 | maxChallengesAllowed += 2; // since initial 2 challenges were for SRP authentication
71 | }
72 |
73 |
74 | if (previousChallenges.Count == 0)
75 | {
76 | // This will executed first time, when the auth process starts
77 | challengeEvent.Response.ChallengeName = CUSTOM_CHALLENGE;
78 | challengeEvent.Response.IssueTokens = false;
79 | challengeEvent.Response.FailAuthentication = false;
80 | }
81 | else if (previousChallenges.Count <= maxChallengesAllowed)
82 | {
83 | // This block will be executed after VerifyAuthChallengeResponse lambda is executed (user has responded to the challenge)
84 |
85 | bool success = challengeEvent.Request.Session.Last().ChallengeResult; // The ChallengeResult is whatever the VerifyAuthChallengeResponse returned in Response.AnswerCorrect
86 |
87 | if (success)
88 | {
89 | // All good, issue tokens
90 | challengeEvent.Response.IssueTokens = true;
91 | challengeEvent.Response.FailAuthentication = false;
92 | }
93 | else
94 | {
95 | // issue the challenge again
96 | challengeEvent.Response.ChallengeName = CUSTOM_CHALLENGE;
97 | challengeEvent.Response.IssueTokens = false;
98 | challengeEvent.Response.FailAuthentication = false;
99 | }
100 | }
101 | else
102 | {
103 | // The user provided a wrong answer 3 times; terminte the current auth process
104 | challengeEvent.Response.IssueTokens = false;
105 | challengeEvent.Response.FailAuthentication = true;
106 | }
107 |
108 | return challengeEvent;
109 | }
110 | catch (Exception ex)
111 | {
112 | Logger.LogError(ex);
113 |
114 | throw;
115 | }
116 | }
117 |
118 | ///
119 | /// This Lambda function is invoked, based on the instruction of the "Define Auth Challenge" trigger, to create a unique challenge for the user.
120 | /// We'll use it to generate a one-time login code and send it to the user.
121 | ///
122 | [Logging(LogEvent = true)]
123 | [LambdaFunction(MemorySize = 1024, PackageType = LambdaPackageType.Zip, ResourceName = "CreateAuthChallenge")]
124 | public CognitoCreateAuthChallengeEvent CreateAuthChallenge(CognitoCreateAuthChallengeEvent challengeEvent)
125 | {
126 | try
127 | {
128 | var previousChallenges = challengeEvent.Request.Session ?? new List();
129 |
130 | if (challengeEvent.Request.ChallengeName != CUSTOM_CHALLENGE)
131 | {
132 | return challengeEvent;
133 | }
134 |
135 | string secretLoginCode = string.Empty;
136 | string email = string.Empty;
137 |
138 | if (previousChallenges.Count == 0 || (previousChallenges.Count == 2 && previousChallenges[1].ChallengeName == PASSWORD_VERIFIER))
139 | {
140 | // This is a new auth session, generate a new secret login code and send it to the user
141 |
142 | // ACTUAL FLOW: Uncomment this
143 | //secretLoginCode = new Random(100000).Next(999999).ToString();
144 | //email = challengeEvent.Request.UserAttributes["email"];
145 | //SendEmail(challengeEvent.Request.UserAttributes["email"], secretLoginCode);
146 |
147 | // TEST FLOW
148 | secretLoginCode = "123456";
149 | email = "dummy@domain.com";
150 | }
151 | else
152 | {
153 | // This block will be executed when a user responds to the challenge, but answers incorrectly.
154 | // Since this is an existing session, no need to generate a new secret code and send it again to the user.
155 | // Retrieve the secret code from the previous challenge from the 'challengeMetadata' property.
156 | secretLoginCode = previousChallenges.Last().ChallengeMetadata;
157 | }
158 |
159 | // It is safe to create new object as child properties might be null
160 | challengeEvent.Response = new CognitoCreateAuthChallengeResponse();
161 |
162 | // This is sent back to the client app
163 | challengeEvent.Response.PublicChallengeParameters.Add("Message", $"A 6 digit code has been sent to {email}");
164 |
165 | // Add the secret login code to the private challenge parameters.
166 | // So it can be verified by the "Verify Auth Challenge Response" trigger
167 | challengeEvent.Response.PrivateChallengeParameters.Add("SecretLoginCode", secretLoginCode);
168 |
169 | // "ChallengeMetadata" field will be persisted across multiple calls to Create Auth Challenge.
170 | // so, we can use this property to store current session's secret code.
171 | // However, the pupose of this property is provide custom challenge a specific name such as CAPTCHA_CHALLENGE.
172 | challengeEvent.Response.ChallengeMetadata = secretLoginCode;
173 |
174 | return challengeEvent;
175 | }
176 | catch (Exception ex)
177 | {
178 | Logger.LogError(ex);
179 |
180 | throw;
181 | }
182 | }
183 |
184 | ///
185 | /// This Lambda function is invoked by the user pool when the user provides the answer to the challenge. Its only job is to determine if that answer is correct.
186 | ///
187 | [Logging(LogEvent = true)]
188 | [LambdaFunction(MemorySize = 1024, PackageType = LambdaPackageType.Zip, ResourceName = "VerifyAuthChallenge")]
189 | public CognitoVerifyAuthChallengeEvent VerifyAuthChallenge(CognitoVerifyAuthChallengeEvent challengeEvent)
190 | {
191 | try
192 | {
193 | string expectedAnswer = challengeEvent.Request.PrivateChallengeParameters["SecretLoginCode"];
194 |
195 | if (challengeEvent.Request.ChallengeAnswer == expectedAnswer)
196 | {
197 | challengeEvent.Response.AnswerCorrect = true;
198 | }
199 | else
200 | {
201 | challengeEvent.Response.AnswerCorrect = false;
202 | }
203 |
204 | return challengeEvent;
205 | }
206 | catch (Exception ex)
207 | {
208 | Logger.LogError(ex);
209 |
210 | throw;
211 | }
212 | }
213 | }
214 |
--------------------------------------------------------------------------------
/src/CustomAuthLambdas/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "profiles": {
3 | "Mock Lambda Test Tool": {
4 | "commandName": "Executable",
5 | "commandLineArgs": "--port 5050",
6 | "workingDirectory": ".\\bin\\$(Configuration)\\net8.0",
7 | "executablePath": "%USERPROFILE%\\.dotnet\\tools\\dotnet-lambda-test-tool-8.0.exe"
8 | }
9 | }
10 | }
--------------------------------------------------------------------------------
/src/CustomAuthLambdas/Startup.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.DependencyInjection;
2 |
3 | namespace AuthLambdas;
4 |
5 | [Amazon.Lambda.Annotations.LambdaStartup]
6 | public class Startup
7 | {
8 | public void ConfigureServices(IServiceCollection services)
9 | {
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/CustomAuthLambdas/aws-lambda-tools-defaults.json:
--------------------------------------------------------------------------------
1 | {
2 | "Information": [
3 | "This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.",
4 | "To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.",
5 | "dotnet lambda help",
6 | "All the command line options for the Lambda command can be specified in this file."
7 | ],
8 | "profile": "default",
9 | "region": "ap-south-1",
10 | "configuration": "Release",
11 | "s3-prefix": "AuthLambdas/",
12 | "template": "serverless.template",
13 | "template-parameters": "",
14 | "docker-host-build-output-dir": "./bin/Release/lambda-publish"
15 | }
--------------------------------------------------------------------------------
/src/TestClient/AuthenticationFlows/AdminUserPasswordAuthenticator.cs:
--------------------------------------------------------------------------------
1 | using Amazon.CognitoIdentityProvider;
2 | using Amazon.CognitoIdentityProvider.Model;
3 | using Amazon.Extensions.CognitoAuthentication;
4 |
5 | namespace TestClient.AuthenticationFlows
6 | {
7 | ///
8 | /// This class provides examples of ADMIN_USER_PASSWORD_AUTH
9 | ///
10 | public class AdminUserPasswordAuthenticator: AuthenticatorBase
11 | {
12 | private readonly IAmazonCognitoIdentityProvider cognitoProvider;
13 |
14 | public AdminUserPasswordAuthenticator( IAmazonCognitoIdentityProvider cognitoProvider)
15 | {
16 | this.cognitoProvider = cognitoProvider;
17 | }
18 |
19 | ///
20 | /// Example of ADMIN_USER_PASSWORD_AUTH using AWSSDK.CognitoIdentityProvider
21 | ///
22 | public async Task Authenticate(string username, string password, string clientId, string userpoolId)
23 | {
24 | try
25 | {
26 | var authParameters = new Dictionary
27 | {
28 | { "USERNAME", username },
29 | { "PASSWORD", password }
30 | };
31 |
32 | var authRequest = new AdminInitiateAuthRequest
33 | {
34 | ClientId = clientId,
35 | UserPoolId = userpoolId,
36 | AuthParameters = authParameters,
37 | AuthFlow = AuthFlowType.ADMIN_USER_PASSWORD_AUTH,
38 | };
39 |
40 | var authResponse = await cognitoProvider.AdminInitiateAuthAsync(authRequest);
41 |
42 | if (authResponse.AuthenticationResult != null)
43 | {
44 | PrintSuccessResult(AuthFlowType.ADMIN_USER_PASSWORD_AUTH, authResponse.AuthenticationResult);
45 | }
46 | else
47 | {
48 | // RespondToAuthChallenge is required for the next challenge i.e. SMS_MFA, MFA_SETUP, etc.
49 | Console.WriteLine($"Additional challenge {authResponse.ChallengeName} is required");
50 | }
51 | }
52 | catch (Exception ex)
53 | {
54 | WriteError(ex.Message);
55 | }
56 | }
57 |
58 | ///
59 | /// Example of ADMIN_USER_PASSWORD_AUTH using Amazon.Extensions.CognitoAuthentication
60 | ///
61 | public async Task AuthenticateWithExtensionLibrary(string username, string password, string clientId, string userpoolId)
62 | {
63 | try
64 | {
65 | var userPool = new CognitoUserPool(userpoolId, clientId, cognitoProvider);
66 | var user = new CognitoUser(username, clientId, userPool, cognitoProvider);
67 |
68 | AuthFlowResponse authResponse = await user.StartWithAdminNoSrpAuthAsync(new InitiateAdminNoSrpAuthRequest()
69 | {
70 | Password = password
71 | }).ConfigureAwait(false);
72 |
73 |
74 | authResponse = await HandleAdditionalChallenges(user, authResponse).ConfigureAwait(false);
75 |
76 | if (authResponse.AuthenticationResult != null)
77 | {
78 | PrintSuccessResult(AuthFlowType.ADMIN_USER_PASSWORD_AUTH, authResponse.AuthenticationResult);
79 | }
80 | else
81 | {
82 | Console.WriteLine("Failed to authenticate");
83 | }
84 | }
85 | catch (Exception ex)
86 | {
87 | WriteError(ex.Message);
88 | }
89 | }
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/src/TestClient/AuthenticationFlows/AuthenticatorBase.cs:
--------------------------------------------------------------------------------
1 | using Amazon.CognitoIdentityProvider;
2 | using Amazon.CognitoIdentityProvider.Model;
3 | using Amazon.Extensions.CognitoAuthentication;
4 |
5 | namespace TestClient.AuthenticationFlows
6 | {
7 | public class AuthenticatorBase
8 | {
9 | ///
10 | /// Handles additional challenges
11 | ///
12 | protected static async Task HandleAdditionalChallenges(CognitoUser user, AuthFlowResponse authResponse)
13 | {
14 | // Authenticating with Multiple Forms of Authentication
15 | while (authResponse.AuthenticationResult == null)
16 | {
17 | if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
18 | {
19 | Console.WriteLine("Enter your desired new password:");
20 | string newPassword = Console.ReadLine() ?? string.Empty;
21 |
22 | authResponse = await user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest()
23 | {
24 | SessionID = authResponse.SessionID,
25 | NewPassword = newPassword
26 | }).ConfigureAwait(false);
27 | }
28 | else if (authResponse.ChallengeName == ChallengeNameType.SMS_MFA)
29 | {
30 | Console.WriteLine("Enter the MFA Code sent to your device:");
31 | string mfaCode = Console.ReadLine() ?? string.Empty;
32 |
33 | authResponse = await user.RespondToSmsMfaAuthAsync(new RespondToSmsMfaRequest()
34 | {
35 | SessionID = authResponse.SessionID,
36 | MfaCode = mfaCode
37 | }).ConfigureAwait(false);
38 | }
39 | else if (authResponse.ChallengeName == ChallengeNameType.CUSTOM_CHALLENGE)
40 | {
41 | Console.WriteLine("Enter the secret code: (Hint: Enter 123456 for this demo)"); // since the same is configured in CreateAuthChallenge lambda function
42 |
43 | string secretCode = Console.ReadLine() ?? string.Empty;
44 |
45 | var challengeParameters = new Dictionary
46 | {
47 | { "USERNAME", user.Username },
48 | { "ANSWER", secretCode }
49 | };
50 |
51 | authResponse = await user.RespondToCustomAuthAsync(new RespondToCustomChallengeRequest()
52 | {
53 | SessionID = authResponse.SessionID,
54 | ChallengeParameters = challengeParameters
55 | }).ConfigureAwait(false);
56 | }
57 | else
58 | {
59 | Console.WriteLine("Unrecognized authentication challenge.");
60 | break;
61 | }
62 | }
63 |
64 | return authResponse;
65 | }
66 |
67 | ///
68 | /// Prints authentication result
69 | ///
70 | protected void PrintSuccessResult(AuthFlowType authFlowType, AuthenticationResultType authenticationResult)
71 | {
72 | Console.ForegroundColor = ConsoleColor.Green;
73 | Console.BackgroundColor = ConsoleColor.Black;
74 | Console.WriteLine($"Authentication successful for {authFlowType}");
75 | Console.ResetColor();
76 |
77 | //You get ID_Token and Access_Token here
78 | //Console.WriteLine(JsonSerializer.Serialize(authenticationResult));
79 | }
80 |
81 | ///
82 | /// Prints error message in red color
83 | ///
84 | protected static void WriteError(string buffer)
85 | {
86 | Console.ForegroundColor = ConsoleColor.Red;
87 | Console.BackgroundColor = ConsoleColor.Black;
88 | Console.WriteLine(buffer);
89 | Console.ResetColor();
90 | }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/src/TestClient/AuthenticationFlows/CustomAuthenticator.cs:
--------------------------------------------------------------------------------
1 | using Amazon.CognitoIdentityProvider;
2 | using Amazon.CognitoIdentityProvider.Model;
3 | using Amazon.Extensions.CognitoAuthentication;
4 |
5 | namespace TestClient.AuthenticationFlows
6 | {
7 | ///
8 | /// This class provides examples of CUSTOM_AUTH
9 | ///
10 | public class CustomAuthenticator : AuthenticatorBase
11 | {
12 | private readonly IAmazonCognitoIdentityProvider cognitoProvider;
13 |
14 | public CustomAuthenticator(IAmazonCognitoIdentityProvider cognitoProvider)
15 | {
16 | this.cognitoProvider = cognitoProvider;
17 | }
18 |
19 | ///
20 | /// Example of CUSTOM_AUTH using AWSSDK.CognitoIdentityProvider
21 | ///
22 | public async Task Authenticate(string username, string clientId)
23 | {
24 | try
25 | {
26 | var authParameters = new Dictionary
27 | {
28 | { "USERNAME", username }
29 | };
30 |
31 | var authRequest = new InitiateAuthRequest
32 | {
33 | ClientId = clientId,
34 | AuthParameters = authParameters,
35 | AuthFlow = AuthFlowType.CUSTOM_AUTH,
36 | };
37 |
38 | var authResponse = await cognitoProvider.InitiateAuthAsync(authRequest);
39 |
40 | if (authResponse.AuthenticationResult == null)
41 | {
42 | if (authResponse.ChallengeName == ChallengeNameType.CUSTOM_CHALLENGE)
43 | {
44 | // just set few properties to make this while loop work properly
45 | var challengeAuthResponse = new RespondToAuthChallengeResponse();
46 | challengeAuthResponse.AuthenticationResult = null;
47 | challengeAuthResponse.Session = authResponse.Session;
48 |
49 | while (challengeAuthResponse.AuthenticationResult == null)
50 | {
51 | Console.WriteLine("Enter the secret code: (Hint: Enter 123456 for this demo)"); // since the same is configured in CreateAuthChallenge lambda function
52 |
53 | string secretCode = Console.ReadLine() ?? string.Empty;
54 |
55 | var challengeResponse = new Dictionary
56 | {
57 | { "USERNAME", username },
58 | { "ANSWER", secretCode }
59 | };
60 |
61 | var challengeRequest = new RespondToAuthChallengeRequest
62 | {
63 | ChallengeName = authResponse.ChallengeName,
64 | ClientId = clientId,
65 | ChallengeResponses = challengeResponse,
66 | Session = challengeAuthResponse.Session
67 | };
68 |
69 | challengeAuthResponse = await cognitoProvider.RespondToAuthChallengeAsync(challengeRequest);
70 | }
71 |
72 | if (challengeAuthResponse.AuthenticationResult != null)
73 | {
74 | PrintSuccessResult(AuthFlowType.CUSTOM_AUTH, challengeAuthResponse.AuthenticationResult);
75 | }
76 | else
77 | {
78 | // though, this is never supposed to execute, as you'll get exception after certain attempts
79 | Console.WriteLine($"Additional challenge {challengeAuthResponse.ChallengeName} is required");
80 | }
81 | }
82 | else
83 | {
84 | Console.WriteLine("Unrecognized authentication challenge.");
85 | }
86 | }
87 | else
88 | {
89 | Console.WriteLine($"Invalid setup. You're not supposed to get the token at this stage.");
90 | }
91 | }
92 | catch (Exception ex)
93 | {
94 | WriteError(ex.Message);
95 | }
96 | }
97 |
98 | ///
99 | /// Example of CUSTOM_AUTH using Amazon.Extensions.CognitoAuthentication
100 | ///
101 | public async Task AuthenticateWithExtensionLibrary(string username, string clientId, string userpoolId)
102 | {
103 | try
104 | {
105 | var userPool = new CognitoUserPool(userpoolId, clientId, cognitoProvider);
106 | var user = new CognitoUser(username, clientId, userPool, cognitoProvider);
107 |
108 | var authParameters = new Dictionary
109 | {
110 | { "USERNAME", username }
111 | };
112 |
113 | AuthFlowResponse authResponse = await user.StartWithCustomAuthAsync(new InitiateCustomAuthRequest()
114 | {
115 | AuthParameters = authParameters,
116 | ClientMetadata = new Dictionary()
117 | }).ConfigureAwait(false);
118 |
119 |
120 | authResponse = await HandleAdditionalChallenges(user, authResponse).ConfigureAwait(false);
121 |
122 | if (authResponse.AuthenticationResult != null)
123 | {
124 | PrintSuccessResult(AuthFlowType.CUSTOM_AUTH, authResponse.AuthenticationResult);
125 | }
126 | else
127 | {
128 | Console.WriteLine("Failed to authenticate");
129 | }
130 | }
131 | catch (Exception ex)
132 | {
133 | WriteError(ex.Message);
134 | }
135 | }
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/src/TestClient/AuthenticationFlows/UserPasswordAuthenticator.cs:
--------------------------------------------------------------------------------
1 | using Amazon.CognitoIdentityProvider;
2 | using Amazon.CognitoIdentityProvider.Model;
3 |
4 | namespace TestClient.AuthenticationFlows
5 | {
6 |
7 | ///
8 | /// This class provides examples of USER_PASSWORD_AUTH
9 | ///
10 | public class UserPasswordAuthenticator : AuthenticatorBase
11 | {
12 | private readonly IAmazonCognitoIdentityProvider cognitoProvider;
13 |
14 | public UserPasswordAuthenticator(IAmazonCognitoIdentityProvider cognitoProvider)
15 | {
16 | this.cognitoProvider = cognitoProvider;
17 | }
18 |
19 | ///
20 | /// Example of USER_PASSWORD_AUTH using AWSSDK.CognitoIdentityProvider
21 | ///
22 | public async Task Authenticate(string username, string password, string clientId)
23 | {
24 | try
25 | {
26 | var authParameters = new Dictionary
27 | {
28 | { "USERNAME", username },
29 | { "PASSWORD", password }
30 | };
31 |
32 | var authRequest = new InitiateAuthRequest
33 | {
34 | ClientId = clientId,
35 | AuthParameters = authParameters,
36 | AuthFlow = AuthFlowType.USER_PASSWORD_AUTH,
37 | };
38 |
39 | var authResponse = await cognitoProvider.InitiateAuthAsync(authRequest);
40 |
41 | if (authResponse.AuthenticationResult != null)
42 | {
43 | PrintSuccessResult(AuthFlowType.USER_PASSWORD_AUTH, authResponse.AuthenticationResult);
44 | }
45 | else
46 | {
47 | // RespondToAuthChallenge is required for the next challenge i.e. SMS_MFA, MFA_SETUP, etc.
48 | Console.WriteLine($"Additional challenge {authResponse.ChallengeName} is required");
49 | }
50 | }
51 | catch (Exception ex)
52 | {
53 | WriteError(ex.Message);
54 | }
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/TestClient/AuthenticationFlows/UserSrpAuthenticator.cs:
--------------------------------------------------------------------------------
1 | using Amazon.CognitoIdentityProvider;
2 | using Amazon.Extensions.CognitoAuthentication;
3 |
4 | namespace TestClient.AuthenticationFlows
5 | {
6 | ///
7 | /// This class provides examples of USER_SRP_AUTH
8 | ///
9 | public class UserSrpAuthenticator : AuthenticatorBase
10 | {
11 | private readonly IAmazonCognitoIdentityProvider cognitoProvider;
12 |
13 | public UserSrpAuthenticator(IAmazonCognitoIdentityProvider cognitoProvider)
14 | {
15 | this.cognitoProvider = cognitoProvider;
16 | }
17 |
18 | ///
19 | /// Example of USER_SRP_AUTH using Amazon.Extensions.CognitoAuthentication
20 | ///
21 | public async Task AuthenticateWithExtensionLibrary(string username, string password, string clientId, string userpoolId)
22 | {
23 | try
24 | {
25 | var userPool = new CognitoUserPool(userpoolId, clientId, cognitoProvider);
26 | var user = new CognitoUser(username, clientId, userPool, cognitoProvider);
27 |
28 | AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
29 | {
30 | Password = password
31 | }).ConfigureAwait(false);
32 |
33 |
34 | authResponse = await HandleAdditionalChallenges(user, authResponse).ConfigureAwait(false);
35 |
36 | if (authResponse.AuthenticationResult != null)
37 | {
38 | PrintSuccessResult(AuthFlowType.USER_SRP_AUTH, authResponse.AuthenticationResult);
39 | }
40 | else
41 | {
42 | Console.WriteLine("Failed to authenticate");
43 | }
44 | }
45 | catch (Exception ex)
46 | {
47 | WriteError(ex.Message);
48 | }
49 | }
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/TestClient/AuthenticationFlows/UserSrpCustomAuthenticator.cs:
--------------------------------------------------------------------------------
1 | using Amazon.CognitoIdentityProvider;
2 | using Amazon.Extensions.CognitoAuthentication;
3 |
4 | namespace TestClient.AuthenticationFlows
5 | {
6 | ///
7 | /// This class provides examples of CUSTOM_AUTH with SRP Password Verification
8 | ///
9 | public class UserSrpCustomAuthenticator : AuthenticatorBase
10 | {
11 | private readonly IAmazonCognitoIdentityProvider cognitoProvider;
12 |
13 | public UserSrpCustomAuthenticator(IAmazonCognitoIdentityProvider cognitoProvider)
14 | {
15 | this.cognitoProvider = cognitoProvider;
16 | }
17 |
18 | ///
19 | /// Example of CUSTOM_AUTH with SRP Password Verification using Amazon.Extensions.CognitoAuthentication
20 | ///
21 | public async Task AuthenticateWithExtensionLibrary(string username, string password, string clientId, string userpoolId)
22 | {
23 | try
24 | {
25 | var userPool = new CognitoUserPool(userpoolId, clientId, cognitoProvider);
26 | var user = new CognitoUser(username, clientId, userPool, cognitoProvider);
27 |
28 | AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
29 | {
30 | IsCustomAuthFlow = true, // <-- this is key thing
31 | Password = password
32 | }).ConfigureAwait(false);
33 |
34 |
35 | authResponse = await HandleAdditionalChallenges(user, authResponse).ConfigureAwait(false);
36 |
37 | if (authResponse.AuthenticationResult != null)
38 | {
39 | PrintSuccessResult(AuthFlowType.CUSTOM_AUTH, authResponse.AuthenticationResult);
40 | }
41 | else
42 | {
43 | Console.WriteLine("Failed to authenticate");
44 | }
45 | }
46 | catch (Exception ex)
47 | {
48 | WriteError(ex.Message);
49 | }
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/TestClient/Program.cs:
--------------------------------------------------------------------------------
1 | using Amazon.CognitoIdentityProvider;
2 | using Amazon.Runtime;
3 | using TestClient.AuthenticationFlows;
4 |
5 | // Replace these placeholders with their actual values
6 | string userName = ""; // use the email address of the cognito user
7 | string password = ""; // use the password of the cognito user
8 | string clientId = ""; // get this from deployment output
9 | string userpoolId = ""; // get this from deployment output
10 |
11 | // The Amazon Cognito service client with anonymous credentials
12 | var cognitoProvider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), FallbackRegionFactory.GetRegionEndpoint());
13 |
14 | // The Amazon Cognito service client with developers IAM credentials, since, AdminInitiateAuth API is meant to be called from a back-end which has access to IAM credentials.
15 | var cognitoProviderForAdmin = new AmazonCognitoIdentityProviderClient(FallbackRegionFactory.GetRegionEndpoint());
16 |
17 |
18 | // USER_PASSWORD_AUTH
19 | Console.WriteLine("USER_PASSWORD_AUTH Authentication Started");
20 | await new UserPasswordAuthenticator(cognitoProvider).Authenticate(userName, password, clientId);
21 | Console.WriteLine("USER_PASSWORD_AUTH Completed\n");
22 |
23 |
24 | // USER_SRP_AUTH
25 | Console.WriteLine("USER_SRP_AUTH Authentication Started");
26 | await new UserSrpAuthenticator(cognitoProvider).AuthenticateWithExtensionLibrary(userName, password, clientId, userpoolId);
27 | Console.WriteLine("USER_SRP_AUTH Completed\n");
28 |
29 |
30 | // ADMIN_USER_PASSWORD_AUTH
31 | Console.WriteLine("ADMIN_USER_PASSWORD_AUTH(1) Authentication Started");
32 | await new AdminUserPasswordAuthenticator(cognitoProviderForAdmin).Authenticate(userName, password, clientId, userpoolId);
33 | Console.WriteLine("ADMIN_USER_PASSWORD_AUTH(1) Completed\n");
34 |
35 | Console.WriteLine("ADMIN_USER_PASSWORD_AUTH(2) Authentication Started");
36 | await new AdminUserPasswordAuthenticator(cognitoProviderForAdmin).AuthenticateWithExtensionLibrary(userName, password, clientId, userpoolId);
37 | Console.WriteLine("ADMIN_USER_PASSWORD_AUTH(2) Completed\n");
38 |
39 |
40 | // CUSTOM_AUTH
41 | Console.WriteLine("CUSTOM_AUTH(1) Authentication Started");
42 | await new CustomAuthenticator(cognitoProvider).Authenticate(userName, clientId);
43 | Console.WriteLine("CUSTOM_AUTH(1) Completed\n");
44 |
45 | Console.WriteLine("CUSTOM_AUTH(2) Authentication Started");
46 | await new CustomAuthenticator(cognitoProvider).AuthenticateWithExtensionLibrary(userName, clientId, userpoolId);
47 | Console.WriteLine("CUSTOM_AUTH(2) Completed\n");
48 |
49 |
50 | // CUSTOM_AUTH with SRP password verification
51 | Console.WriteLine("CUSTOM_AUTH With SRP Authentication Started");
52 | await new UserSrpCustomAuthenticator(cognitoProvider).AuthenticateWithExtensionLibrary(userName, password, clientId, userpoolId);
53 | Console.WriteLine("CUSTOM_AUTH With SRP Completed \n");
54 |
55 | Console.WriteLine("You're all done! You can now close the window.");
56 | Console.ReadLine();
57 |
58 |
--------------------------------------------------------------------------------
/src/TestClient/TestClient.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net8.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/template.yaml:
--------------------------------------------------------------------------------
1 | AWSTemplateFormatVersion: '2010-09-09'
2 | Transform: AWS::Serverless-2016-10-31
3 | Description: SAM template for the demo of Cognito Authentication Flows with .NET
4 | Resources:
5 | DefineAuthChallenge:
6 | Type: AWS::Serverless::Function
7 | Metadata:
8 | Tool: Amazon.Lambda.Annotations
9 | Properties:
10 | Runtime: dotnet8
11 | CodeUri: ./src/CustomAuthLambdas
12 | MemorySize: 1024
13 | Timeout: 30
14 | Policies:
15 | - AWSLambdaBasicExecutionRole
16 | PackageType: Zip
17 | Handler: CustomAuthLambdas::CustomAuthLambdas.Functions_DefineAuthChallenge_Generated::DefineAuthChallenge
18 | ReservedConcurrentExecutions: 50
19 | CreateAuthChallenge:
20 | Type: AWS::Serverless::Function
21 | Metadata:
22 | Tool: Amazon.Lambda.Annotations
23 | Properties:
24 | Runtime: dotnet8
25 | CodeUri: ./src/CustomAuthLambdas
26 | MemorySize: 1024
27 | Timeout: 30
28 | Policies:
29 | - AWSLambdaBasicExecutionRole
30 | PackageType: Zip
31 | Handler: CustomAuthLambdas::CustomAuthLambdas.Functions_CreateAuthChallenge_Generated::CreateAuthChallenge
32 | ReservedConcurrentExecutions: 50
33 | VerifyAuthChallenge:
34 | Type: AWS::Serverless::Function
35 | Metadata:
36 | Tool: Amazon.Lambda.Annotations
37 | Properties:
38 | Runtime: dotnet8
39 | CodeUri: ./src/CustomAuthLambdas
40 | MemorySize: 1024
41 | Timeout: 30
42 | Policies:
43 | - AWSLambdaBasicExecutionRole
44 | PackageType: Zip
45 | Handler: CustomAuthLambdas::CustomAuthLambdas.Functions_VerifyAuthChallenge_Generated::VerifyAuthChallenge
46 | ReservedConcurrentExecutions: 50
47 | DefineAuthChallengeLambdaPermission:
48 | Type: AWS::Lambda::Permission
49 | Properties:
50 | Action: lambda:InvokeFunction
51 | FunctionName: !Ref 'DefineAuthChallenge'
52 | Principal: cognito-idp.amazonaws.com
53 | SourceArn: !GetAtt 'CognitoUserPool.Arn'
54 | CreateAuthChallengeLambdaPermission:
55 | Type: AWS::Lambda::Permission
56 | Properties:
57 | Action: lambda:InvokeFunction
58 | FunctionName: !Ref 'CreateAuthChallenge'
59 | Principal: cognito-idp.amazonaws.com
60 | SourceArn: !GetAtt 'CognitoUserPool.Arn'
61 | VerifyAuthChallengeLambdaPermission:
62 | Type: AWS::Lambda::Permission
63 | Properties:
64 | Action: lambda:InvokeFunction
65 | FunctionName: !Ref 'VerifyAuthChallenge'
66 | Principal: cognito-idp.amazonaws.com
67 | SourceArn: !GetAtt 'CognitoUserPool.Arn'
68 | CognitoUserPool:
69 | Type: AWS::Cognito::UserPool
70 | Properties:
71 | UserPoolName: authflow-demo-userpool
72 | UsernameAttributes:
73 | - email
74 | AutoVerifiedAttributes:
75 | - email
76 | LambdaConfig:
77 | DefineAuthChallenge: !GetAtt 'DefineAuthChallenge.Arn'
78 | CreateAuthChallenge: !GetAtt 'CreateAuthChallenge.Arn'
79 | VerifyAuthChallengeResponse: !GetAtt 'VerifyAuthChallenge.Arn'
80 | CognitoUserPoolClient:
81 | Type: AWS::Cognito::UserPoolClient
82 | Properties:
83 | SupportedIdentityProviders:
84 | - COGNITO
85 | ClientName: authflow-demo-userpool
86 | UserPoolId: !Ref 'CognitoUserPool'
87 | ExplicitAuthFlows:
88 | - ALLOW_USER_SRP_AUTH
89 | - ALLOW_USER_PASSWORD_AUTH
90 | - ALLOW_ADMIN_USER_PASSWORD_AUTH
91 | - ALLOW_CUSTOM_AUTH
92 | - ALLOW_REFRESH_TOKEN_AUTH
93 | Outputs:
94 | UserpoolId:
95 | Value: !Ref CognitoUserPool
96 | Description: Cognito UserPool Id
97 | ClientId:
98 | Value: !Ref CognitoUserPoolClient
99 | Description: Cognito UserPool ClientId
--------------------------------------------------------------------------------