├── .gitignore ├── LICENSE ├── README.md ├── SimpleTokenProvider.sln ├── src └── SimpleTokenProvider │ ├── SimpleTokenProvider.csproj │ ├── TokenProviderAppBuilderExtensions.cs │ ├── TokenProviderMiddleware.cs │ └── TokenProviderOptions.cs └── test └── SimpleTokenProvider.Test ├── Controllers ├── MeController.cs └── ValuesController.cs ├── CustomJwtDataFormat.cs ├── Program.cs ├── Properties └── launchSettings.json ├── SimpleTokenProvider.Test.csproj ├── Startup.Auth.cs ├── Startup.cs ├── appsettings.json └── web.config /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | build/ 21 | bld/ 22 | [Bb]in/ 23 | [Oo]bj/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | 84 | # Visual Studio profiler 85 | *.psess 86 | *.vsp 87 | *.vspx 88 | *.sap 89 | 90 | # TFS 2012 Local Workspace 91 | $tf/ 92 | 93 | # Guidance Automation Toolkit 94 | *.gpState 95 | 96 | # ReSharper is a .NET coding add-in 97 | _ReSharper*/ 98 | *.[Rr]e[Ss]harper 99 | *.DotSettings.user 100 | 101 | # JustCode is a .NET coding add-in 102 | .JustCode 103 | 104 | # TeamCity is a build add-in 105 | _TeamCity* 106 | 107 | # DotCover is a Code Coverage Tool 108 | *.dotCover 109 | 110 | # NCrunch 111 | _NCrunch_* 112 | .*crunch*.local.xml 113 | nCrunchTemp_* 114 | 115 | # MightyMoose 116 | *.mm.* 117 | AutoTest.Net/ 118 | 119 | # Web workbench (sass) 120 | .sass-cache/ 121 | 122 | # Installshield output folder 123 | [Ee]xpress/ 124 | 125 | # DocProject is a documentation generator add-in 126 | DocProject/buildhelp/ 127 | DocProject/Help/*.HxT 128 | DocProject/Help/*.HxC 129 | DocProject/Help/*.hhc 130 | DocProject/Help/*.hhk 131 | DocProject/Help/*.hhp 132 | DocProject/Help/Html2 133 | DocProject/Help/html 134 | 135 | # Click-Once directory 136 | publish/ 137 | 138 | # Publish Web Output 139 | *.[Pp]ublish.xml 140 | *.azurePubxml 141 | # TODO: Comment the next line if you want to checkin your web deploy settings 142 | # but database connection strings (with potential passwords) will be unencrypted 143 | *.pubxml 144 | *.publishproj 145 | 146 | # NuGet Packages 147 | *.nupkg 148 | # The packages folder can be ignored because of Package Restore 149 | **/packages/* 150 | # except build/, which is used as an MSBuild target. 151 | !**/packages/build/ 152 | # Uncomment if necessary however generally it will be regenerated when needed 153 | #!**/packages/repositories.config 154 | 155 | # Microsoft Azure Build Output 156 | csx/ 157 | *.build.csdef 158 | 159 | # Microsoft Azure Emulator 160 | ecf/ 161 | rcf/ 162 | 163 | # Microsoft Azure ApplicationInsights config file 164 | ApplicationInsights.config 165 | 166 | # Windows Store app package directory 167 | AppPackages/ 168 | BundleArtifacts/ 169 | 170 | # Visual Studio cache files 171 | # files ending in .cache can be ignored 172 | *.[Cc]ache 173 | # but keep track of directories ending in .cache 174 | !*.[Cc]ache/ 175 | 176 | # Others 177 | ClientBin/ 178 | ~$* 179 | *~ 180 | *.dbmdl 181 | *.dbproj.schemaview 182 | *.pfx 183 | *.publishsettings 184 | node_modules/ 185 | orleans.codegen.cs 186 | 187 | # RIA/Silverlight projects 188 | Generated_Code/ 189 | 190 | # Backup & report files from converting an old project file 191 | # to a newer Visual Studio version. Backup files are not needed, 192 | # because we have git ;-) 193 | _UpgradeReport_Files/ 194 | Backup*/ 195 | UpgradeLog*.XML 196 | UpgradeLog*.htm 197 | 198 | # SQL Server files 199 | *.mdf 200 | *.ldf 201 | 202 | # Business Intelligence projects 203 | *.rdl.data 204 | *.bim.layout 205 | *.bim_*.settings 206 | 207 | # Microsoft Fakes 208 | FakesAssemblies/ 209 | 210 | # GhostDoc plugin setting file 211 | *.GhostDoc.xml 212 | 213 | # Node.js Tools for Visual Studio 214 | .ntvs_analysis.dat 215 | 216 | # Visual Studio 6 build log 217 | *.plg 218 | 219 | # Visual Studio 6 workspace options file 220 | *.opt 221 | 222 | # Visual Studio LightSwitch build output 223 | **/*.HTMLClient/GeneratedArtifacts 224 | **/*.DesktopClient/GeneratedArtifacts 225 | **/*.DesktopClient/ModelManifest.xml 226 | **/*.Server/GeneratedArtifacts 227 | **/*.Server/ModelManifest.xml 228 | _Pvt_Extensions 229 | 230 | # Paket dependency manager 231 | .paket/paket.exe 232 | 233 | # FAKE - F# Make 234 | .fake/ 235 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Simple Token Provider Middleware for ASP.NET 2 | 3 | ### :warning: Deprecated: This project and the concepts it uses are outdated! 4 | At the time it was created, there weren't many resources available for token authentication in early ASP.NET Core. Nowadays, I would not recommend doing this yourself! 5 | 6 | Here are some resources for doing token authentication in modern ASP.NET Core: 7 | - [Bearer Token Authentication in ASP.NET Core](https://devblogs.microsoft.com/dotnet/bearer-token-authentication-in-asp-net-core/) on the Microsoft .NET blog 8 | - [OpenIddict](https://documentation.openiddict.com/) 9 | 10 | --- 11 | 12 | This project demonstrates how to generate [JSON Web Tokens](https://en.wikipedia.org/wiki/JSON_Web_Token) (JWTs) for token authentication in ASP.NET Core RC2. The functionality is wrapped up in a reusable middleware component. 13 | 14 | Original blog post: [Token Authentication in ASP.NET Core](https://stormpath.com/blog/token-authentication-asp-net-core) 15 | 16 | This has **not** been tested in production, so explore and use at your own risk! 17 | 18 | ## Configuring the middleware 19 | 20 | The token provider endpoint can be added to your pipeline in `Configure()`: 21 | 22 | ```csharp 23 | app.UseSimpleTokenProvider(new TokenProviderOptions 24 | { 25 | Path = "/api/token", 26 | Audience = "ExampleAudience", 27 | Issuer = "ExampleIssuer", 28 | SigningCredentials = signingCredentials, 29 | IdentityResolver = GetIdentity 30 | }); 31 | ``` 32 | 33 | The options are: 34 | 35 | * **Path** (optional) - The endpoint path relative to the server root. Default: `/token` 36 | * **Audience** - The JWT `aud` claim value. 37 | * **Issuer** - The JWT `iss` claim value. 38 | * **Expiration** (optional) - The expiration duration for new tokens. Default: 5 minutes 39 | * **SigningCredentials** - The signing credentials to use when signing new tokens. 40 | * **IdentityResolver** - A delegate that takes a username/password and returns a `ClaimsIdentity` if the user exists, or `null` if the user does not exist. 41 | * **NonceGenerator** (optional) - A delegate that generates a random value (nonce) for each new token. Default: `Guid.NewGuid()` 42 | 43 | If you are using an HMAC-SHA256 key (symmetric signing), the `SigningCredentials` will look like: 44 | 45 | ```csharp 46 | // The secret key every token will be signed with. 47 | // Keep this safe on the server! 48 | var secretKey = "mysupersecret_secretkey!123"; 49 | 50 | var signingCredentials = new SigningCredentials( 51 | new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)), 52 | SecurityAlgorithms.HmacSha256); 53 | ``` 54 | 55 | The `IdentityResolver` delegate abstracts away the concern of looking up and verifying a user given a username and password. If the user exists and the password is valid, a `ClaimsIdentity` should be returned. If not, the delegate should return null. 56 | 57 | You can use the following dummy resolver for testing: **(don't use in production!)** 58 | 59 | ```csharp 60 | private Task GetIdentity(string username, string password) 61 | { 62 | // Don't do this in production, obviously! 63 | if (username == "TEST" && password == "TEST123") 64 | { 65 | return Task.FromResult(new ClaimsIdentity(new GenericIdentity(username, "Token"), new Claim[] { })); 66 | } 67 | 68 | // Credentials are invalid, or account doesn't exist 69 | return Task.FromResult(null); 70 | } 71 | ``` 72 | 73 | ## How it works 74 | 75 | At a high level, the middleware does the following: 76 | 77 | * Intercepts requests to `options.Path` 78 | * Verifies the request is a POST with `Content-Type: application/x-www-form-urlencoded` 79 | * Pulls the username and password out of the form body 80 | * Delegates to `options.IdentityResolver` to look up the user; errors if the credentials are bad 81 | * Creates a JWT with the following claims: 82 | * `sub` (subject) - the username 83 | * `jti` (nonce) - a random value 84 | * `iat` (issued-at) - the current time 85 | * `nbf` (not-before) - the current time 86 | * `exp` (expiration) - the current time + `options.Expiration` 87 | * `iss` (issuer) - `options.Issuer` 88 | * `aud` (audience) - `options.Audience` 89 | * Encodes the JWT to a string and sends it back to the client 90 | 91 | ## Trying it out 92 | 93 | You can install the middleware in a new project, or just run the included test project. Send a POST request using a tool like Fiddler or Postman: 94 | 95 | ``` 96 | POST /token (or whatever you set options.Path to) 97 | Content-Type: application/x-www-form-urlencoded 98 | 99 | username=TEST&password=TEST123 100 | ``` 101 | 102 | You should get a `200 OK` response: 103 | 104 | ``` 105 | { 106 | "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJURVNUIiwianRpIjoiYzRjYzdhMmUtMjI0OS00ZWUzLWJkM2MtYzU5MDkzYmU5MGU1IiwiaWF0IjoxNDYzNTMwMDI0LCJuYmYiOjE0NjM1MzAwMjMsImV4cCI6MTQ2MzUzMDMyMywiaXNzIjoiRXhhbXBsZUlzc3VlciIsImF1ZCI6IkV4YW1wbGVBdWRpZW5jZSJ9.mI0NPO437IuBSt5kmayy5XhNFEHVF4IyMkKsmtas6w8", 107 | "expires_in": 300 108 | } 109 | ``` 110 | 111 | You can try decoding and verifying the JWT at [jsonwebtoken.io](https://jsonwebtoken.io). 112 | 113 | ## Acknowledgements 114 | 115 | These resources were extremely helpful as I was figuring out how to make this work: 116 | 117 | * https://github.com/mrsheepuk/ASPNETSelfCreatedTokenAuthExample 118 | * http://stackoverflow.com/questions/29048122/token-based-authentication-in-asp-net-5-vnext 119 | -------------------------------------------------------------------------------- /SimpleTokenProvider.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26228.10 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{253C448D-6DEE-44D4-9982-88FE9A7C3069}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C0CBE584-E111-47F1-BC4B-3DD5CCC69861}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{137C2B1B-D53E-4C9D-B73C-BE47A3EA3ABC}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimpleTokenProvider.Test", "test\SimpleTokenProvider.Test\SimpleTokenProvider.Test.csproj", "{D07748BD-2C78-4DB8-AB9E-B26D89E1CE74}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SimpleTokenProvider", "src\SimpleTokenProvider\SimpleTokenProvider.csproj", "{7296ED00-D6D3-4EA1-9EC6-A3E757ADF8B0}" 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {D07748BD-2C78-4DB8-AB9E-B26D89E1CE74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {D07748BD-2C78-4DB8-AB9E-B26D89E1CE74}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {D07748BD-2C78-4DB8-AB9E-B26D89E1CE74}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {D07748BD-2C78-4DB8-AB9E-B26D89E1CE74}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {7296ED00-D6D3-4EA1-9EC6-A3E757ADF8B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {7296ED00-D6D3-4EA1-9EC6-A3E757ADF8B0}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {7296ED00-D6D3-4EA1-9EC6-A3E757ADF8B0}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {7296ED00-D6D3-4EA1-9EC6-A3E757ADF8B0}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(NestedProjects) = preSolution 35 | {D07748BD-2C78-4DB8-AB9E-B26D89E1CE74} = {137C2B1B-D53E-4C9D-B73C-BE47A3EA3ABC} 36 | {7296ED00-D6D3-4EA1-9EC6-A3E757ADF8B0} = {253C448D-6DEE-44D4-9982-88FE9A7C3069} 37 | EndGlobalSection 38 | EndGlobal 39 | -------------------------------------------------------------------------------- /src/SimpleTokenProvider/SimpleTokenProvider.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Simple authentication token provider for ASP.NET Core. 5 | Nate Barbettini 6 | netstandard1.4 7 | SimpleTokenProvider 8 | SimpleTokenProvider 9 | token;authentication;security;jwt 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/SimpleTokenProvider/TokenProviderAppBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Nate Barbettini. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. 3 | 4 | using System; 5 | using Microsoft.AspNetCore.Builder; 6 | using Microsoft.Extensions.Options; 7 | 8 | namespace SimpleTokenProvider 9 | { 10 | /// 11 | /// Adds a token generation endpoint to an application pipeline. 12 | /// 13 | public static class TokenProviderAppBuilderExtensions 14 | { 15 | /// 16 | /// Adds the middleware to the specified , which enables token generation capabilities. 17 | /// The to add the middleware to. 18 | /// A that specifies options for the middleware. 19 | /// A reference to this instance after the operation has completed. 20 | public static IApplicationBuilder UseSimpleTokenProvider(this IApplicationBuilder app, TokenProviderOptions options) 21 | { 22 | if (app == null) 23 | { 24 | throw new ArgumentNullException(nameof(app)); 25 | } 26 | 27 | if (options == null) 28 | { 29 | throw new ArgumentNullException(nameof(options)); 30 | } 31 | 32 | return app.UseMiddleware(Options.Create(options)); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /src/SimpleTokenProvider/TokenProviderMiddleware.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Nate Barbettini. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. 3 | 4 | using System; 5 | using System.IdentityModel.Tokens.Jwt; 6 | using System.Security.Claims; 7 | using System.Threading.Tasks; 8 | using Microsoft.AspNetCore.Http; 9 | using Microsoft.Extensions.Logging; 10 | using Microsoft.Extensions.Options; 11 | using Newtonsoft.Json; 12 | 13 | namespace SimpleTokenProvider 14 | { 15 | /// 16 | /// Token generator middleware component which is added to an HTTP pipeline. 17 | /// This class is not created by application code directly, 18 | /// instead it is added by calling the 19 | /// extension method. 20 | /// 21 | public class TokenProviderMiddleware 22 | { 23 | private readonly RequestDelegate _next; 24 | private readonly TokenProviderOptions _options; 25 | private readonly ILogger _logger; 26 | private readonly JsonSerializerSettings _serializerSettings; 27 | 28 | public TokenProviderMiddleware( 29 | RequestDelegate next, 30 | IOptions options, 31 | ILoggerFactory loggerFactory) 32 | { 33 | _next = next; 34 | _logger = loggerFactory.CreateLogger(); 35 | 36 | _options = options.Value; 37 | ThrowIfInvalidOptions(_options); 38 | 39 | _serializerSettings = new JsonSerializerSettings 40 | { 41 | Formatting = Formatting.Indented 42 | }; 43 | } 44 | 45 | public Task Invoke(HttpContext context) 46 | { 47 | // If the request path doesn't match, skip 48 | if (!context.Request.Path.Equals(_options.Path, StringComparison.Ordinal)) 49 | { 50 | return _next(context); 51 | } 52 | 53 | // Request must be POST with Content-Type: application/x-www-form-urlencoded 54 | if (!context.Request.Method.Equals("POST") 55 | || !context.Request.HasFormContentType) 56 | { 57 | context.Response.StatusCode = 400; 58 | return context.Response.WriteAsync("Bad request."); 59 | } 60 | 61 | _logger.LogInformation("Handling request: " + context.Request.Path); 62 | 63 | return GenerateToken(context); 64 | } 65 | 66 | private async Task GenerateToken(HttpContext context) 67 | { 68 | var username = context.Request.Form["username"]; 69 | var password = context.Request.Form["password"]; 70 | 71 | var identity = await _options.IdentityResolver(username, password); 72 | if (identity == null) 73 | { 74 | context.Response.StatusCode = 400; 75 | await context.Response.WriteAsync("Invalid username or password."); 76 | return; 77 | } 78 | 79 | var now = DateTime.UtcNow; 80 | 81 | // Specifically add the jti (nonce), iat (issued timestamp), and sub (subject/user) claims. 82 | // You can add other claims here, if you want: 83 | var claims = new Claim[] 84 | { 85 | new Claim(JwtRegisteredClaimNames.Sub, username), 86 | new Claim(JwtRegisteredClaimNames.Jti, await _options.NonceGenerator()), 87 | new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(now).ToString(), ClaimValueTypes.Integer64) 88 | }; 89 | 90 | // Create the JWT and write it to a string 91 | var jwt = new JwtSecurityToken( 92 | issuer: _options.Issuer, 93 | audience: _options.Audience, 94 | claims: claims, 95 | notBefore: now, 96 | expires: now.Add(_options.Expiration), 97 | signingCredentials: _options.SigningCredentials); 98 | var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); 99 | 100 | var response = new 101 | { 102 | access_token = encodedJwt, 103 | expires_in = (int)_options.Expiration.TotalSeconds 104 | }; 105 | 106 | // Serialize and return the response 107 | context.Response.ContentType = "application/json"; 108 | await context.Response.WriteAsync(JsonConvert.SerializeObject(response, _serializerSettings)); 109 | } 110 | 111 | private static void ThrowIfInvalidOptions(TokenProviderOptions options) 112 | { 113 | if (string.IsNullOrEmpty(options.Path)) 114 | { 115 | throw new ArgumentNullException(nameof(TokenProviderOptions.Path)); 116 | } 117 | 118 | if (string.IsNullOrEmpty(options.Issuer)) 119 | { 120 | throw new ArgumentNullException(nameof(TokenProviderOptions.Issuer)); 121 | } 122 | 123 | if (string.IsNullOrEmpty(options.Audience)) 124 | { 125 | throw new ArgumentNullException(nameof(TokenProviderOptions.Audience)); 126 | } 127 | 128 | if (options.Expiration == TimeSpan.Zero) 129 | { 130 | throw new ArgumentException("Must be a non-zero TimeSpan.", nameof(TokenProviderOptions.Expiration)); 131 | } 132 | 133 | if (options.IdentityResolver == null) 134 | { 135 | throw new ArgumentNullException(nameof(TokenProviderOptions.IdentityResolver)); 136 | } 137 | 138 | if (options.SigningCredentials == null) 139 | { 140 | throw new ArgumentNullException(nameof(TokenProviderOptions.SigningCredentials)); 141 | } 142 | 143 | if (options.NonceGenerator == null) 144 | { 145 | throw new ArgumentNullException(nameof(TokenProviderOptions.NonceGenerator)); 146 | } 147 | } 148 | 149 | /// 150 | /// Get this datetime as a Unix epoch timestamp (seconds since Jan 1, 1970, midnight UTC). 151 | /// 152 | /// The date to convert. 153 | /// Seconds since Unix epoch. 154 | public static long ToUnixEpochDate(DateTime date) => new DateTimeOffset(date).ToUniversalTime().ToUnixTimeSeconds(); 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/SimpleTokenProvider/TokenProviderOptions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) Nate Barbettini. All rights reserved. 2 | // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. 3 | 4 | 5 | using System; 6 | using System.Security.Claims; 7 | using System.Threading.Tasks; 8 | using Microsoft.IdentityModel.Tokens; 9 | 10 | namespace SimpleTokenProvider 11 | { 12 | /// 13 | /// Provides options for . 14 | /// 15 | public class TokenProviderOptions 16 | { 17 | /// 18 | /// The relative request path to listen on. 19 | /// 20 | /// The default path is /token. 21 | public string Path { get; set; } = "/token"; 22 | 23 | /// 24 | /// The Issuer (iss) claim for generated tokens. 25 | /// 26 | public string Issuer { get; set; } 27 | 28 | /// 29 | /// The Audience (aud) claim for the generated tokens. 30 | /// 31 | public string Audience { get; set; } 32 | 33 | /// 34 | /// The expiration time for the generated tokens. 35 | /// 36 | /// The default is five minutes (300 seconds). 37 | public TimeSpan Expiration { get; set; } = TimeSpan.FromMinutes(5); 38 | 39 | /// 40 | /// The signing key to use when generating tokens. 41 | /// 42 | public SigningCredentials SigningCredentials { get; set; } 43 | 44 | /// 45 | /// Resolves a user identity given a username and password. 46 | /// 47 | public Func> IdentityResolver { get; set; } 48 | 49 | /// 50 | /// Generates a random value (nonce) for each generated token. 51 | /// 52 | /// The default nonce is a random GUID. 53 | public Func> NonceGenerator { get; set; } 54 | = new Func>(() => Task.FromResult(Guid.NewGuid().ToString())); 55 | } 56 | } -------------------------------------------------------------------------------- /test/SimpleTokenProvider.Test/Controllers/MeController.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Security.Claims; 3 | using Microsoft.AspNetCore.Authorization; 4 | using Microsoft.AspNetCore.Mvc; 5 | 6 | namespace SimpleTokenProvider.Test.Controllers 7 | { 8 | [Route("api/[controller]")] 9 | [Authorize] 10 | public class MeController : Controller 11 | { 12 | public string Get() 13 | { 14 | // The JWT "sub" claim is automatically mapped to ClaimTypes.NameIdentifier 15 | // by the UseJwtBearerAuthentication middleware 16 | var username = HttpContext.User.Claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value; 17 | 18 | return $"Hello {username}!"; 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /test/SimpleTokenProvider.Test/Controllers/ValuesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Authorization; 6 | using Microsoft.AspNetCore.Mvc; 7 | 8 | namespace SimpleTokenProvider.Test.Controllers 9 | { 10 | [Route("api/[controller]")] 11 | public class ValuesController : Controller 12 | { 13 | // GET: api/values 14 | // Anonymous 15 | [HttpGet] 16 | public IEnumerable Get() 17 | { 18 | return new string[] { "value1", "value2" }; 19 | } 20 | 21 | // GET api/values/5 22 | [HttpGet("{id}")] 23 | [Authorize] 24 | public string Get(int id) 25 | { 26 | return "value"; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /test/SimpleTokenProvider.Test/CustomJwtDataFormat.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IdentityModel.Tokens.Jwt; 3 | using System.Security.Claims; 4 | using Microsoft.AspNetCore.Authentication; 5 | using Microsoft.AspNetCore.Http.Authentication; 6 | using Microsoft.IdentityModel.Tokens; 7 | 8 | namespace SimpleTokenProvider.Test 9 | { 10 | public class CustomJwtDataFormat : ISecureDataFormat 11 | { 12 | private readonly string algorithm; 13 | private readonly TokenValidationParameters validationParameters; 14 | 15 | public CustomJwtDataFormat(string algorithm, TokenValidationParameters validationParameters) 16 | { 17 | this.algorithm = algorithm; 18 | this.validationParameters = validationParameters; 19 | } 20 | 21 | public AuthenticationTicket Unprotect(string protectedText) 22 | => Unprotect(protectedText, null); 23 | 24 | public AuthenticationTicket Unprotect(string protectedText, string purpose) 25 | { 26 | var handler = new JwtSecurityTokenHandler(); 27 | ClaimsPrincipal principal = null; 28 | SecurityToken validToken = null; 29 | 30 | try 31 | { 32 | principal = handler.ValidateToken(protectedText, this.validationParameters, out validToken); 33 | 34 | var validJwt = validToken as JwtSecurityToken; 35 | 36 | if (validJwt == null) 37 | { 38 | throw new ArgumentException("Invalid JWT"); 39 | } 40 | 41 | if (!validJwt.Header.Alg.Equals(algorithm, StringComparison.Ordinal)) 42 | { 43 | throw new ArgumentException($"Algorithm must be '{algorithm}'"); 44 | } 45 | 46 | // Additional custom validation of JWT claims here (if any) 47 | } 48 | catch (SecurityTokenValidationException) 49 | { 50 | return null; 51 | } 52 | catch (ArgumentException) 53 | { 54 | return null; 55 | } 56 | 57 | // Validation passed. Return a valid AuthenticationTicket: 58 | return new AuthenticationTicket(principal, new AuthenticationProperties(), "Cookie"); 59 | } 60 | 61 | // This ISecureDataFormat implementation is decode-only 62 | public string Protect(AuthenticationTicket data) 63 | { 64 | throw new NotImplementedException(); 65 | } 66 | 67 | public string Protect(AuthenticationTicket data, string purpose) 68 | { 69 | throw new NotImplementedException(); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /test/SimpleTokenProvider.Test/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore.Hosting; 7 | 8 | namespace SimpleTokenProvider.Test 9 | { 10 | public class Program 11 | { 12 | public static void Main(string[] args) 13 | { 14 | var host = new WebHostBuilder() 15 | .UseKestrel() 16 | .UseContentRoot(Directory.GetCurrentDirectory()) 17 | .UseIISIntegration() 18 | .UseStartup() 19 | .Build(); 20 | 21 | host.Run(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /test/SimpleTokenProvider.Test/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:2444/", 7 | "sslPort": 0 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "launchUrl": "api/values", 15 | "environmentVariables": { 16 | "ASPNETCORE_ENVIRONMENT": "Development" 17 | } 18 | }, 19 | "SimpleTokenProvider": { 20 | "commandName": "Project", 21 | "launchBrowser": true, 22 | "launchUrl": "http://localhost:5000/api/values", 23 | "environmentVariables": { 24 | "ASPNETCORE_ENVIRONMENT": "Development" 25 | } 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /test/SimpleTokenProvider.Test/SimpleTokenProvider.Test.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netcoreapp1.1 5 | SimpleTokenProvider.Test 6 | Exe 7 | SimpleTokenProvider.Test 8 | 9 | 10 | 11 | 12 | PreserveNewest 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /test/SimpleTokenProvider.Test/Startup.Auth.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Security.Claims; 3 | using System.Security.Principal; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore.Builder; 7 | using Microsoft.IdentityModel.Tokens; 8 | 9 | namespace SimpleTokenProvider.Test 10 | { 11 | public partial class Startup 12 | { 13 | // The secret key every token will be signed with. 14 | // Keep this safe on the server! 15 | private static readonly string secretKey = "mysupersecret_secretkey!123"; 16 | 17 | private void ConfigureAuth(IApplicationBuilder app) 18 | { 19 | var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey)); 20 | 21 | app.UseSimpleTokenProvider(new TokenProviderOptions 22 | { 23 | Path = "/api/token", 24 | Audience = "ExampleAudience", 25 | Issuer = "ExampleIssuer", 26 | SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256), 27 | IdentityResolver = GetIdentity 28 | }); 29 | 30 | var tokenValidationParameters = new TokenValidationParameters 31 | { 32 | // The signing key must match! 33 | ValidateIssuerSigningKey = true, 34 | IssuerSigningKey = signingKey, 35 | 36 | // Validate the JWT Issuer (iss) claim 37 | ValidateIssuer = true, 38 | ValidIssuer = "ExampleIssuer", 39 | 40 | // Validate the JWT Audience (aud) claim 41 | ValidateAudience = true, 42 | ValidAudience = "ExampleAudience", 43 | 44 | // Validate the token expiry 45 | ValidateLifetime = true, 46 | 47 | // If you want to allow a certain amount of clock drift, set that here: 48 | ClockSkew = TimeSpan.Zero 49 | }; 50 | 51 | app.UseJwtBearerAuthentication(new JwtBearerOptions 52 | { 53 | AutomaticAuthenticate = true, 54 | AutomaticChallenge = true, 55 | TokenValidationParameters = tokenValidationParameters 56 | }); 57 | 58 | app.UseCookieAuthentication(new CookieAuthenticationOptions 59 | { 60 | AutomaticAuthenticate = true, 61 | AutomaticChallenge = true, 62 | AuthenticationScheme = "Cookie", 63 | CookieName = "access_token", 64 | TicketDataFormat = new CustomJwtDataFormat( 65 | SecurityAlgorithms.HmacSha256, 66 | tokenValidationParameters) 67 | }); 68 | } 69 | 70 | private Task GetIdentity(string username, string password) 71 | { 72 | // Don't do this in production, obviously! 73 | if (username == "TEST" && password == "TEST123") 74 | { 75 | return Task.FromResult(new ClaimsIdentity(new GenericIdentity(username, "Token"), new Claim[] { })); 76 | } 77 | 78 | // Credentials are invalid, or account doesn't exist 79 | return Task.FromResult(null); 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /test/SimpleTokenProvider.Test/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.Extensions.Configuration; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using Microsoft.Extensions.Logging; 6 | using System; 7 | using System.Collections.Generic; 8 | using System.Linq; 9 | using System.Threading.Tasks; 10 | 11 | namespace SimpleTokenProvider.Test 12 | { 13 | public partial class Startup 14 | { 15 | public Startup(IHostingEnvironment env) 16 | { 17 | var builder = new ConfigurationBuilder() 18 | .SetBasePath(env.ContentRootPath) 19 | .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) 20 | .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) 21 | .AddEnvironmentVariables(); 22 | Configuration = builder.Build(); 23 | } 24 | 25 | public IConfigurationRoot Configuration { get; set; } 26 | 27 | public void ConfigureServices(IServiceCollection services) 28 | { 29 | services.AddMvc(); 30 | } 31 | 32 | public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 33 | { 34 | loggerFactory.AddConsole(LogLevel.Debug); 35 | loggerFactory.AddDebug(); 36 | 37 | ConfigureAuth(app); 38 | 39 | app.UseStaticFiles(); 40 | 41 | app.UseMvc(); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /test/SimpleTokenProvider.Test/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "IncludeScopes": false, 4 | "LogLevel": { 5 | "Default": "Verbose", 6 | "System": "Information", 7 | "Microsoft": "Information" 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /test/SimpleTokenProvider.Test/web.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | --------------------------------------------------------------------------------