├── .github └── workflows │ ├── publish-package.yml │ └── pull-request.yml ├── .gitignore ├── .releaserc ├── CHANGELOG.md ├── LICENSE ├── README.MD ├── samples ├── NetDevPack.Security.JwtExtensions.ApiAuthenticator │ ├── Controllers │ │ └── AuthenticationController.cs │ ├── NetDevPack.Security.JwtExtensions.ApiAuthenticator.csproj │ ├── Program.cs │ ├── Properties │ │ └── launchSettings.json │ ├── Request │ │ └── AuthenticationRequest.cs │ ├── Services │ │ ├── DummyAuthenticationService.cs │ │ └── IAuthenticationService.cs │ ├── Startup.cs │ ├── appsettings.Development.json │ └── appsettings.json └── NetDevPack.Security.JwtExtensions.ApiClient │ ├── Controllers │ └── WeatherForecastController.cs │ ├── NetDevPack.Security.JwtExtensions.ApiClient.csproj │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── Startup.cs │ ├── WeatherForecast.cs │ ├── appsettings.Development.json │ └── appsettings.json ├── src ├── NetDevPack.Security.JwtExtensions.sln └── NetDevPack.Security.JwtExtensions │ ├── JwkList.cs │ ├── JwkOptions.cs │ ├── JwksExtension.cs │ ├── JwksRetriever.cs │ └── NetDevPack.Security.JwtExtensions.csproj └── tests ├── NetDevPack.Security.JwtExtensions.ApiTests ├── Controllers │ ├── ProtectedWeatherForecastController.cs │ └── WeatherForecastController.cs ├── NetDevPack.Security.JwtExtensions.ApiTests.csproj ├── Program.cs ├── Properties │ └── launchSettings.json ├── Startup.cs ├── WeatherForecast.cs ├── appsettings.Development.json └── appsettings.json └── NetDevPack.Security.JwtExtensions.Tests ├── Infra ├── AuthMiddleware.cs └── Server.cs ├── JwksTests.cs └── NetDevPack.Security.JwtExtensions.Tests.csproj /.github/workflows/publish-package.yml: -------------------------------------------------------------------------------- 1 | name: Master - Publish packages 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | 7 | env: 8 | CURRENT_REPO_URL: https://github.com/${{ github.repository }} 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | defaults: 14 | run: 15 | working-directory: src 16 | 17 | steps: 18 | - name: Checkout repository 19 | uses: actions/checkout@v3 20 | 21 | - name: Setup .NET 6 22 | uses: actions/setup-dotnet@v3 23 | with: 24 | dotnet-version: 6.0.x 25 | 26 | - name: Setup .NET 7 27 | uses: actions/setup-dotnet@v3 28 | with: 29 | dotnet-version: 7.0.x 30 | 31 | - name: Setup .NET 8 32 | uses: actions/setup-dotnet@v3 33 | with: 34 | dotnet-version: 8.0.x 35 | 36 | - name: Restore dependencies 37 | run: dotnet restore 38 | 39 | - name: Build 40 | run: dotnet build --no-restore 41 | 42 | - name: Semantic Release 43 | id: semantic 44 | uses: cycjimmy/semantic-release-action@v3 45 | with: 46 | semantic_version: 19.0.5 47 | extra_plugins: | 48 | @semantic-release/changelog 49 | @semantic-release/git 50 | env: 51 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 52 | 53 | - name: Generate Package 54 | run: dotnet pack -c Release -o out -p:PackageVersion=${{ steps.semantic.outputs.new_release_version }} -p:RepositoryUrl=${{env.CURRENT_REPO_URL}} 55 | 56 | - name: Publish the package to nuget.org 57 | run: dotnet nuget push ./out/*.nupkg -n -d -k ${{ secrets.NUGET_AUTH_TOKEN}} -s https://api.nuget.org/v3/index.json -------------------------------------------------------------------------------- /.github/workflows/pull-request.yml: -------------------------------------------------------------------------------- 1 | name: Pull Request Analisys 2 | 3 | on: 4 | pull_request: 5 | branches: [ master ] 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | defaults: 11 | run: 12 | working-directory: ./src 13 | 14 | steps: 15 | - name: Checkout repository 16 | uses: actions/checkout@v3 17 | 18 | - name: Setup .NET 6 19 | uses: actions/setup-dotnet@v3 20 | with: 21 | dotnet-version: 6.0.x 22 | 23 | - name: Setup .NET 7 24 | uses: actions/setup-dotnet@v3 25 | with: 26 | dotnet-version: 7.0.x 27 | 28 | - name: Setup .NET 8 29 | uses: actions/setup-dotnet@v3 30 | with: 31 | dotnet-version: 8.0.x 32 | 33 | - name: Restore dependencies 34 | run: dotnet restore 35 | 36 | - name: Build 37 | run: dotnet build --no-restore 38 | 39 | - name: Test 40 | run: dotnet test --no-build -------------------------------------------------------------------------------- /.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 | PublishProfiles 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | [Xx]64/ 21 | [Xx]86/ 22 | [Bb]uild/ 23 | bld/ 24 | [Bb]in/ 25 | [Oo]bj/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # DNX 46 | project.lock.json 47 | artifacts/ 48 | 49 | *_i.c 50 | *_p.c 51 | *_i.h 52 | *.ilk 53 | *.meta 54 | *.obj 55 | *.pch 56 | *.pdb 57 | *.pgc 58 | *.pgd 59 | *.rsp 60 | *.sbr 61 | *.tlb 62 | *.tli 63 | *.tlh 64 | *.tmp 65 | *.tmp_proj 66 | *.log 67 | *.vspscc 68 | *.vssscc 69 | .builds 70 | *.pidb 71 | *.svclog 72 | *.scc 73 | 74 | # Chutzpah Test files 75 | _Chutzpah* 76 | 77 | # Visual C++ cache files 78 | ipch/ 79 | *.aps 80 | *.ncb 81 | *.opendb 82 | *.opensdf 83 | *.sdf 84 | *.cachefile 85 | *.VC.db 86 | 87 | # Visual Studio profiler 88 | *.psess 89 | *.vsp 90 | *.vspx 91 | *.sap 92 | 93 | # TFS 2012 Local Workspace 94 | $tf/ 95 | 96 | # Guidance Automation Toolkit 97 | *.gpState 98 | 99 | # ReSharper is a .NET coding add-in 100 | _ReSharper*/ 101 | *.[Rr]e[Ss]harper 102 | *.DotSettings.user 103 | 104 | # JustCode is a .NET coding add-in 105 | .JustCode 106 | 107 | # TeamCity is a build add-in 108 | _TeamCity* 109 | 110 | # DotCover is a Code Coverage Tool 111 | *.dotCover 112 | 113 | # NCrunch 114 | _NCrunch_* 115 | .*crunch*.local.xml 116 | nCrunchTemp_* 117 | 118 | # MightyMoose 119 | *.mm.* 120 | AutoTest.Net/ 121 | 122 | # Web workbench (sass) 123 | .sass-cache/ 124 | 125 | # Installshield output folder 126 | [Ee]xpress/ 127 | 128 | # DocProject is a documentation generator add-in 129 | DocProject/buildhelp/ 130 | DocProject/Help/*.HxT 131 | DocProject/Help/*.HxC 132 | DocProject/Help/*.hhc 133 | DocProject/Help/*.hhk 134 | DocProject/Help/*.hhp 135 | DocProject/Help/Html2 136 | DocProject/Help/html 137 | 138 | # Click-Once directory 139 | publish/ 140 | 141 | # Publish Web Output 142 | *.[Pp]ublish.xml 143 | *.azurePubxml 144 | 145 | # TODO: Un-comment the next line if you do not want to checkin 146 | # your web deploy settings because they may include unencrypted 147 | # passwords 148 | #*.pubxml 149 | *.publishproj 150 | 151 | # NuGet Packages 152 | *.nupkg 153 | # The packages folder can be ignored because of Package Restore 154 | **/packages/* 155 | # except build/, which is used as an MSBuild target. 156 | !**/packages/build/ 157 | # Uncomment if necessary however generally it will be regenerated when needed 158 | #!**/packages/repositories.config 159 | # NuGet v3's project.json files produces more ignoreable files 160 | *.nuget.props 161 | *.nuget.targets 162 | 163 | # Microsoft Azure Build Output 164 | csx/ 165 | *.build.csdef 166 | 167 | # Microsoft Azure Emulator 168 | ecf/ 169 | rcf/ 170 | 171 | # Windows Store app package directory 172 | AppPackages/ 173 | BundleArtifacts/ 174 | 175 | # Visual Studio cache files 176 | # files ending in .cache can be ignored 177 | *.[Cc]ache 178 | # but keep track of directories ending in .cache 179 | !*.[Cc]ache/ 180 | 181 | # Others 182 | ClientBin/ 183 | [Ss]tyle[Cc]op.* 184 | ~$* 185 | *~ 186 | *.dbmdl 187 | *.dbproj.schemaview 188 | *.pfx 189 | *.publishsettings 190 | node_modules/ 191 | orleans.codegen.cs 192 | 193 | # RIA/Silverlight projects 194 | Generated_Code/ 195 | 196 | # Backup & report files from converting an old project file 197 | # to a newer Visual Studio version. Backup files are not needed, 198 | # because we have git ;-) 199 | _UpgradeReport_Files/ 200 | Backup*/ 201 | UpgradeLog*.XML 202 | UpgradeLog*.htm 203 | 204 | # SQL Server files 205 | *.mdf 206 | *.ldf 207 | 208 | # Business Intelligence projects 209 | *.rdl.data 210 | *.bim.layout 211 | *.bim_*.settings 212 | 213 | # Microsoft Fakes 214 | FakesAssemblies/ 215 | 216 | # GhostDoc plugin setting file 217 | *.GhostDoc.xml 218 | 219 | # Node.js Tools for Visual Studio 220 | .ntvs_analysis.dat 221 | 222 | # Visual Studio 6 build log 223 | *.plg 224 | 225 | # Visual Studio 6 workspace options file 226 | *.opt 227 | 228 | # Visual Studio LightSwitch build output 229 | **/*.HTMLClient/GeneratedArtifacts 230 | **/*.DesktopClient/GeneratedArtifacts 231 | **/*.DesktopClient/ModelManifest.xml 232 | **/*.Server/GeneratedArtifacts 233 | **/*.Server/ModelManifest.xml 234 | _Pvt_Extensions 235 | 236 | # LightSwitch generated files 237 | GeneratedArtifacts/ 238 | ModelManifest.xml 239 | 240 | # Paket dependency manager 241 | .paket/paket.exe 242 | 243 | # FAKE - F# Make 244 | .fake/ 245 | /ASP.NET Core/03 - WebAPI/Projetos/01 MinhaAPICompleta 3.1/API/MinhaAPICompleta.sln.DotSettings.zip 246 | /ASP.NET Core/04 - Enterprise Applications/Projetos/Instrutor/NerdStoreEnterprise/ComunicacaoFilaIdentidadeCliente.rar 247 | -------------------------------------------------------------------------------- /.releaserc: -------------------------------------------------------------------------------- 1 | { 2 | "branches": ["master"], 3 | 4 | "plugins": [ 5 | "@semantic-release/commit-analyzer", 6 | "@semantic-release/release-notes-generator", 7 | "@semantic-release/changelog", 8 | "@semantic-release/github", 9 | "@semantic-release/git" 10 | ] 11 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # [8.0.0](https://github.com/NetDevPack/Security.JwtExtensions/compare/v7.1.0...v8.0.0) (2024-04-19) 2 | 3 | 4 | ### Bug Fixes 5 | 6 | * deps ([2738f10](https://github.com/NetDevPack/Security.JwtExtensions/commit/2738f10d2b87b6df634fa92bcdd19c698a3eb8e2)) 7 | * deps upgrade ([76afaa9](https://github.com/NetDevPack/Security.JwtExtensions/commit/76afaa96c27012e29ffbd700188e90e63572eb6f)) 8 | 9 | 10 | ### BREAKING CHANGES 11 | 12 | * .NET 8 13 | 14 | # [7.1.0](https://github.com/NetDevPack/Security.JwtExtensions/compare/v7.0.0...v7.1.0) (2024-02-08) 15 | 16 | 17 | ### Features 18 | 19 | * .NET 8 ([2fa28da](https://github.com/NetDevPack/Security.JwtExtensions/commit/2fa28dad49d0bb5aed8cc9cc246a43c01c06f655)) 20 | 21 | # [7.0.0](https://github.com/NetDevPack/Security.JwtExtensions/compare/v6.0.2...v7.0.0) (2022-11-17) 22 | 23 | 24 | ### Features 25 | 26 | * net 7 ([cc5fe34](https://github.com/NetDevPack/Security.JwtExtensions/commit/cc5fe347933f03ff934787ae3821263b48050cef)) 27 | 28 | 29 | ### BREAKING CHANGES 30 | 31 | * net 7 sup and dropped net 5 32 | 33 | ## [6.0.2](https://github.com/NetDevPack/Security.JwtExtensions/compare/v6.0.1...v6.0.2) (2022-04-18) 34 | 35 | 36 | ### Bug Fixes 37 | 38 | * updgrade packages ([b651e94](https://github.com/NetDevPack/Security.JwtExtensions/commit/b651e94f6d2be5b34d36c377dc5cb4c5a485c0dc)) 39 | 40 | ## [6.0.1](https://github.com/NetDevPack/Security.JwtExtensions/compare/v6.0.0...v6.0.1) (2022-04-18) 41 | 42 | 43 | ### Bug Fixes 44 | 45 | * publish package fix ([61d00b3](https://github.com/NetDevPack/Security.JwtExtensions/commit/61d00b3d4424b9d5ef507bcb056836869a8a1c46)) 46 | 47 | # [6.0.0](https://github.com/NetDevPack/Security.JwtExtensions/compare/v5.0.1...v6.0.0) (2022-04-18) 48 | 49 | 50 | ### Bug Fixes 51 | 52 | * jwks string ([de8b5e8](https://github.com/NetDevPack/Security.JwtExtensions/commit/de8b5e8fd1faee3e7171a07db891c2509512a5ed)) 53 | 54 | 55 | ### Features 56 | 57 | * .net 6 ([e97b52b](https://github.com/NetDevPack/Security.JwtExtensions/commit/e97b52b9a92c8a8662415c4717ce99eee5121176)) 58 | * .net 6 ([2b93cab](https://github.com/NetDevPack/Security.JwtExtensions/commit/2b93cab63d51c627d4648d845e5d1b71fad60c7b)) 59 | * .net 6 ([3862101](https://github.com/NetDevPack/Security.JwtExtensions/commit/386210183526036e22e3cdecdfa97ae035023e47)) 60 | * semantic commits ([f2ad888](https://github.com/NetDevPack/Security.JwtExtensions/commit/f2ad88894865eee869bd1fa5aa3d4b0b991bfc1a)) 61 | 62 | 63 | ### BREAKING CHANGES 64 | 65 | * .NET 6 version 66 | * .NET 6 version 67 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 NetDevPack 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.MD: -------------------------------------------------------------------------------- 1 | .NET DevPack 2 | 3 | What is the .NET DevPack JwtExtensions? 4 | ===================== 5 | .NET DevPack JwtExtensions was created to help you validate Bearer tokens from Jwks endpoint. It configure your ASP.NET Core with JWT Bearer Token using a Custom JWKS Endpoint. Giving hability to leverage the security of your environment using Assymetric Keys. Which is by far a most recommended cryptography to digitally signin you JWT. 6 | 7 | [![Codacy Badge](https://app.codacy.com/project/badge/Grade/f1bd42eda59844ea95852606741147fa)](https://www.codacy.com/gh/NetDevPack/NetDevPack.Security.JwtExtensions?utm_source=github.com&utm_medium=referral&utm_content=NetDevPack/NetDevPack.Security.JwtExtensions&utm_campaign=Badge_Grade) 8 | [![Build status](https://ci.appveyor.com/api/projects/status/e283g9ik4rk3ymsp?svg=true)](https://ci.appveyor.com/project/netdevpack/netdevpack-jwtextensions) 9 | [![License](http://img.shields.io/github/license/NetDevPack/NetDevPack.Security.JwtExtensions.svg)](LICENSE) 10 | 11 | ## Give a Star! :star: 12 | If you liked the project or if NetDevPack helped you, please give a star ;) 13 | 14 | ## Get Started 15 | 16 | | Package | Version | Popularity | 17 | | ------- | ----- | ----- | 18 | | `NetDevPack.Security.JwtExtensions` | [![NuGet](https://img.shields.io/nuget/v/NetDevPack.Security.JwtExtensions.svg)](https://nuget.org/packages/NetDevPack.Security.JwtExtensions) | [![Nuget](https://img.shields.io/nuget/dt/NetDevPack.Security.JwtExtensions.svg)](https://nuget.org/packages/NetDevPack.Security.JwtExtensions) | 19 | 20 | 21 | .NET DevPack.JwtExtensions can be installed in your ASP.NET Core application using the Nuget package manager or the `dotnet` CLI. 22 | 23 | ``` 24 | dotnet add package NetDevPack.Security.JwtExtensions 25 | ``` 26 | 27 | Then use Extension at configuration in `ConfigureServices` method of your `Startup.cs`: 28 | 29 | ```csharp 30 | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) 31 | .AddJwtBearer(options => 32 | { 33 | options.SetJwksOptions(new JwkOptions("https://localhost:5001/jwks")); 34 | }); 35 | ``` 36 | 37 | ### Configuring JWT 38 | If you want to generate JSON Web Tokens in your application you need to add the [NetDevPack.Jwk](https://github.com/NetDevPack/NetDevPack.Jwk). 39 | 40 | >**Note:** NetDevPack.Security.JwtExtensions is for those who already have an api who use `NetDevPack.Jwk` 41 | > 42 | >**Note:** The `NetDevPack.Jwk` is a set of components who will generate Keys using industry security best standards (NIST Rotating keys, RSA Key Length, ECDsa P-256). It's supports [Elliptic Curves](https://blog.cloudflare.com/a-relatively-easy-to-understand-primer-on-elliptic-curve-cryptography/) and RSA as well. 43 | 44 | ## Examples 45 | Use the [sample application](https://github.com/NetDevPack/NetDevPack.Security.JwtExtensions/tree/master/samples/ApiClient) to understand how NetDevPack.Security.JwtExtensions can be implemented and help you to decrease the complexity of your application and development time. 46 | 47 | ## About 48 | .NET DevPack.JwtExtensions was developed by [Bruno Brito](https://brunobrito.net.br) under the [MIT license](LICENSE). 49 | 50 | -------------------------------------------------------------------------------- /samples/NetDevPack.Security.JwtExtensions.ApiAuthenticator/Controllers/AuthenticationController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using ApiAuthenticator.Request; 4 | using ApiAuthenticator.Services; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Microsoft.Extensions.Logging; 7 | 8 | namespace ApiAuthenticator.Controllers 9 | { 10 | [ApiController] 11 | [Route("/v1/authentication")] 12 | public class AuthenticationController : ControllerBase 13 | { 14 | private readonly ILogger _logger; 15 | private readonly IAuthenticationService _authenticationService; 16 | 17 | public AuthenticationController( 18 | ILogger logger, 19 | IAuthenticationService authenticationService) 20 | { 21 | _logger = logger; 22 | _authenticationService = authenticationService; 23 | } 24 | 25 | [HttpPost] 26 | public async ValueTask Authentication([FromBody] AuthenticationRequest request) 27 | { 28 | try 29 | { 30 | if (string.IsNullOrEmpty(request.Login)) 31 | { 32 | throw new ArgumentNullException(); 33 | } 34 | 35 | if (string.IsNullOrEmpty(request.Password)) 36 | { 37 | throw new ArgumentNullException(); 38 | } 39 | 40 | if (!await _authenticationService.SignInAsync(request.Login, request.Password)) 41 | { 42 | return new ForbidResult(); 43 | } 44 | 45 | var token = await _authenticationService.GenerateToken(); 46 | 47 | return Ok(token); 48 | 49 | } 50 | catch (Exception e) 51 | { 52 | _logger.LogError(e.Message, e); 53 | return BadRequest(request); 54 | } 55 | } 56 | } 57 | } -------------------------------------------------------------------------------- /samples/NetDevPack.Security.JwtExtensions.ApiAuthenticator/NetDevPack.Security.JwtExtensions.ApiAuthenticator.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6.0;net7.0;net8.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /samples/NetDevPack.Security.JwtExtensions.ApiAuthenticator/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Hosting; 3 | 4 | namespace ApiAuthenticator 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | CreateHostBuilder(args).Build().Run(); 11 | } 12 | 13 | public static IHostBuilder CreateHostBuilder(string[] args) => 14 | Host.CreateDefaultBuilder(args) 15 | .ConfigureWebHostDefaults(webBuilder => 16 | { 17 | webBuilder.UseStartup(); 18 | }); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /samples/NetDevPack.Security.JwtExtensions.ApiAuthenticator/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:52226", 8 | "sslPort": 44363 9 | } 10 | }, 11 | "profiles": { 12 | 13 | "ApiAuthenticator": { 14 | "commandName": "Project", 15 | "launchBrowser": true, 16 | "launchUrl": "", 17 | "applicationUrl": "https://localhost:5005;http://localhost:5006", 18 | "environmentVariables": { 19 | "ASPNETCORE_ENVIRONMENT": "Development" 20 | } 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /samples/NetDevPack.Security.JwtExtensions.ApiAuthenticator/Request/AuthenticationRequest.cs: -------------------------------------------------------------------------------- 1 | namespace ApiAuthenticator.Request 2 | { 3 | public sealed class AuthenticationRequest 4 | { 5 | public string Login { get; set; } 6 | public string Password { get; set; } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /samples/NetDevPack.Security.JwtExtensions.ApiAuthenticator/Services/DummyAuthenticationService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IdentityModel.Tokens.Jwt; 3 | using System.Security.Claims; 4 | using System.Threading.Tasks; 5 | using ApiAuthenticator.Services; 6 | using Bogus; 7 | using Microsoft.AspNetCore.Http; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.IdentityModel.Tokens; 10 | using NetDevPack.Security.Jwt.Core.Interfaces; 11 | 12 | namespace NetDevPack.Security.JwtExtensions.ApiAuthenticator.Services 13 | { 14 | public class AuthenticationService : IAuthenticationService 15 | { 16 | private readonly IConfiguration _configuration; 17 | private readonly IJwtService _jsonWebKeySetService; 18 | private readonly IHttpContextAccessor _httpContextAccessor; 19 | 20 | public AuthenticationService(IConfiguration configuration, IJwtService jsonWebKeySetService, IHttpContextAccessor httpContextAccessor) 21 | { 22 | _configuration = configuration; 23 | _jsonWebKeySetService = jsonWebKeySetService; 24 | _httpContextAccessor = httpContextAccessor; 25 | } 26 | 27 | public async ValueTask GenerateToken() 28 | { 29 | 30 | var faker = new Faker(); 31 | var tokenHandler = new JwtSecurityTokenHandler(); 32 | var key = await _jsonWebKeySetService.GetCurrentSigningCredentials(); 33 | 34 | var tokenDescriptor = new SecurityTokenDescriptor 35 | { 36 | Subject = new ClaimsIdentity(new[] 37 | { 38 | new Claim(JwtRegisteredClaimNames.UniqueName, faker.Person.UserName), 39 | new Claim(JwtRegisteredClaimNames.Amr, "Fake"), 40 | new Claim(JwtRegisteredClaimNames.Email, faker.Person.Email), 41 | new Claim(JwtRegisteredClaimNames.GivenName, faker.Person.FullName), 42 | }), 43 | Expires = DateTime.UtcNow.AddHours(1), 44 | Issuer = $"{_httpContextAccessor.HttpContext.Request.Scheme}://{_httpContextAccessor.HttpContext.Request.Host}", 45 | SigningCredentials = key 46 | }; 47 | var jwt = tokenHandler.CreateToken(tokenDescriptor); 48 | var jws = tokenHandler.WriteToken(jwt); 49 | 50 | 51 | return await Task.FromResult(jws); 52 | } 53 | 54 | public async ValueTask SignInAsync(string login, string password) 55 | { 56 | var faker = new Faker(); 57 | 58 | if (string.IsNullOrEmpty(login)) 59 | { 60 | return false; 61 | } 62 | 63 | if (password.Length < 3) 64 | { 65 | return false; 66 | } 67 | 68 | return await Task.FromResult(true); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /samples/NetDevPack.Security.JwtExtensions.ApiAuthenticator/Services/IAuthenticationService.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace ApiAuthenticator.Services 4 | { 5 | public interface IAuthenticationService 6 | { 7 | ValueTask SignInAsync(string login, string password); 8 | ValueTask GenerateToken(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /samples/NetDevPack.Security.JwtExtensions.ApiAuthenticator/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.Hosting; 6 | using System.IO; 7 | 8 | namespace ApiAuthenticator 9 | { 10 | public class Startup 11 | { 12 | private readonly IWebHostEnvironment _env; 13 | 14 | public Startup(IConfiguration configuration, IWebHostEnvironment env) 15 | { 16 | _env = env; 17 | Configuration = configuration; 18 | } 19 | 20 | public IConfiguration Configuration { get; } 21 | 22 | // This method gets called by the runtime. Use this method to add services to the container. 23 | public void ConfigureServices(IServiceCollection services) 24 | { 25 | services.AddControllers(); 26 | services.AddHttpContextAccessor(); 27 | services.AddJwksManager().PersistKeysInMemory(); 28 | } 29 | 30 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 31 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 32 | { 33 | if (env.IsDevelopment()) 34 | { 35 | app.UseDeveloperExceptionPage(); 36 | } 37 | 38 | app.UseHttpsRedirection(); 39 | app.UseJwksDiscovery(); 40 | app.UseRouting(); 41 | 42 | app.UseAuthorization(); 43 | 44 | app.UseEndpoints(endpoints => 45 | { 46 | endpoints.MapControllers(); 47 | }); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /samples/NetDevPack.Security.JwtExtensions.ApiAuthenticator/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /samples/NetDevPack.Security.JwtExtensions.ApiAuthenticator/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*" 10 | } 11 | -------------------------------------------------------------------------------- /samples/NetDevPack.Security.JwtExtensions.ApiClient/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authorization; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Microsoft.Extensions.Logging; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using NetDevPack.Security.JwtExtensions.ApiClient; 8 | 9 | namespace NetDevPack.Security.JwtExtensionsApiClient.Controllers 10 | { 11 | [ApiController] 12 | [Route("[controller]"), Authorize] 13 | public class WeatherForecastController : ControllerBase 14 | { 15 | private static readonly string[] Summaries = new[] 16 | { 17 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 18 | }; 19 | 20 | private readonly ILogger _logger; 21 | 22 | public WeatherForecastController(ILogger logger) 23 | { 24 | _logger = logger; 25 | } 26 | 27 | [HttpGet] 28 | public IEnumerable Get() 29 | { 30 | var rng = new Random(); 31 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 32 | { 33 | Date = DateTime.Now.AddDays(index), 34 | TemperatureC = rng.Next(-20, 55), 35 | Summary = Summaries[rng.Next(Summaries.Length)] 36 | }) 37 | .ToArray(); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /samples/NetDevPack.Security.JwtExtensions.ApiClient/NetDevPack.Security.JwtExtensions.ApiClient.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0;net7.0;net8.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /samples/NetDevPack.Security.JwtExtensions.ApiClient/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace NetDevPack.Security.JwtExtensions.ApiClient 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /samples/NetDevPack.Security.JwtExtensions.ApiClient/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:52944", 8 | "sslPort": 44302 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "weatherforecast", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "ApiClient": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "weatherforecast", 24 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /samples/NetDevPack.Security.JwtExtensions.ApiClient/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authentication.JwtBearer; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | using NetDevPack.Security.JwtExtensions; 8 | 9 | namespace NetDevPack.Security.JwtExtensions.ApiClient 10 | { 11 | public class Startup 12 | { 13 | public Startup(IConfiguration configuration) 14 | { 15 | Configuration = configuration; 16 | } 17 | 18 | public IConfiguration Configuration { get; } 19 | 20 | // This method gets called by the runtime. Use this method to add services to the container. 21 | public void ConfigureServices(IServiceCollection services) 22 | { 23 | services.AddControllers(); 24 | 25 | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) 26 | .AddJwtBearer(options => 27 | { 28 | options.RequireHttpsMetadata = true; 29 | options.SaveToken = true; 30 | 31 | // API Authenticator Endpoint 32 | options.SetJwksOptions(new JwkOptions(Configuration["JwksUri"])); 33 | }); 34 | } 35 | 36 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 37 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 38 | { 39 | if (env.IsDevelopment()) 40 | { 41 | app.UseDeveloperExceptionPage(); 42 | } 43 | 44 | app.UseHttpsRedirection(); 45 | 46 | app.UseRouting(); 47 | 48 | app.UseAuthentication(); 49 | 50 | app.UseAuthorization(); 51 | 52 | app.UseEndpoints(endpoints => 53 | { 54 | endpoints.MapControllers(); 55 | }); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /samples/NetDevPack.Security.JwtExtensions.ApiClient/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace NetDevPack.Security.JwtExtensions.ApiClient 4 | { 5 | public class WeatherForecast 6 | { 7 | public DateTime Date { get; set; } 8 | 9 | public int TemperatureC { get; set; } 10 | 11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 12 | 13 | public string Summary { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /samples/NetDevPack.Security.JwtExtensions.ApiClient/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /samples/NetDevPack.Security.JwtExtensions.ApiClient/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*", 10 | "JwksUri": "https://localhost:5005/jwks" 11 | } 12 | -------------------------------------------------------------------------------- /src/NetDevPack.Security.JwtExtensions.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30225.117 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{22F8F825-438F-497A-850E-D24D3E7C88D2}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{25FA94BF-8B5B-4346-AEE8-6CC211FE015F}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NetDevPack.Security.JwtExtensions", "NetDevPack.Security.JwtExtensions\NetDevPack.Security.JwtExtensions.csproj", "{669CC050-6F58-4ACB-A675-BC692DDB7EAB}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NetDevPack.Security.JwtExtensions.ApiClient", "..\samples\NetDevPack.Security.JwtExtensions.ApiClient\NetDevPack.Security.JwtExtensions.ApiClient.csproj", "{3AFAC6BB-85B5-43F3-AEDB-763D630A73C0}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NetDevPack.Security.JwtExtensions.ApiAuthenticator", "..\samples\NetDevPack.Security.JwtExtensions.ApiAuthenticator\NetDevPack.Security.JwtExtensions.ApiAuthenticator.csproj", "{892D8E58-96F9-423B-B7CC-E043C95EB519}" 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NetDevPack.Security.JwtExtensions.ApiTests", "..\tests\NetDevPack.Security.JwtExtensions.ApiTests\NetDevPack.Security.JwtExtensions.ApiTests.csproj", "{39BAA874-EBA9-4F2B-9052-CE1F87A291DD}" 17 | EndProject 18 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NetDevPack.Security.JwtExtensions.Tests", "..\tests\NetDevPack.Security.JwtExtensions.Tests\NetDevPack.Security.JwtExtensions.Tests.csproj", "{C27054DE-E193-4F93-A66D-EB9141B4ECFB}" 19 | EndProject 20 | Global 21 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 22 | Debug|Any CPU = Debug|Any CPU 23 | Release|Any CPU = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 26 | {669CC050-6F58-4ACB-A675-BC692DDB7EAB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {669CC050-6F58-4ACB-A675-BC692DDB7EAB}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {669CC050-6F58-4ACB-A675-BC692DDB7EAB}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {669CC050-6F58-4ACB-A675-BC692DDB7EAB}.Release|Any CPU.Build.0 = Release|Any CPU 30 | {3AFAC6BB-85B5-43F3-AEDB-763D630A73C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 31 | {3AFAC6BB-85B5-43F3-AEDB-763D630A73C0}.Debug|Any CPU.Build.0 = Debug|Any CPU 32 | {3AFAC6BB-85B5-43F3-AEDB-763D630A73C0}.Release|Any CPU.ActiveCfg = Release|Any CPU 33 | {3AFAC6BB-85B5-43F3-AEDB-763D630A73C0}.Release|Any CPU.Build.0 = Release|Any CPU 34 | {892D8E58-96F9-423B-B7CC-E043C95EB519}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 35 | {892D8E58-96F9-423B-B7CC-E043C95EB519}.Debug|Any CPU.Build.0 = Debug|Any CPU 36 | {892D8E58-96F9-423B-B7CC-E043C95EB519}.Release|Any CPU.ActiveCfg = Release|Any CPU 37 | {892D8E58-96F9-423B-B7CC-E043C95EB519}.Release|Any CPU.Build.0 = Release|Any CPU 38 | {39BAA874-EBA9-4F2B-9052-CE1F87A291DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 39 | {39BAA874-EBA9-4F2B-9052-CE1F87A291DD}.Debug|Any CPU.Build.0 = Debug|Any CPU 40 | {39BAA874-EBA9-4F2B-9052-CE1F87A291DD}.Release|Any CPU.ActiveCfg = Release|Any CPU 41 | {39BAA874-EBA9-4F2B-9052-CE1F87A291DD}.Release|Any CPU.Build.0 = Release|Any CPU 42 | {C27054DE-E193-4F93-A66D-EB9141B4ECFB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 43 | {C27054DE-E193-4F93-A66D-EB9141B4ECFB}.Debug|Any CPU.Build.0 = Debug|Any CPU 44 | {C27054DE-E193-4F93-A66D-EB9141B4ECFB}.Release|Any CPU.ActiveCfg = Release|Any CPU 45 | {C27054DE-E193-4F93-A66D-EB9141B4ECFB}.Release|Any CPU.Build.0 = Release|Any CPU 46 | EndGlobalSection 47 | GlobalSection(SolutionProperties) = preSolution 48 | HideSolutionNode = FALSE 49 | EndGlobalSection 50 | GlobalSection(NestedProjects) = preSolution 51 | {3AFAC6BB-85B5-43F3-AEDB-763D630A73C0} = {25FA94BF-8B5B-4346-AEE8-6CC211FE015F} 52 | {892D8E58-96F9-423B-B7CC-E043C95EB519} = {25FA94BF-8B5B-4346-AEE8-6CC211FE015F} 53 | {39BAA874-EBA9-4F2B-9052-CE1F87A291DD} = {22F8F825-438F-497A-850E-D24D3E7C88D2} 54 | {C27054DE-E193-4F93-A66D-EB9141B4ECFB} = {22F8F825-438F-497A-850E-D24D3E7C88D2} 55 | EndGlobalSection 56 | GlobalSection(ExtensibilityGlobals) = postSolution 57 | SolutionGuid = {BD6B2063-A310-4A07-AFE7-D2390E27A8AB} 58 | EndGlobalSection 59 | EndGlobal 60 | -------------------------------------------------------------------------------- /src/NetDevPack.Security.JwtExtensions/JwkList.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.IdentityModel.Tokens; 2 | using System; 3 | 4 | namespace NetDevPack.Security.JwtExtensions 5 | { 6 | public sealed class JwkList 7 | { 8 | public JwkList(JsonWebKeySet jwkTaskResult) 9 | { 10 | Jwks = jwkTaskResult; 11 | When = DateTime.Now; 12 | } 13 | 14 | public DateTime When { get; set; } 15 | public JsonWebKeySet Jwks { get; set; } 16 | } 17 | } -------------------------------------------------------------------------------- /src/NetDevPack.Security.JwtExtensions/JwkOptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace NetDevPack.Security.JwtExtensions 4 | { 5 | public class JwkOptions 6 | { 7 | public JwkOptions() { } 8 | public JwkOptions(string jwksUri, string issuer = null, TimeSpan? cacheTime = null, string audience = null) 9 | { 10 | JwksUri = jwksUri; 11 | var jwks = new Uri(jwksUri); 12 | Issuer = issuer ?? $"{jwks.Scheme}://{jwks.Authority}"; 13 | KeepFor = cacheTime ?? TimeSpan.FromMinutes(15); 14 | Audience = audience; 15 | } 16 | public string Issuer { get; set; } 17 | public string JwksUri { get; set; } 18 | public TimeSpan KeepFor { get; set; } = TimeSpan.FromMinutes(15); 19 | public string Audience { get; set; } 20 | } 21 | } -------------------------------------------------------------------------------- /src/NetDevPack.Security.JwtExtensions/JwksExtension.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Http; 2 | using Microsoft.AspNetCore.Authentication.JwtBearer; 3 | using Microsoft.IdentityModel.Protocols; 4 | using Microsoft.IdentityModel.Protocols.OpenIdConnect; 5 | 6 | namespace NetDevPack.Security.JwtExtensions 7 | { 8 | public static class JwksExtension 9 | { 10 | public static void SetJwksOptions(this JwtBearerOptions options, JwkOptions jwkOptions) 11 | { 12 | var httpClient = new HttpClient(options.BackchannelHttpHandler ?? new HttpClientHandler()) 13 | { 14 | Timeout = options.BackchannelTimeout, 15 | MaxResponseContentBufferSize = 1024 * 1024 * 10 // 10 MB 16 | }; 17 | 18 | options.ConfigurationManager = new ConfigurationManager( 19 | jwkOptions.JwksUri, 20 | new JwksRetriever(), 21 | new HttpDocumentRetriever(httpClient) { RequireHttps = options.RequireHttpsMetadata }); 22 | 23 | options.TokenValidationParameters.ValidateAudience = false; 24 | options.TokenValidationParameters.ValidIssuer = jwkOptions.Issuer; 25 | 26 | if (!string.IsNullOrEmpty(jwkOptions.Audience)) 27 | { 28 | options.TokenValidationParameters.ValidateAudience = true; 29 | options.TokenValidationParameters.ValidAudience = jwkOptions.Audience; 30 | } 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/NetDevPack.Security.JwtExtensions/JwksRetriever.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | using System.Threading.Tasks; 4 | using Microsoft.IdentityModel.Logging; 5 | using Microsoft.IdentityModel.Protocols; 6 | using Microsoft.IdentityModel.Protocols.OpenIdConnect; 7 | using Microsoft.IdentityModel.Tokens; 8 | 9 | namespace NetDevPack.Security.JwtExtensions 10 | { 11 | public class JwksRetriever : IConfigurationRetriever 12 | { 13 | public Task GetConfigurationAsync(string address, IDocumentRetriever retriever, CancellationToken cancel) 14 | { 15 | return GetAsync(address, retriever, cancel); 16 | } 17 | 18 | /// 19 | /// Retrieves a populated given an address and an . 20 | /// 21 | /// address of the jwks uri. 22 | /// the to use to read the jwks 23 | /// . 24 | /// A populated instance. 25 | public static async Task GetAsync(string address, IDocumentRetriever retriever, CancellationToken cancel) 26 | { 27 | if (string.IsNullOrWhiteSpace(address)) 28 | throw LogHelper.LogArgumentNullException(nameof(address)); 29 | 30 | if (retriever == null) 31 | throw LogHelper.LogArgumentNullException(nameof(retriever)); 32 | 33 | IdentityModelEventSource.ShowPII = true; 34 | var doc = await retriever.GetDocumentAsync(address, cancel); 35 | LogHelper.LogVerbose("IDX21811: Deserializing the string: '{0}' obtained from metadata endpoint into openIdConnectConfiguration object.", doc); 36 | var jwks = new JsonWebKeySet(doc); 37 | var openIdConnectConfiguration = new OpenIdConnectConfiguration() 38 | { 39 | JsonWebKeySet = jwks, 40 | JwksUri = address, 41 | }; 42 | foreach (var securityKey in jwks.GetSigningKeys()) 43 | openIdConnectConfiguration.SigningKeys.Add(securityKey); 44 | 45 | return openIdConnectConfiguration; 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /src/NetDevPack.Security.JwtExtensions/NetDevPack.Security.JwtExtensions.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1;net6.0;net7.0;net8.0 5 | 3.1.0 6 | Bruno Brito 7 | https://raw.githubusercontent.com/NetDevPack/NetDevPack/master/assets/IconNuget.png 8 | jwt jwks jwks_uri 9 | Extension to load JWKS from custom uri 10 | Component for easy use of JWKS endpoint for Assymetric keys 11 | en 12 | MIT 13 | https://github.com/brunohbrito/Jwks.Manager 14 | git 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /tests/NetDevPack.Security.JwtExtensions.ApiTests/Controllers/ProtectedWeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using Microsoft.AspNetCore.Authorization; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Microsoft.Extensions.Logging; 7 | 8 | namespace NetDevPack.Security.JwtExtensions.ApiTests.Controllers 9 | { 10 | [ApiController] 11 | [Route("[controller]"), Authorize] 12 | public class ProtectedWeatherForecastController : ControllerBase 13 | { 14 | private static readonly string[] Summaries = new[] 15 | { 16 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 17 | }; 18 | 19 | private readonly ILogger _logger; 20 | 21 | public ProtectedWeatherForecastController(ILogger logger) 22 | { 23 | _logger = logger; 24 | } 25 | 26 | [HttpGet] 27 | public IEnumerable Get() 28 | { 29 | var rng = new Random(); 30 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 31 | { 32 | Date = DateTime.Now.AddDays(index), 33 | TemperatureC = rng.Next(-20, 55), 34 | Summary = Summaries[rng.Next(Summaries.Length)] 35 | }) 36 | .ToArray(); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /tests/NetDevPack.Security.JwtExtensions.ApiTests/Controllers/WeatherForecastController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Mvc; 6 | using Microsoft.Extensions.Logging; 7 | 8 | namespace NetDevPack.Security.JwtExtensions.ApiTests.Controllers 9 | { 10 | [ApiController] 11 | [Route("[controller]")] 12 | public class WeatherForecastController : ControllerBase 13 | { 14 | private static readonly string[] Summaries = new[] 15 | { 16 | "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" 17 | }; 18 | 19 | private readonly ILogger _logger; 20 | 21 | public WeatherForecastController(ILogger logger) 22 | { 23 | _logger = logger; 24 | } 25 | 26 | [HttpGet] 27 | public IEnumerable Get() 28 | { 29 | var rng = new Random(); 30 | return Enumerable.Range(1, 5).Select(index => new WeatherForecast 31 | { 32 | Date = DateTime.Now.AddDays(index), 33 | TemperatureC = rng.Next(-20, 55), 34 | Summary = Summaries[rng.Next(Summaries.Length)] 35 | }) 36 | .ToArray(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /tests/NetDevPack.Security.JwtExtensions.ApiTests/NetDevPack.Security.JwtExtensions.ApiTests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0;net7.0;net8.0 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /tests/NetDevPack.Security.JwtExtensions.ApiTests/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Hosting; 2 | using Microsoft.Extensions.Hosting; 3 | 4 | namespace NetDevPack.Security.JwtExtensions.ApiTests 5 | { 6 | public class Program 7 | { 8 | public static void Main(string[] args) 9 | { 10 | CreateHostBuilder(args).Build().Run(); 11 | } 12 | 13 | public static IHostBuilder CreateHostBuilder(string[] args) => 14 | Host.CreateDefaultBuilder(args) 15 | .ConfigureWebHostDefaults(webBuilder => 16 | { 17 | webBuilder.UseStartup(); 18 | }); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /tests/NetDevPack.Security.JwtExtensions.ApiTests/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:60223", 8 | "sslPort": 44366 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "weatherforecast", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "ApiTest": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "weatherforecast", 24 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /tests/NetDevPack.Security.JwtExtensions.ApiTests/Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Authentication.JwtBearer; 2 | using Microsoft.AspNetCore.Builder; 3 | using Microsoft.AspNetCore.Hosting; 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | 8 | namespace NetDevPack.Security.JwtExtensions.ApiTests 9 | { 10 | public class Startup 11 | { 12 | public Startup(IConfiguration configuration) 13 | { 14 | Configuration = configuration; 15 | } 16 | 17 | public IConfiguration Configuration { get; } 18 | 19 | // This method gets called by the runtime. Use this method to add services to the container. 20 | public void ConfigureServices(IServiceCollection services) 21 | { 22 | services.AddControllers(); 23 | 24 | services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) 25 | .AddJwtBearer(options => 26 | { 27 | options.IncludeErrorDetails = true; // <- great for debugging 28 | options.SetJwksOptions(new JwkOptions("https://localhost:5001/jwks", audience: "jwt-test", issuer: "https://mysite.com")); 29 | }); 30 | } 31 | 32 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 33 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 34 | { 35 | if (env.IsDevelopment()) 36 | { 37 | app.UseDeveloperExceptionPage(); 38 | } 39 | 40 | app.UseHttpsRedirection(); 41 | 42 | app.UseRouting(); 43 | 44 | app.UseAuthentication(); 45 | 46 | app.UseAuthorization(); 47 | 48 | app.UseEndpoints(endpoints => 49 | { 50 | endpoints.MapControllers(); 51 | }); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /tests/NetDevPack.Security.JwtExtensions.ApiTests/WeatherForecast.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace NetDevPack.Security.JwtExtensions.ApiTests 4 | { 5 | public class WeatherForecast 6 | { 7 | public DateTime Date { get; set; } 8 | 9 | public int TemperatureC { get; set; } 10 | 11 | public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); 12 | 13 | public string Summary { get; set; } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /tests/NetDevPack.Security.JwtExtensions.ApiTests/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /tests/NetDevPack.Security.JwtExtensions.ApiTests/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | "AllowedHosts": "*" 10 | } 11 | -------------------------------------------------------------------------------- /tests/NetDevPack.Security.JwtExtensions.Tests/Infra/AuthMiddleware.cs: -------------------------------------------------------------------------------- 1 | using Bogus; 2 | using Microsoft.AspNetCore.Http; 3 | using Microsoft.IdentityModel.Tokens; 4 | using System; 5 | using System.IdentityModel.Tokens.Jwt; 6 | using System.Security.Claims; 7 | using System.Threading.Tasks; 8 | using NetDevPack.Security.Jwt.Core.Interfaces; 9 | 10 | namespace NetDevPack.Security.JwtExtensions.Tests.Infra 11 | { 12 | public class AuthMiddleware 13 | { 14 | private readonly RequestDelegate _next; 15 | private static string _jws; 16 | public AuthMiddleware(RequestDelegate next) 17 | { 18 | _next = next; 19 | } 20 | 21 | public async Task Invoke(HttpContext httpContext, IJwtService keyService) 22 | { 23 | if (!string.IsNullOrEmpty(_jws)) 24 | { 25 | await httpContext.Response.WriteAsync(_jws); 26 | return; 27 | } 28 | 29 | var faker = new Faker(); 30 | var tokenHandler = new JwtSecurityTokenHandler(); 31 | var creds = await keyService.GetCurrentSigningCredentials(); 32 | var tokenDescriptor = new SecurityTokenDescriptor 33 | { 34 | Subject = new ClaimsIdentity(new Claim[] 35 | { 36 | new Claim(JwtRegisteredClaimNames.UniqueName, faker.Person.UserName), 37 | new Claim(JwtRegisteredClaimNames.Amr, "Fake"), 38 | new Claim(JwtRegisteredClaimNames.Email, faker.Person.Email), 39 | new Claim(JwtRegisteredClaimNames.GivenName, faker.Person.FullName), 40 | }), 41 | Expires = DateTime.UtcNow.AddHours(1), 42 | Audience = "jwt-test", 43 | Issuer = "https://mysite.com", 44 | SigningCredentials = creds 45 | }; 46 | var jwt = tokenHandler.CreateToken(tokenDescriptor); 47 | _jws = tokenHandler.WriteToken(jwt); 48 | await httpContext.Response.WriteAsync(_jws); 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /tests/NetDevPack.Security.JwtExtensions.Tests/Infra/Server.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.Extensions.DependencyInjection; 5 | using System; 6 | using System.IO; 7 | using System.Net.Http; 8 | using System.Threading.Tasks; 9 | 10 | namespace NetDevPack.Security.JwtExtensions.Tests.Infra 11 | { 12 | public class Server : IDisposable 13 | { 14 | public const string ServerUrl = "https://localhost:5001"; 15 | public readonly IWebHost TestServer; 16 | public readonly HttpClient HttpClient = new HttpClient() { BaseAddress = new Uri(ServerUrl) }; 17 | 18 | public Server() 19 | { 20 | TestServer = 21 | new WebHostBuilder() 22 | .UseKestrel() 23 | .ConfigureServices(services => 24 | { 25 | services.AddMemoryCache(); 26 | services.AddJwksManager().PersistKeysInMemory(); 27 | }) 28 | .Configure(app => 29 | { 30 | app.UseDeveloperExceptionPage(); 31 | app.UseJwksDiscovery(); 32 | app.Map(new PathString("/auth"), x => x.UseMiddleware()); 33 | 34 | }) 35 | .UseUrls(ServerUrl).Build(); 36 | TestServer.Start(); 37 | 38 | } 39 | 40 | public void Dispose() 41 | { 42 | Task.WaitAll(TestServer?.StopAsync()!); 43 | HttpClient?.Dispose(); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /tests/NetDevPack.Security.JwtExtensions.Tests/JwksTests.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.AspNetCore.Mvc.Testing; 3 | using NetDevPack.Security.JwtExtensions.Tests.Infra; 4 | using System; 5 | using System.IO; 6 | using System.Linq; 7 | using System.Net; 8 | using System.Net.Http; 9 | using System.Net.Http.Headers; 10 | using System.Threading.Tasks; 11 | using NetDevPack.Security.JwtExtensions.ApiTests; 12 | using Xunit; 13 | using Xunit.Abstractions; 14 | 15 | namespace NetDevPack.Security.JwtExtensions.Tests 16 | { 17 | public class JwksTests : IClassFixture>, IDisposable 18 | { 19 | private readonly WebApplicationFactory _webApplicationFactory; 20 | private readonly ITestOutputHelper _output; 21 | private HttpClient _client; 22 | private Server _server; 23 | 24 | private const string InvalidSignature = "eyJhbGciOiJFUzI1NiIsImtpZCI6Im1qeEQyQUphcXE4cW8zMWRiMjFyTGciLCJ0eXAiOiJhdCtqd3QifQ.eyJuYmYiOjE1OTU3MzQ0MzksImV4cCI6MTU5NTczODAzOSwiaXNzIjoiaHR0cHM6Ly9zc28uanBwcm9qZWN0Lm5ldCIsImF1ZCI6ImpwX2FwaSIsImNsaWVudF9pZCI6IklTNC1BZG1pbiIsInN1YiI6Ijc0MkYyMzk2LTg1N0MtNEI0Qy01NUExLTA4RDYzMTczMUIzRCIsImF1dGhfdGltZSI6MTU5NTczNDQzMiwiaWRwIjoiR29vZ2xlIiwiaXM0LXJpZ2h0cyI6Im1hbmFnZXIiLCJyb2xlIjoiQWRtaW5pc3RyYXRvciIsImVtYWlsIjoiYmhkZWJyaXRvQGdtYWlsLmNvbSIsInVzZXJuYW1lIjoiYnJ1bm8iLCJzY29wZSI6WyJvcGVuaWQiLCJwcm9maWxlIiwiZW1haWwiLCJyb2xlIiwianBfYXBpLmlzNCJdLCJhbXIiOlsiZXh0ZXJuYWwiXX0.i4_sfpzcS5oVVdgQqyH2qJfp02Jl-dAm3KuDr8G1BEz2flw6d3yPB8C82qhuM9PDNO7UBcXm8LJdMfI--SUK0A"; 25 | 26 | public JwksTests(WebApplicationFactory webApplicationFactory, ITestOutputHelper output) 27 | { 28 | _webApplicationFactory = webApplicationFactory; 29 | _output = output; 30 | _client = webApplicationFactory.CreateClient(); 31 | _server = new Server(); 32 | // Force key generation 33 | var tokenRequest = new HttpRequestMessage(HttpMethod.Get, "https://localhost:5001/auth"); 34 | _server.HttpClient.SendAsync(tokenRequest).Wait(); 35 | } 36 | 37 | [Fact] 38 | public async Task Should_200() 39 | { 40 | var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost/WeatherForecast"); 41 | 42 | var response = await _client.SendAsync(request); 43 | 44 | response.StatusCode.Should().Be(HttpStatusCode.OK); 45 | } 46 | 47 | [Fact] 48 | public async Task Should_401() 49 | { 50 | var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost/ProtectedWeatherForecast"); 51 | request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "generic token"); 52 | var response = await _client.SendAsync(request); 53 | 54 | response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); 55 | } 56 | 57 | [Fact] 58 | public async Task Should_Not_Validate_Bearer_Token_With_Invalid_Signature() 59 | { 60 | var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost/ProtectedWeatherForecast"); 61 | request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", InvalidSignature); 62 | var response = await _client.SendAsync(request); 63 | 64 | response.StatusCode.Should().Be(HttpStatusCode.Unauthorized); 65 | } 66 | 67 | [Fact] 68 | public async Task Should_Validate_Bearer_Token() 69 | { 70 | var tokenRequest = new HttpRequestMessage(HttpMethod.Get, "https://localhost:5001/auth"); 71 | var tokenResponse = await _server.HttpClient.SendAsync(tokenRequest); 72 | var token = await tokenResponse.Content.ReadAsStringAsync(); 73 | 74 | var request = new HttpRequestMessage(HttpMethod.Get, "https://localhost/ProtectedWeatherForecast"); 75 | request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); 76 | var response = await _client.SendAsync(request); 77 | 78 | try { response.EnsureSuccessStatusCode(); } catch { _output.WriteLine(string.Join(" ", response.Headers.GetValues("WWW-Authenticate"))); throw; }; 79 | } 80 | 81 | 82 | 83 | 84 | public void Dispose() 85 | { 86 | _server.Dispose(); 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /tests/NetDevPack.Security.JwtExtensions.Tests/NetDevPack.Security.JwtExtensions.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net6.0;net7.0;net8.0 5 | 10.0 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | all 18 | runtime; build; native; contentfiles; analyzers; buildtransitive 19 | 20 | 21 | all 22 | runtime; build; native; contentfiles; analyzers; buildtransitive 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | --------------------------------------------------------------------------------