├── logo.png ├── src ├── HexMaster.Functions.JwtBinding │ ├── Constants.cs │ ├── Configuration │ │ ├── JwtBindingDebugConfiguration.cs │ │ └── JwtBindingConfiguration.cs │ ├── Model │ │ └── AuthorizedModel.cs │ ├── Exceptions │ │ ├── ConfigurationException.cs │ │ ├── AuthorizationScopesException.cs │ │ ├── AuthorizationFailedException.cs │ │ ├── AuthorizationOperationException.cs │ │ ├── IssuerPatternValidationException.cs │ │ ├── AuthorizationSchemeNotSupportedException.cs │ │ └── IdentityNotAllowedException.cs │ ├── JwtBindingStartup.cs │ ├── JwtBindingExtension.cs │ ├── JwtBindingAttribute.cs │ ├── HexMaster.Functions.JwtBinding.csproj │ ├── JwtBinding.cs │ └── TokenValidator │ │ └── TokenValidatorService.cs ├── HexMaster.Functions.JwtBinding.Tests │ ├── HexMaster.Functions.JwtBinding.Tests.csproj │ └── TokenValidator │ │ └── TokenValidatorServiceTests.cs └── JWT Binding.sln ├── .github └── workflows │ ├── build.yml │ └── main.yml ├── CONTRIBUTING.md ├── LICENSE ├── .devcontainer ├── Dockerfile └── devcontainer.json ├── .vscode ├── launch.json └── tasks.json ├── README.md └── .gitignore /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nikneem/azure-functions-jwt-binding/HEAD/logo.png -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding/Constants.cs: -------------------------------------------------------------------------------- 1 | namespace HexMaster.Functions.JwtBinding 2 | { 3 | public class Constants 4 | { 5 | 6 | public const string ConfigurationSectionName = "JwtBinding"; 7 | public const string DefaultAuthorizationHeader = "Authorization"; 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding/Configuration/JwtBindingDebugConfiguration.cs: -------------------------------------------------------------------------------- 1 | namespace HexMaster.Functions.JwtBinding.Configuration 2 | { 3 | public class JwtBindingDebugConfiguration 4 | { 5 | public bool Enabled { get; set; } 6 | public string Subject { get; set; } 7 | public string Name { get; set; } 8 | 9 | } 10 | } -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding/Model/AuthorizedModel.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Claims; 2 | 3 | namespace HexMaster.Functions.JwtBinding.Model 4 | { 5 | public class AuthorizedModel 6 | { 7 | public string Subject { get; set; } 8 | public string Name { get; set; } 9 | public ClaimsPrincipal User { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding/Exceptions/ConfigurationException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HexMaster.Functions.JwtBinding.Exceptions 4 | { 5 | public sealed class ConfigurationException : Exception 6 | { 7 | public ConfigurationException(string message, Exception ex = null) : base(message, ex) 8 | { 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding/Exceptions/AuthorizationScopesException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HexMaster.Functions.JwtBinding.Exceptions 4 | { 5 | public class AuthorizationScopesException: Exception 6 | { 7 | public AuthorizationScopesException(string message, Exception inner = null) : base(message, inner) 8 | { 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding/Exceptions/AuthorizationFailedException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HexMaster.Functions.JwtBinding.Exceptions 4 | { 5 | public sealed class AuthorizationFailedException : Exception 6 | { 7 | 8 | internal AuthorizationFailedException(Exception innerException) 9 | : base("JWT Token Validation failed, request not authorized", innerException) 10 | { 11 | } 12 | 13 | } 14 | } -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding/Exceptions/AuthorizationOperationException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HexMaster.Functions.JwtBinding.Exceptions 4 | { 5 | public sealed class AuthorizationOperationException : Exception 6 | { 7 | internal AuthorizationOperationException() 8 | : base("Could not validate JWT Token because the token could not be retrieved from a valid HTTP Context") 9 | { 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding/Exceptions/IssuerPatternValidationException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HexMaster.Functions.JwtBinding.Exceptions 4 | { 5 | public class IssuerPatternValidationException : Exception 6 | { 7 | internal IssuerPatternValidationException(string issuer, string pattern) 8 | : base($"The issuer '{issuer}' does not match the pattern '{pattern}', token validation failed") 9 | { 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding/Exceptions/AuthorizationSchemeNotSupportedException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HexMaster.Functions.JwtBinding.Exceptions 4 | { 5 | public sealed class AuthorizationSchemeNotSupportedException : Exception 6 | { 7 | internal AuthorizationSchemeNotSupportedException(string scheme) : 8 | base($"The authorization scheme '{scheme}' is not supported. Please use the Bearer scheme") 9 | { 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding/JwtBindingStartup.cs: -------------------------------------------------------------------------------- 1 | using HexMaster.Functions.JwtBinding; 2 | using Microsoft.Azure.WebJobs; 3 | using Microsoft.Azure.WebJobs.Hosting; 4 | 5 | [assembly: WebJobsStartup(typeof(JwtBindingStartup))] 6 | namespace HexMaster.Functions.JwtBinding 7 | { 8 | public class JwtBindingStartup : IWebJobsStartup 9 | { 10 | public void Configure(IWebJobsBuilder builder) 11 | { 12 | builder.AddJwtBindingExtension(); 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding/Exceptions/IdentityNotAllowedException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HexMaster.Functions.JwtBinding.Exceptions 4 | { 5 | public class IdentityNotAllowedException : AuthorizationScopesException 6 | { 7 | public IdentityNotAllowedException(string message, Exception inner = null) : base( 8 | $"Identity provided in the `sub` claim is not authorizied to contact this endpoint.{Environment.NewLine}{message}", 9 | inner) 10 | { 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build & Test 2 | 3 | on: 4 | pull_request: 5 | branches: [ main ] 6 | 7 | jobs: 8 | build: 9 | 10 | runs-on: ubuntu-latest 11 | env: 12 | working-directory: ./src 13 | 14 | steps: 15 | - uses: actions/checkout@v2 16 | - name: Setup .NET Core 17 | uses: actions/setup-dotnet@v1 18 | with: 19 | dotnet-version: 3.1.301 20 | - name: Install dependencies 21 | run: dotnet restore "./src" 22 | - name: Build solution 23 | run: dotnet build "./src" --configuration Release --no-restore 24 | - name: Execute unit tests 25 | run: dotnet test "./src" 26 | -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding.Tests/HexMaster.Functions.JwtBinding.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding/Configuration/JwtBindingConfiguration.cs: -------------------------------------------------------------------------------- 1 | namespace HexMaster.Functions.JwtBinding.Configuration 2 | { 3 | public sealed class JwtBindingConfiguration 4 | { 5 | 6 | public const string SectionName = Constants.ConfigurationSectionName; 7 | 8 | public string Issuer { get; set; } 9 | public string IssuerPattern { get; set; } 10 | public string Audience { get; set; } 11 | public string SymmetricSecuritySigningKey { get; set; } 12 | public string X509CertificateSigningKey { get; set; } 13 | public string Scopes { get; set; } 14 | public string Roles { get; set; } 15 | public string AllowedIdentities { get; set; } 16 | public string Header { get; set; } 17 | 18 | public JwtBindingDebugConfiguration DebugConfiguration { get; set; } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Build & Release to NuGet 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | env: 11 | working-directory: ./src 12 | 13 | steps: 14 | - uses: actions/checkout@v2 15 | - name: Setup .NET Core 16 | uses: actions/setup-dotnet@v1 17 | with: 18 | dotnet-version: 3.1.301 19 | - name: Install dependencies 20 | run: dotnet restore "./src" 21 | - name: Build solution 22 | run: dotnet build "./src" --configuration Release --no-restore 23 | - name: Execute unit tests 24 | run: dotnet test "./src" 25 | - name: Publish NuGet 26 | uses: brandedoutcast/publish-nuget@v2.5.5 27 | with: 28 | PROJECT_FILE_PATH: src/HexMaster.Functions.JwtBinding/HexMaster.Functions.JwtBinding.csproj 29 | NUGET_KEY: ${{secrets.NUGET_KEY}} 30 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to the Azure Functions JWT Binding 2 | 3 | Thanks for helping make the Azure Functions JWT Binding better 😍. 4 | 5 | There are many areas we can use contributions - ranging from code, documentation, feature proposals, issue triage, samples, and content creation. 6 | 7 | ## Getting Help 8 | 9 | If you have a question about the Azure Functions JWT Binding or how best to contribute, use either one of the issues you want to work on and write comments, questions or remarks there. We're happy to help you out. 10 | 11 | ## Contributing on Issues 12 | 13 | One of the easiest ways to contribute is through [issues](https://github.com/nikneem/azure-functions-jwt-binding/issues). Just find an issue that fits your skills, or you would like to learn on / get involved with. It's important to leave a message you're going to work on the issue so we can assign it to you. This prevents issues from being addressed multiple times. 14 | 15 | ### Testing 16 | 17 | Changes made to existing code, or new features added to the system should be backed by unit tests. 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 nikneem 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 | -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding/JwtBindingExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using HexMaster.Functions.JwtBinding.Configuration; 3 | using HexMaster.Functions.JwtBinding.TokenValidator; 4 | using Microsoft.Azure.WebJobs; 5 | using Microsoft.Extensions.Configuration; 6 | using Microsoft.Extensions.DependencyInjection; 7 | 8 | namespace HexMaster.Functions.JwtBinding 9 | { 10 | public static class JwtBindingExtension 11 | { 12 | public static IWebJobsBuilder AddJwtBindingExtension(this IWebJobsBuilder builder) 13 | { 14 | if (builder == null) 15 | { 16 | throw new ArgumentNullException(nameof(builder)); 17 | } 18 | 19 | var serviceProvider = builder.Services.BuildServiceProvider(); 20 | 21 | var configuration = serviceProvider.GetService(); 22 | builder.Services.Configure(configuration.GetSection(JwtBindingConfiguration.SectionName)); 23 | 24 | builder.Services.AddSingleton(); 25 | builder.AddExtension(); 26 | return builder; 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.162.0/containers/dotnet/.devcontainer/base.Dockerfile 2 | 3 | # [Choice] .NET version: 5.0, 3.1, 2.1 4 | ARG VARIANT="5.0" 5 | FROM mcr.microsoft.com/vscode/devcontainers/dotnetcore:0-${VARIANT} 6 | 7 | # [Option] Install Node.js 8 | # ARG INSTALL_NODE="true" 9 | # ARG NODE_VERSION="lts/*" 10 | # RUN if [ "${INSTALL_NODE}" = "true" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi 11 | 12 | # [Option] Install Azure CLI 13 | # ARG INSTALL_AZURE_CLI="false" 14 | # COPY library-scripts/azcli-debian.sh /tmp/library-scripts/ 15 | # RUN if [ "$INSTALL_AZURE_CLI" = "true" ]; then bash /tmp/library-scripts/azcli-debian.sh; fi \ 16 | # && apt-get clean -y && rm -rf /var/lib/apt/lists/* /tmp/library-scripts 17 | 18 | # [Optional] Uncomment this section to install additional OS packages. 19 | # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 20 | # && apt-get -y install --no-install-recommends 21 | 22 | # [Optional] Uncomment this line to install global node packages. 23 | # RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1 -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | // Use IntelliSense to find out which attributes exist for C# debugging 6 | // Use hover for the description of the existing attributes 7 | // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | // If you have changed target frameworks, make sure to update the program path. 13 | "program": "${workspaceFolder}/src/HexMaster.Functions.JwtBinding.Tests/bin/Debug/netcoreapp3.1/HexMaster.Functions.JwtBinding.Tests.dll", 14 | "args": [], 15 | "cwd": "${workspaceFolder}/src/HexMaster.Functions.JwtBinding.Tests", 16 | // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console 17 | "console": "internalConsole", 18 | "stopAtEntry": false 19 | }, 20 | { 21 | "name": ".NET Core Attach", 22 | "type": "coreclr", 23 | "request": "attach", 24 | "processId": "${command:pickProcess}" 25 | } 26 | ] 27 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/src/HexMaster.Functions.JwtBinding.Tests/HexMaster.Functions.JwtBinding.Tests.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/src/HexMaster.Functions.JwtBinding.Tests/HexMaster.Functions.JwtBinding.Tests.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/src/HexMaster.Functions.JwtBinding.Tests/HexMaster.Functions.JwtBinding.Tests.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /src/JWT Binding.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30204.135 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HexMaster.Functions.JwtBinding", "HexMaster.Functions.JwtBinding\HexMaster.Functions.JwtBinding.csproj", "{8E7D20EB-231E-412F-982B-972451BAB6E8}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HexMaster.Functions.JwtBinding.Tests", "HexMaster.Functions.JwtBinding.Tests\HexMaster.Functions.JwtBinding.Tests.csproj", "{DDA1D7D6-4C9D-4032-A269-93F4BF0C9A5F}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {8E7D20EB-231E-412F-982B-972451BAB6E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {8E7D20EB-231E-412F-982B-972451BAB6E8}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {8E7D20EB-231E-412F-982B-972451BAB6E8}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {8E7D20EB-231E-412F-982B-972451BAB6E8}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {DDA1D7D6-4C9D-4032-A269-93F4BF0C9A5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {DDA1D7D6-4C9D-4032-A269-93F4BF0C9A5F}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {DDA1D7D6-4C9D-4032-A269-93F4BF0C9A5F}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {DDA1D7D6-4C9D-4032-A269-93F4BF0C9A5F}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {548C17A1-B4EB-48B2-A281-AABD372853BB} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the README at: 2 | // https://github.com/microsoft/vscode-dev-containers/tree/v0.162.0/containers/dotnet 3 | { 4 | "name": "C# (.NET)", 5 | "build": { 6 | "dockerfile": "Dockerfile", 7 | "args": { 8 | // Update 'VARIANT' to pick a .NET Core version: 2.1, 3.1, 5.0 9 | "VARIANT": "3.1", 10 | // Options 11 | "INSTALL_NODE": "false", 12 | "NODE_VERSION": "lts/*", 13 | "INSTALL_AZURE_CLI": "false" 14 | } 15 | }, 16 | 17 | // Set *default* container specific settings.json values on container create. 18 | "settings": { 19 | "terminal.integrated.shell.linux": "/bin/bash", 20 | "github.codespaces.defaultExtensions": [ 21 | "GitHub.codespaces", 22 | "GitHub.vscode-pull-request-github" 23 | ] 24 | }, 25 | 26 | // Add the IDs of extensions you want installed when the container is created. 27 | "extensions": [ 28 | "ms-dotnettools.csharp", 29 | "GitHub.codespaces" 30 | ], 31 | 32 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 33 | // "forwardPorts": [5000, 5001], 34 | 35 | // [Optional] To reuse of your local HTTPS dev cert: 36 | // 37 | // 1. Export it locally using this command: 38 | // * Windows PowerShell: 39 | // dotnet dev-certs https --trust; dotnet dev-certs https -ep "$env:USERPROFILE/.aspnet/https/aspnetapp.pfx" -p "SecurePwdGoesHere" 40 | // * macOS/Linux terminal: 41 | // dotnet dev-certs https --trust; dotnet dev-certs https -ep "${HOME}/.aspnet/https/aspnetapp.pfx" -p "SecurePwdGoesHere" 42 | // 43 | // 2. Uncomment these 'remoteEnv' lines: 44 | // "remoteEnv": { 45 | // "ASPNETCORE_Kestrel__Certificates__Default__Password": "SecurePwdGoesHere", 46 | // "ASPNETCORE_Kestrel__Certificates__Default__Path": "/home/vscode/.aspnet/https/aspnetapp.pfx", 47 | // }, 48 | // 49 | // 3. Do one of the following depending on your scenario: 50 | // * When using GitHub Codespaces and/or Remote - Containers: 51 | // 1. Start the container 52 | // 2. Drag ~/.aspnet/https/aspnetapp.pfx into the root of the file explorer 53 | // 3. Open a terminal in VS Code and run "mkdir -p /home/vscode/.aspnet/https && mv aspnetapp.pfx /home/vscode/.aspnet/https" 54 | // 55 | // * If only using Remote - Containers with a local container, uncomment this line instead: 56 | // "mounts": [ "source=${env:HOME}${env:USERPROFILE}/.aspnet/https,target=/home/vscode/.aspnet/https,type=bind" ], 57 | 58 | // Use 'postCreateCommand' to run commands after the container is created. 59 | // "postCreateCommand": "dotnet restore", 60 | 61 | // Comment out connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. 62 | "remoteUser": "vscode" 63 | } 64 | -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding/JwtBindingAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel; 3 | using Microsoft.Azure.WebJobs.Description; 4 | 5 | namespace HexMaster.Functions.JwtBinding 6 | { 7 | 8 | [Binding] 9 | [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.ReturnValue)] 10 | public class JwtBindingAttribute : Attribute 11 | { 12 | public JwtBindingAttribute() 13 | { 14 | } 15 | 16 | public JwtBindingAttribute(string issuer = null, string audience = null, string scopes = null, string roles = null, string signature = null, string allowedIdentities = null, string header = null) 17 | { 18 | Issuer = issuer; 19 | Audience = audience; 20 | Scopes = scopes; 21 | Roles = roles; 22 | Signature = signature; 23 | AllowedIdentities = allowedIdentities; 24 | Header = header; 25 | } 26 | 27 | [AutoResolve] 28 | [Description("Comma seperated scopes, these scopes must be present in the JWT Token to validate succesfully")] 29 | public string Scopes { get; set; } 30 | 31 | [AutoResolve] 32 | [Description("Comma seperated roles, these roles must be present in the JWT Token to validate succesfully")] 33 | public string Roles { get; set; } 34 | 35 | [AutoResolve] 36 | [Description("When passed, the token validator will validate if the passed token at least contains the given audience. When the audience is set to null or empty, the audience validation will not be done.")] 37 | public string Audience { get; set; } 38 | 39 | [AutoResolve] 40 | [Description("The name of your token issuer. Usually this is the base URL of all services you call to authorize")] 41 | public string Issuer { get; set; } 42 | 43 | [AutoResolve] 44 | [Description("Pass in a valid symmetric security signing key. If no signature is passed, the validator will try to download them from your token provider. When that fails, the token validation fails.")] 45 | public string Signature { get; set; } 46 | 47 | [AutoResolve] 48 | [Description("Pass in a valid base64-encoded X509 certificate public key. If there is no value for Signature nor X509CertificateSigningKey parameter, the validator will try to download the signing keys from your token provider, i.e. Issuer. When that fails, the token validation fails.")] 49 | public string X509CertificateSigningKey { get; set; } 50 | 51 | [AutoResolve] 52 | [Description("Comma seperated identifiers of identities which are allowed. This will try to be matched on the `sub` claim of the token.")] 53 | public string AllowedIdentities { get; set; } 54 | 55 | [AutoResolve] 56 | [Description("The name of the header to use that contains the Bearer token.")] 57 | public string Header { get; set; } 58 | } 59 | } -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding/HexMaster.Functions.JwtBinding.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.1 5 | true 6 | 1.4.3 7 | Eduard Keilholz 8 | Azure Functions JWT Validation Input Binding 9 | This is an input binding for Azure Functions allowing you to validate JWT tokens for Azure Functions with a HTTP trigger. 10 | https://github.com/nikneem/azure-functions-jwt-binding 11 | LICENSE 12 | https://github.com/nikneem/azure-functions-jwt-binding/raw/main/logo.png 13 | https://github.com/nikneem/azure-functions-jwt-binding 14 | C#, Azure Functions, Binding, JWT, Token, Validation 15 | Added support for a custom authorization header through configuration (issue #42) 16 | 17 | Added support for X905 Certificate signatures 18 | 19 | Added a check for existence of the Authorization header in the HTTP request and throws in case it's missing 20 | 21 | Added pattern validation for the issuer. For more information, see issue #31 on GitHub (https://github.com/nikneem/azure-functions-jwt-binding/issues/31) 22 | 23 | Added options pattern. This means you no longer have to pass configuration values through the binding attributes. Values from you app config are used instead. You can still use the attribute configuration to configure the binding, or to overwrite the default configuration. 24 | 25 | - 1.1.2 - Fixed configuration bug 26 | - 1.2.0 - Added AllowedIdenities feature 27 | 1.4.3.0 28 | git 29 | logo.png 30 | 1.4.3.0 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | True 46 | 47 | 48 | 49 | True 50 | 51 | 52 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding/JwtBinding.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IdentityModel.Tokens.Jwt; 3 | using System.Net.Http.Headers; 4 | using System.Security.Claims; 5 | using HexMaster.Functions.JwtBinding.Configuration; 6 | using HexMaster.Functions.JwtBinding.Exceptions; 7 | using HexMaster.Functions.JwtBinding.Model; 8 | using HexMaster.Functions.JwtBinding.TokenValidator; 9 | using Microsoft.AspNetCore.Http; 10 | using Microsoft.Azure.WebJobs.Description; 11 | using Microsoft.Azure.WebJobs.Host.Config; 12 | using Microsoft.Extensions.Logging; 13 | using Microsoft.Extensions.Options; 14 | 15 | namespace HexMaster.Functions.JwtBinding 16 | { 17 | [Extension("JwtBinding", Constants.ConfigurationSectionName)] 18 | public class JwtBinding : IExtensionConfigProvider 19 | { 20 | private readonly TokenValidatorService _service; 21 | private readonly IOptions _configuration; 22 | private readonly IHttpContextAccessor _http; 23 | private readonly ILogger _logger; 24 | 25 | public JwtBinding( 26 | TokenValidatorService service, 27 | IOptions configuration, 28 | IHttpContextAccessor http, 29 | ILogger logger) 30 | { 31 | _service = service; 32 | _configuration = configuration; 33 | _http = http; 34 | _logger = logger; 35 | } 36 | 37 | public void Initialize(ExtensionConfigContext context) 38 | { 39 | var rule = context.AddBindingRule(); 40 | rule.BindToInput(BuildItemFromAttribute); 41 | } 42 | 43 | private AuthorizedModel BuildItemFromAttribute(JwtBindingAttribute arg) 44 | { 45 | var configuration = GetFunctionConfiguration(arg); 46 | 47 | if ((configuration.DebugConfiguration?.Enabled).GetValueOrDefault()) 48 | { 49 | _logger.LogWarning("## WARNING ## - The JWT Validation Binding is running in DEBUG mode and currently returns fixed values!"); 50 | return new AuthorizedModel 51 | { 52 | Name = configuration.DebugConfiguration?.Name, 53 | Subject = configuration.DebugConfiguration?.Subject, 54 | User = GetUserFromDebugConfiguration(configuration) 55 | }; 56 | } 57 | 58 | if (string.IsNullOrWhiteSpace(configuration.Issuer)) 59 | { 60 | _logger.LogWarning("No valid issuer configured, cannot validate token"); 61 | throw new ArgumentNullException(nameof(arg.Issuer), "The JwtBinding requires an issuer to validate JWT Tokens"); 62 | } 63 | 64 | if (_http.HttpContext != null) 65 | { 66 | var authHeaderValue = _http.HttpContext.Request.Headers[configuration.Header]; 67 | 68 | if (AuthenticationHeaderValue.TryParse(authHeaderValue, out AuthenticationHeaderValue headerValue)) 69 | { 70 | _logger.LogInformation("Now validating token"); 71 | 72 | return _service.ValidateToken(headerValue, configuration); 73 | } 74 | 75 | throw new AuthorizationFailedException( 76 | new Exception("Authorization header is missing, add a bearer token to the header of your HTTP request") 77 | ); 78 | } 79 | 80 | throw new AuthorizationOperationException(); 81 | } 82 | 83 | private JwtBindingConfiguration GetFunctionConfiguration(JwtBindingAttribute arg) 84 | { 85 | var configuration = _configuration.Value ?? new JwtBindingConfiguration(); 86 | configuration.Issuer = arg.Issuer ?? configuration.Issuer; 87 | configuration.Audience = arg.Audience ?? configuration.Audience; 88 | configuration.Scopes = arg.Scopes ?? configuration.Scopes; 89 | configuration.Roles = arg.Roles ?? configuration.Roles; 90 | configuration.SymmetricSecuritySigningKey = arg.Signature ?? configuration.SymmetricSecuritySigningKey; 91 | configuration.X509CertificateSigningKey = arg.X509CertificateSigningKey ?? configuration.X509CertificateSigningKey; 92 | configuration.AllowedIdentities = arg.AllowedIdentities ?? configuration.AllowedIdentities; 93 | configuration.Header = arg.Header ?? configuration.Header ?? Constants.DefaultAuthorizationHeader; 94 | return configuration; 95 | } 96 | 97 | private ClaimsPrincipal GetUserFromDebugConfiguration(JwtBindingConfiguration configuration) 98 | { 99 | var subject = configuration.DebugConfiguration?.Subject; 100 | var name = configuration.DebugConfiguration?.Name; 101 | var claimsIdentity = new ClaimsIdentity(); 102 | 103 | if (!string.IsNullOrEmpty(subject)) { 104 | claimsIdentity.AddClaim(new Claim(JwtRegisteredClaimNames.NameId, subject)); 105 | } 106 | 107 | if (!string.IsNullOrEmpty(name)) { 108 | claimsIdentity.AddClaim(new Claim(JwtRegisteredClaimNames.GivenName, name)); 109 | } 110 | 111 | return new ClaimsPrincipal(claimsIdentity); 112 | } 113 | } 114 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Azure Functions Input Binding for JWT Tokens 2 | 3 | This is an Azure Functions binding validating JWT Tokens for HTTP Triggered Azure Functions. 4 | 5 | [![Code Smells](https://sonarcloud.io/api/project_badges/measure?project=nikneem_azure-functions-jwt-binding&metric=code_smells)](https://sonarcloud.io/dashboard?id=nikneem_azure-functions-jwt-binding) 6 | [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=nikneem_azure-functions-jwt-binding&metric=alert_status)](https://sonarcloud.io/dashboard?id=nikneem_azure-functions-jwt-binding) 7 | [![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=nikneem_azure-functions-jwt-binding&metric=reliability_rating)](https://sonarcloud.io/dashboard?id=nikneem_azure-functions-jwt-binding) 8 | [![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=nikneem_azure-functions-jwt-binding&metric=security_rating)](https://sonarcloud.io/dashboard?id=nikneem_azure-functions-jwt-binding) 9 | [![Technical Debt](https://sonarcloud.io/api/project_badges/measure?project=nikneem_azure-functions-jwt-binding&metric=sqale_index)](https://sonarcloud.io/dashboard?id=nikneem_azure-functions-jwt-binding) 10 | [![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=nikneem_azure-functions-jwt-binding&metric=vulnerabilities)](https://sonarcloud.io/dashboard?id=nikneem_azure-functions-jwt-binding) 11 | 12 | ## Support & Usage 13 | The binding is only tested on ASP.NET Core 3.1 Azure Functions with the Azure Functions v3. 14 | 15 | [Find this package on NuGet](https://www.nuget.org/packages/HexMaster.Functions.JwtBinding/) 16 | 17 | Package Manager 18 | `Install-Package HexMaster.Functions.JwtBinding` 19 | 20 | .NET CLI 21 | `dotnet add package HexMaster.Functions.JwtBinding` 22 | 23 | ## Validating tokens 24 | Let's say you run a SPA in which you want users to log in. You'll probably end up with a JWT token (or Access Token if you like). But now, you want to call a backend system, and pass that token so your backend can verify and identify the user. In conventional ASP.NET Core projects, you can add token validation to the request pipeline. In Azure Functions you can not. And this is where the binding kicks in. You need to, _manually_, validate the token and verify the caller's identity. And I thought is was a good idea to create a custom binding validating the token and -in the end- make sure who calls our functions. 25 | 26 | ## Configuration 27 | The JwtBinding prefixed is used to configure the binding. The binding uses the Options Pattern to inject the *JwtBinding* configuration section as a *JwtBindingConfiguration* object. The values in the configuration can be overridden by the Binding Attribute arguments. 28 | 29 | The Issuer value is mandatory. When no issuer was configured using the app config, or the attribute an exception will be raised and no validation will be done. 30 | 31 | The following properties are available using the configuration: 32 | 33 | 34 | * **Issuer** is the name of the issuer. The binding new assumes this is a valid URL to your token provider. This URL is also used to download signatures when no signature was provided through configuration. 35 | 36 | * **Audience** is the name of your current audience (client). The token contains a list of 0 or more valid audiences. When configured, the token will be inspected and the configured value must be in the list of token's audiences. When no value was configured, audience validation will be skipped. 37 | 38 | * **Signature** is the value of your token signature. This is only when you're using a symmetric signature which is not recommended. If you don't use a symmetric signature, the binding is going to try and download the signature from your token provider. At this time it is not (yet) possible to configure a public key for signature validation. 39 | 40 | * **Scopes** is an optional list of (comma separated) scopes. When configured, all configured scopes must be present in the token. If no scopes were configured, scope validation will be skipped. 41 | 42 | * **Roles** is an optional list of (comma separated) roles. When configured, all configured roles must be present in the token. If no roles were configured, role validation will be skipped. 43 | 44 | * **AllowedIdentities** is an optional list of (comma separated) identities. When configured, the subject of the token is matched against one of the specified identities. If not found, an exception is thrown. If no identities were configured, identity validation will be skipped. 45 | 46 | * **Header** is an optional value to change the name of the header used for Authorization. i.e. if you want to use `X-Authorization` instead of `Authorization` 47 | 48 | * **DebugConfiguration** is a nested object allowing you to configure your environment for running in debug (development) mode. 49 | * **Enabled** is a switch to turn debug mode on or off. Set this value to `true` to enable debugging mode. 50 | Note that it's far safer to remove the entire configuration block in acceptance/production environments. 51 | * **Subject** is the fixed *Subject* to return when running in debug mode. 52 | * **Name** is the fixed *Name* to return when running in debug mode 53 | 54 | ### Example 55 | This example is an example which you can use to paste in your *local.settings.json* when running your azure functions localhost: 56 | 57 | ```json 58 | "JwtBinding:Issuer": "https://your-token-provider.com", 59 | "JwtBinding:Audience": "your-secret-api", 60 | "JwtBinding:Scopes": "data:read,data:write", 61 | "JwtBinding:Roles": "Role1,Role2", 62 | "JwtBinding:Header": "X-Authorization", 63 | "JwtBinding:AllowedIdentities": "Identity1,Identity2", 64 | "JwtBinding:DebugConfiguration:Enabled": true, 65 | "JwtBinding:DebugConfiguration:Subject": "TheSubject", 66 | "JwtBinding:DebugConfiguration:Name": "TheName" 67 | ``` 68 | 69 | 70 | ## Usage 71 | To use the token binding, simply add an `AuthorizedModel` parameter to your function with the `JwtBinding` attribute and you're good to go. 72 | 73 | ```csharp 74 | // This example fully relies on your app config 75 | [JwtBinding] AuthorizedModel auth 76 | ``` 77 | 78 | ```csharp 79 | // This example relies on your app config, but overwrites 80 | // the scopes configuration with a new value 81 | [JwtBinding(scopes: "data:delete")] AuthorizedModel auth 82 | ``` 83 | 84 | ## About token validation 85 | With JWT Tokens you really want to validate some extra stuff before just accepting the request. The binding uses the [JwtSecurityTokenHandler ](https://docs.microsoft.com/en-us/dotnet/api/system.identitymodel.tokens.jwt.jwtsecuritytokenhandler?view=azure-dotnet&WT.mc_id=AZ-MVP-5003924) class under the hood, which takes care of some validations for us. Not all of them however. 86 | 87 | ### Issuer and Audiences 88 | You may want to validate the Issuer and/or Audience of the token. 89 | 90 | Issuer check means 91 | - Check if the token is generated by the provider that I expect 92 | 93 | Audience check 94 | - Check if the called is allowed to access this API 95 | 96 | If you use the JwtBinding attribute without parameters, neither one of these checks are done. However, you can pass the issuer and audience as a parameter to the `JwtBindingAttribute` like so: 97 | ```csharp 98 | [JwtBinding("%JwtBinding:Issuer%", "%JwtBinding:Audience%")] AuthorizedModel auth 99 | ``` 100 | 101 | Note `%JwtBinding:Issuer%` is a reference to the configuration of your Azure Function. Make sure the configuration values exist. To run your function locally, add the following to the values section in your `local.settings.json` 102 | 103 | ```json 104 | "JwtBinding:Audience": "your-audience", 105 | "JwtBinding:Issuer": "https://your-token-provider.com" 106 | ``` 107 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding/TokenValidator/TokenValidatorService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IdentityModel.Tokens.Jwt; 4 | using System.Linq; 5 | using System.Net.Http.Headers; 6 | using System.Security.Claims; 7 | using System.Security.Cryptography.X509Certificates; 8 | using System.Text; 9 | using System.Text.RegularExpressions; 10 | using System.Threading.Tasks; 11 | using HexMaster.Functions.JwtBinding.Configuration; 12 | using HexMaster.Functions.JwtBinding.Exceptions; 13 | using HexMaster.Functions.JwtBinding.Model; 14 | using Microsoft.Extensions.Logging; 15 | using Microsoft.IdentityModel.Protocols; 16 | using Microsoft.IdentityModel.Protocols.OpenIdConnect; 17 | using Microsoft.IdentityModel.Tokens; 18 | 19 | namespace HexMaster.Functions.JwtBinding.TokenValidator 20 | { 21 | public class TokenValidatorService 22 | { 23 | private readonly ILogger _logger; 24 | private ICollection _securityKeys; 25 | 26 | public AuthorizedModel ValidateToken( 27 | AuthenticationHeaderValue value, 28 | JwtBindingConfiguration config) 29 | { 30 | if (value?.Scheme != "Bearer") 31 | { 32 | throw new AuthorizationSchemeNotSupportedException(value?.Scheme); 33 | } 34 | if (string.IsNullOrWhiteSpace(config.Issuer)) 35 | { 36 | throw new ConfigurationException("Configuring an issuer is required in order to validate a JWT Token"); 37 | } 38 | 39 | var validationParameter = GetTokenValidationParameters(config.Issuer, config.Audience, config.IssuerPattern); 40 | 41 | validationParameter.IssuerSigningKey = GetIssuerSigningKey(config); 42 | if(validationParameter.IssuerSigningKey == default) 43 | { 44 | validationParameter.IssuerSigningKeys = RetrieveIssuerSigningKeys(config.Issuer).Result; 45 | } 46 | 47 | try 48 | { 49 | var handler = new JwtSecurityTokenHandler(); 50 | handler.InboundClaimTypeMap.Clear(); 51 | var claimsPrincipal = handler.ValidateToken(value.Parameter, validationParameter, out var token); 52 | ValidateIssuerPattern(token, config.IssuerPattern); 53 | ValidateScopes(token, config.Scopes); 54 | ValidateRoles(token, config.Roles); 55 | ValidateIdentities(token, config.AllowedIdentities); 56 | 57 | var displayName = GetDisplayNameFromToken(claimsPrincipal); 58 | return GetAuthorizedModelFromToken(token, displayName, claimsPrincipal); 59 | } 60 | catch (SecurityTokenSignatureKeyNotFoundException ex1) 61 | { 62 | _logger.LogError(ex1, "Failed to validate token signature, token is considered to be invalid"); 63 | throw new AuthorizationFailedException(ex1); 64 | } 65 | catch (SecurityTokenException ex2) 66 | { 67 | _logger.LogError(ex2, "Failed to validate, token is considered to be invalid"); 68 | throw new AuthorizationFailedException(ex2); 69 | } 70 | catch (Exception ex) 71 | { 72 | _logger.LogError(ex, "Unknown exception occurred while trying to validate JWT Token"); 73 | throw new AuthorizationFailedException(ex); 74 | } 75 | } 76 | 77 | private static AuthorizedModel GetAuthorizedModelFromToken(SecurityToken token, string displayName, ClaimsPrincipal claimsPrincipal) 78 | { 79 | if (token is JwtSecurityToken jwtToken) 80 | { 81 | var nameId = jwtToken.Claims.FirstOrDefault(x => x.Type == JwtRegisteredClaimNames.NameId)?.Value; 82 | var givenName = jwtToken.Claims.FirstOrDefault(x => x.Type == JwtRegisteredClaimNames.GivenName)?.Value; 83 | return new AuthorizedModel 84 | { 85 | Subject = jwtToken.Subject ?? nameId, 86 | Name = displayName ?? givenName, 87 | User = claimsPrincipal 88 | }; 89 | } 90 | 91 | return null; 92 | } 93 | 94 | private void ValidateIssuerPattern(SecurityToken token, string issuerPattern) 95 | { 96 | if (string.IsNullOrWhiteSpace(issuerPattern)) 97 | { 98 | return; 99 | } 100 | 101 | if (!Regex.IsMatch(token.Issuer, issuerPattern)) 102 | { 103 | throw new IssuerPatternValidationException(token.Issuer, issuerPattern); 104 | } 105 | } 106 | 107 | private void ValidateScopes(SecurityToken token, string scopes) 108 | { 109 | var validScopeClaimTypes = new[] {"scp","scope"}; 110 | if (string.IsNullOrWhiteSpace(scopes)) 111 | { 112 | return; 113 | } 114 | 115 | if (token is JwtSecurityToken jwtToken) 116 | { 117 | var tokenScopes = new List(); 118 | foreach (var claimType in validScopeClaimTypes) 119 | { 120 | tokenScopes.AddRange(jwtToken.Claims.Where(clm => clm.Type == claimType).Select(clm => clm.Value)); 121 | } 122 | 123 | foreach (var requiredScope in scopes.Split(',')) 124 | { 125 | if (!tokenScopes.Contains(requiredScope)) 126 | { 127 | throw new AuthorizationScopesException($"Failed to validate scope {requiredScope}, it's missing"); 128 | } 129 | } 130 | } 131 | else 132 | { 133 | throw new AuthorizationScopesException("Failed to validate scopes because the passed token could not be converted to a valid JwtSecurityToken object"); 134 | } 135 | } 136 | private void ValidateRoles(SecurityToken token, string roles) 137 | { 138 | var validScopeClaimTypes = new[] {"roles"}; 139 | if (string.IsNullOrWhiteSpace(roles)) 140 | { 141 | return; 142 | } 143 | 144 | if (token is JwtSecurityToken jwtToken) 145 | { 146 | var tokenRoles = new List(); 147 | foreach (var claimType in validScopeClaimTypes) 148 | { 149 | tokenRoles.AddRange(jwtToken.Claims.Where(clm => clm.Type == claimType).Select(clm => clm.Value)); 150 | } 151 | 152 | foreach (var requiredRole in roles.Split(',')) 153 | { 154 | if (!tokenRoles.Contains(requiredRole)) 155 | { 156 | throw new AuthorizationScopesException($"Failed to validate role {requiredRole}, it's missing"); 157 | } 158 | } 159 | } 160 | else 161 | { 162 | throw new AuthorizationScopesException("Failed to validate roles because the passed token could not be converted to a valid JwtSecurityToken object"); 163 | } 164 | } 165 | 166 | private void ValidateIdentities(SecurityToken validatedToken, string allowedIdentities) 167 | { 168 | if (string.IsNullOrWhiteSpace(allowedIdentities)) 169 | { 170 | return; 171 | } 172 | var identities = allowedIdentities.Split(','); 173 | 174 | if (validatedToken is JwtSecurityToken jwtToken) 175 | { 176 | if (!identities.Any(i => string.Equals(i, jwtToken.Subject, StringComparison.OrdinalIgnoreCase))) 177 | { 178 | throw new IdentityNotAllowedException(jwtToken.Subject); 179 | } 180 | } 181 | else 182 | { 183 | throw new AuthorizationScopesException("Failed to validate identity because the passed token could not be converted to a valid JwtSecurityToken object"); 184 | } 185 | } 186 | 187 | 188 | private static string GetDisplayNameFromToken(ClaimsPrincipal claimsPrincipal) 189 | { 190 | if (claimsPrincipal.Identity is ClaimsIdentity claimsIdentity) 191 | { 192 | return claimsIdentity.Claims.FirstOrDefault(clm => clm.Type == claimsIdentity.NameClaimType)?.Value; 193 | } 194 | return null; 195 | } 196 | 197 | private static TokenValidationParameters GetTokenValidationParameters(string issuer, string audience, string issuerPattern) 198 | { 199 | var validateIssuer = string.IsNullOrWhiteSpace(issuerPattern); 200 | var validationParameter = new TokenValidationParameters 201 | { 202 | RequireSignedTokens = false, 203 | ValidAudience = audience, 204 | ValidateAudience = !string.IsNullOrWhiteSpace(audience), 205 | ValidIssuer = issuer, 206 | ValidateIssuer = validateIssuer, 207 | ValidateIssuerSigningKey = false, 208 | ValidateLifetime = true 209 | }; 210 | return validationParameter; 211 | } 212 | 213 | 214 | private static SecurityKey GetIssuerSigningKey(JwtBindingConfiguration config) 215 | { 216 | if (!string.IsNullOrWhiteSpace(config.SymmetricSecuritySigningKey)) 217 | { 218 | return new SymmetricSecurityKey(Encoding.ASCII.GetBytes(config.SymmetricSecuritySigningKey)); 219 | } 220 | 221 | if (!string.IsNullOrWhiteSpace(config.X509CertificateSigningKey)) 222 | { 223 | var certificate = new X509Certificate2(Convert.FromBase64String(config.X509CertificateSigningKey)); 224 | var certificateKey = new X509SecurityKey(certificate); 225 | return certificateKey; 226 | } 227 | 228 | return null; 229 | } 230 | 231 | private async Task> RetrieveIssuerSigningKeys(string issuer) 232 | { 233 | if (_securityKeys == null) 234 | { 235 | var addSlashCharacter = issuer.EndsWith("/") ? "" : "/"; 236 | var stsDiscoveryEndpoint = $"{issuer}{addSlashCharacter}.well-known/openid-configuration"; 237 | _logger.LogInformation("Downloading OpenID Configuration from {stsDiscoveryEndpoint}", 238 | stsDiscoveryEndpoint); 239 | var retriever = new OpenIdConnectConfigurationRetriever(); 240 | var configManager = 241 | new ConfigurationManager(stsDiscoveryEndpoint, retriever); 242 | 243 | var config = await configManager 244 | .GetConfigurationAsync() 245 | .ConfigureAwait(false); 246 | 247 | _logger.LogInformation("Found {count} signing keys for token signature", config.SigningKeys.Count); 248 | _securityKeys = config.SigningKeys; 249 | } 250 | 251 | return _securityKeys; 252 | } 253 | 254 | public TokenValidatorService(ILogger logger) 255 | { 256 | _logger = logger; 257 | } 258 | } 259 | } -------------------------------------------------------------------------------- /src/HexMaster.Functions.JwtBinding.Tests/TokenValidator/TokenValidatorServiceTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IdentityModel.Tokens.Jwt; 3 | using System.Linq; 4 | using System.Net.Http.Headers; 5 | using System.Security.Claims; 6 | using System.Security.Cryptography.X509Certificates; 7 | using System.Text; 8 | using HexMaster.Functions.JwtBinding.Configuration; 9 | using HexMaster.Functions.JwtBinding.Exceptions; 10 | using HexMaster.Functions.JwtBinding.Model; 11 | using HexMaster.Functions.JwtBinding.TokenValidator; 12 | using Microsoft.Extensions.Logging; 13 | using Microsoft.IdentityModel.Tokens; 14 | using Moq; 15 | using NUnit.Framework; 16 | 17 | namespace HexMaster.Functions.JwtBinding.Tests.TokenValidator 18 | { 19 | [TestFixture] 20 | public class TokenValidatorServiceTests 21 | { 22 | 23 | private Mock> _loggerMock; 24 | private TokenValidatorService _service; 25 | private string _audience; 26 | private string _issuer; 27 | private string _issuerPattern; 28 | private string _scheme; 29 | private string _token; 30 | private string _subject; 31 | private string _symmetricSigningKey; 32 | private string _givenName; 33 | private string _scopes; 34 | private string _allowedIdentities; 35 | private string _certificateWithPrivateKey; 36 | private string _certificateWithPublicKey; 37 | 38 | [SetUp] 39 | public void Setup() 40 | { 41 | _loggerMock = new Mock>(); 42 | _service = new TokenValidatorService(_loggerMock.Object); 43 | } 44 | 45 | [Test] 46 | public void WhenTokenWithSymmetricSignatureIsValid_ThenItReturnsAuthorizedModel() 47 | { 48 | WithValidJwtToken(); 49 | var model = Validate(); 50 | 51 | Assert.AreEqual(model.Subject, _subject); 52 | Assert.AreEqual(model.Name, _givenName); 53 | AssertExpectedUserClaims(model); 54 | } 55 | 56 | [Test] 57 | public void WhenTokenWithX509CertificateSingingKeyIsValid_ThenItReturnsAuthorizedModel() 58 | { 59 | WithValidX509CertificateSigningKey(); 60 | WithValidJwtToken(); 61 | var model = Validate(); 62 | 63 | Assert.AreEqual(model.Subject, _subject); 64 | Assert.AreEqual(model.Name, _givenName); 65 | AssertExpectedUserClaims(model); 66 | } 67 | 68 | [Test] 69 | public void WhenTokenWithX509CertificateSingingKeyIsInvalid_ThenItThrowsAuthorizationFailedException() 70 | { 71 | WithInvalidX509CertificateSigningKey(); 72 | WithValidJwtToken(); 73 | Assert.Throws(Act); 74 | } 75 | 76 | [Test] 77 | public void WhenTokenSchemeIsInvalid_ThenItThrowsAuthorizationSchemeNotSupportedException() 78 | { 79 | WithValidJwtToken(); 80 | WithInvalidScheme(); 81 | Assert.Throws(Act); 82 | } 83 | 84 | [Test] 85 | public void WhenTokenWithSymmetricSignatureIsInvalid_ThenItThrowsAuthorizationFailedException() 86 | { 87 | WithValidJwtToken(); 88 | WithInvalidSignature(); 89 | Assert.Throws(Act); 90 | } 91 | 92 | [Test] 93 | public void WhenTokenIssuerIsInvalid_ThenItThrowsAuthorizationFailedException() 94 | { 95 | WithValidJwtToken(); 96 | WithInvalidIssuer(); 97 | WithoutIssuerPattern(); 98 | Assert.Throws(Act); 99 | } 100 | 101 | [Test] 102 | public void WhenTokenIssuerIsNull_ThenItThrowsConfigurationException() 103 | { 104 | WithValidJwtToken(); 105 | WithEmptyIssuer(); 106 | Assert.Throws(Act); 107 | } 108 | 109 | [Test] 110 | public void WhenTokenAudienceIsInvalid_ThenItThrowsAuthorizationFailedException() 111 | { 112 | WithValidJwtToken(); 113 | WithInvalidAudience(); 114 | Assert.Throws(Act); 115 | } 116 | 117 | [Test] 118 | public void WhenTokenScopeIsInvalid_ThenItThrowsAuthorizationFailedException() 119 | { 120 | WithValidJwtToken(); 121 | WithInvalidScopes(); 122 | Assert.Throws(Act); 123 | } 124 | 125 | [Test] 126 | public void WhenAllowedIdenityIsInvalid_ThenItReturnsAuthorizedModel() 127 | { 128 | WithValidJwtToken(); 129 | WithoutAllowedIdentitiesSpecified(); 130 | var model = Validate(); 131 | Assert.AreEqual(model.Subject, _subject); 132 | Assert.AreEqual(model.Name, _givenName); 133 | AssertExpectedUserClaims(model); 134 | } 135 | 136 | [Test] 137 | public void WhenMultipleAllowedIdentitiesSpecified_ThenItReturnsAuthorizedModel() 138 | { 139 | WithValidJwtToken(); 140 | WithAllowedIdentitiesSpecifiedMatchingTheSubject(); 141 | var model = Validate(); 142 | Assert.AreEqual(model.Subject, _subject); 143 | Assert.AreEqual(model.Name, _givenName); 144 | AssertExpectedUserClaims(model); 145 | } 146 | 147 | [Test] 148 | public void WhenAllowedIdentitiesSpecifiedMatchingTheSubject_ThenItReturnsAuthorizedModel() 149 | { 150 | WithValidJwtToken(); 151 | WithAllowedIdentitiesSpecifiedMatchingTheSubject(); 152 | var model = Validate(); 153 | Assert.AreEqual(model.Subject, _subject); 154 | Assert.AreEqual(model.Name, _givenName); 155 | AssertExpectedUserClaims(model); 156 | } 157 | 158 | [Test] 159 | public void WhenMultipleAllowedIdentitiesSpecifiedAndNoneAreInTheToken_ThenItThrowsAuthorizationFailedException() 160 | { 161 | WithValidJwtToken(); 162 | WithMultipleAllowedIdentitiesSpecifiedAndNoneAreInTheSubject(); 163 | var ex = Assert.Throws(Act); 164 | Assert.That(ex.InnerException.GetType(), Is.EqualTo(typeof(IdentityNotAllowedException))); 165 | } 166 | 167 | [Test] 168 | public void WhenInvalidIssuerButValidIssuerPatternInTheToken_ThenItReturnsAuthorizedModel() 169 | { 170 | WithValidJwtToken(); 171 | var tokenIssuer = _issuer; 172 | WithInvalidIssuer(); 173 | WithValidIssuerPattern(); 174 | var model = Validate(); 175 | Assert.AreEqual(model.Subject, _subject); 176 | Assert.AreEqual(model.Name, _givenName); 177 | AssertExpectedUserClaims(model, expectedIssuer: tokenIssuer); 178 | } 179 | [Test] 180 | public void WhenInvalidIssuerAndInvalidIssuerPatternInTheToken_ThenItThrowsAuthorizationFailedException() 181 | { 182 | WithValidJwtToken(); 183 | WithInvalidIssuerPattern(); 184 | var ex = Assert.Throws(Act); 185 | Assert.That(ex.InnerException.GetType(), Is.EqualTo(typeof(IssuerPatternValidationException))); 186 | } 187 | 188 | private void WithInvalidScheme() 189 | { 190 | _scheme = "Invalid"; 191 | } 192 | 193 | private void WithInvalidSignature() 194 | { 195 | _symmetricSigningKey = Guid.NewGuid().ToString(); 196 | } 197 | 198 | private void WithInvalidIssuer() 199 | { 200 | _issuer = "https://my-random-issuer.com"; 201 | } 202 | 203 | private void WithEmptyIssuer() 204 | { 205 | _issuer = null; 206 | } 207 | 208 | private void WithInvalidAudience() 209 | { 210 | _audience = "invalid-audience"; 211 | } 212 | 213 | private void WithInvalidScopes() 214 | { 215 | _scopes = "nothing:nothing"; 216 | } 217 | 218 | private void WithoutIssuerPattern() 219 | { 220 | _issuerPattern = string.Empty; 221 | } 222 | private void WithValidIssuerPattern() 223 | { 224 | _issuerPattern = "https://my.*"; 225 | } 226 | private void WithInvalidIssuerPattern() 227 | { 228 | _issuerPattern = "eduard"; 229 | } 230 | 231 | private void WithoutAllowedIdentitiesSpecified() 232 | { 233 | _allowedIdentities = null; 234 | } 235 | private void WithAllowedIdentitiesSpecifiedMatchingTheSubject() 236 | { 237 | _allowedIdentities = _subject; 238 | } 239 | private void WithMultipleAllowedIdentitiesSpecified() 240 | { 241 | _allowedIdentities = $"Some,More,{_subject},Identities"; 242 | } 243 | 244 | private void WithMultipleAllowedIdentitiesSpecifiedAndNoneAreInTheSubject() 245 | { 246 | _allowedIdentities = $"Some,More,Identities"; 247 | } 248 | 249 | private void WithValidX509CertificateSigningKey() 250 | { 251 | _certificateWithPrivateKey = @"MIINugIBAzCCDXYGCSqGSIb3DQEHAaCCDWcEgg1jMIINXzCCBgAGCSqGSIb3DQEHAaCCBfEEggXtMIIF6TCCBeUGCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAjv464XE0Z4nAICB9AEggTYKFKZSgNvHodiWQcf07Ly0F0TodeHD8UgBnokwIGtwUKUafzeF9xFoC3IyP+NQv88lC16gRMpuUbjoW7BwMyajdWweShlHN8eGFWWeh9EztbcOnMZEu1SGe022LMasfP9MVE1+PqY+XoHiP4GQo2+79wxtjABFno/z68sMcoDOSGyGuZ4KV4jMh/S7Uj4YjuyfzfYJRL0uAuuq9IUo9+1psCZpIdrr8vjKImyqz6XMNlbabcdHPYxatfNZooQFMuWp5CtBPgELalwY9sgU4je/pVIGkeb0D/jVfGig3FY0Qprcm0GelkhKNT1sQvYsFfJ1/37qDaF+PApxbDTxMOYzn99lwpKNVreHX+b5ZxPiIE8jebYJzv03kfxEPd+JqSwLpcwgDW8IOwh4tVxN2baR+v5mV3yWPzImpC3Wfz4OxBy4sDlcgsHhVlfvPn5iIV1mNOrOcbEea6J0QYWBfl0wl5NedsERon/WD8PQjdEZXkiiWYncJ1DQQtnKE+OTjkQ/H0eS4gEq6sjB/++gACscTrnDmFX36tM8kTbzRa9I3Ip9HY5SlvE5cYNNUdfkRV1+QZI2Ht0ow97GmuZOQg6eoUwjOPWu59m0tYu28Sram4ilvHVjbrw7LUgsIy/4w9S6l7SAxgvPtTrsbNrXRM2zIFLtRMPDf7Zpddp6jkKiBU9oiJYbZdoIRj180amdHOllFy50TBgzi1VH1jtffuUoRlrqMdaUX1mKK4mzf0YmKLLiVXk+k8vumv1ZYFO7MKCwscpEtx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H/BAQDAgWgMB0GA1UdJQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDATATBgNVHREEDDAKggh0ZXN0LmNvbTAfBgNVHSMEGDAWgBSssX5m9KOicRcEr0xpkbiS2b/cITAdBgNVHQ4EFgQUe6sY+2e7cL2m2DnWlmpg/Meyp4cwDQYJKoZIhvcNAQEFBQADggEBAJYBybo/AHyqjuPnQfp8nPRLzMHwwu7iUDDtVrw0VH9dk473UaaCd5JNBBh1FDvgkS/CSYIY2MBIejcHEq2rGAuTuOJnsRWDPipdmReo+KK/feubu78JUofCoWcKTnhO7nMe1rtOIOSSa/LR2mtRliMVa7wSxPXUQv363LKCfMJxNVj5FxoxMDYwzhMBsoagnE03EbkYAJKb1jHqSSoto19PYVMl+y5XPlcomI/P5D50hp2cI4ulYafvQ4rETF9SKSwaeOopK5RiqSvu2fVEfXfaOM0MXS8vyJwHDTeOcwBWIB7gyUl0l9wVTYjlTTajz+RyI8LZVYSVcdmsgHb3S1A="; 253 | } 254 | 255 | private void WithInvalidX509CertificateSigningKey() 256 | { 257 | _certificateWithPrivateKey = @"MIINugIBAzCCDXYGCSqGSIb3DQEHAaCCDWcEgg1jMIINXzCCBgAGCSqGSIb3DQEHAaCCBfEEggXtMIIF6TCCBeUGCyqGSIb3DQEMCgECoIIE/jCCBPowHAYKKoZIhvcNAQwBAzAOBAjv464XE0Z4nAICB9AEggTYKFKZSgNvHodiWQcf07Ly0F0TodeHD8UgBnokwIGtwUKUafzeF9xFoC3IyP+NQv88lC16gRMpuUbjoW7BwMyajdWweShlHN8eGFWWeh9EztbcOnMZEu1SGe022LMasfP9MVE1+PqY+XoHiP4GQo2+79wxtjABFno/z68sMcoDOSGyGuZ4KV4jMh/S7Uj4YjuyfzfYJRL0uAuuq9IUo9+1psCZpIdrr8vjKImyqz6XMNlbabcdHPYxatfNZooQFMuWp5CtBPgELalwY9sgU4je/pVIGkeb0D/jVfGig3FY0Qprcm0GelkhKNT1sQvYsFfJ1/37qDaF+PApxbDTx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FVJSzktyrVC34j70cMYSqY4ev5A+fs2zgGp/4cMDcwHzAHBgUrDgMCGgQUUG+ZhmoN/MaNkyP3EWNX81zZoQQEFAuZPgiZ8hZN0m3+o4CLhQk4Uu6R"; 259 | } 260 | 261 | private void WithValidJwtToken() 262 | { 263 | _audience = "my-valid-audience"; 264 | _issuer = "https://my-valid-issuer"; 265 | _scheme = "Bearer"; 266 | _subject = $"{DateTime.UtcNow.Ticks}"; 267 | _givenName = "Tommy Token"; 268 | _symmetricSigningKey = Guid.NewGuid().ToString(); 269 | _scopes = "something:create,other:list"; 270 | _allowedIdentities = ""; 271 | _token = CreateJwtToken(); 272 | } 273 | 274 | private string CreateJwtToken() 275 | { 276 | var tokenHandler = new JwtSecurityTokenHandler(); 277 | 278 | // Create JWToken 279 | var signingCredentials = string.IsNullOrWhiteSpace(_certificateWithPrivateKey) 280 | ? new SigningCredentials(new SymmetricSecurityKey(Encoding.Default.GetBytes(_symmetricSigningKey)), 281 | SecurityAlgorithms.HmacSha256Signature) 282 | : new SigningCredentials(new X509SecurityKey(new X509Certificate2(Convert.FromBase64String(_certificateWithPrivateKey), "SelfSigned_Test")), SecurityAlgorithms.RsaSha256Signature); 283 | 284 | var token = tokenHandler.CreateJwtSecurityToken( 285 | _issuer, 286 | _audience, 287 | CreateClaimsIdentities(), 288 | DateTime.UtcNow, 289 | DateTime.UtcNow.AddDays(1), 290 | signingCredentials: signingCredentials); 291 | 292 | return tokenHandler.WriteToken(token); 293 | } 294 | 295 | private ClaimsIdentity CreateClaimsIdentities() 296 | { 297 | var claimsIdentity = new ClaimsIdentity(); 298 | claimsIdentity.AddClaim(new Claim(JwtRegisteredClaimNames.NameId, _subject)); 299 | claimsIdentity.AddClaim(new Claim(JwtRegisteredClaimNames.GivenName, _givenName)); 300 | 301 | foreach (var scope in _scopes.Split(',')) 302 | { 303 | claimsIdentity.AddClaim(new Claim("scp", scope)); 304 | } 305 | 306 | return claimsIdentity; 307 | } 308 | 309 | 310 | private void Act() 311 | { 312 | var config = new JwtBindingConfiguration 313 | { 314 | SymmetricSecuritySigningKey = _symmetricSigningKey, 315 | Scopes = _scopes, 316 | Audience = _audience, 317 | Issuer = _issuer, 318 | IssuerPattern = _issuerPattern, 319 | AllowedIdentities = _allowedIdentities 320 | }; 321 | _service.ValidateToken( 322 | new AuthenticationHeaderValue(_scheme, _token), 323 | config); 324 | } 325 | 326 | private AuthorizedModel Validate() 327 | { 328 | var config = new JwtBindingConfiguration 329 | { 330 | Scopes = _scopes, 331 | Audience = _audience, 332 | Issuer = _issuer, 333 | IssuerPattern = _issuerPattern 334 | }; 335 | 336 | if (!string.IsNullOrWhiteSpace(_certificateWithPrivateKey)) 337 | { 338 | config.X509CertificateSigningKey = _certificateWithPublicKey; 339 | } 340 | else 341 | { 342 | config.SymmetricSecuritySigningKey = _symmetricSigningKey; 343 | } 344 | 345 | return _service.ValidateToken( 346 | new AuthenticationHeaderValue(_scheme, _token), 347 | config); 348 | } 349 | 350 | private void AssertExpectedUserClaims( 351 | AuthorizedModel model, 352 | string expectedIssuer = null, 353 | string expectedAudience = null, 354 | string expectedSubject = null, 355 | string expectedGivenName = null, 356 | string expectedScopes = null) 357 | { 358 | Assert.IsTrue(model.User.Identity.IsAuthenticated); 359 | Assert.AreEqual(model.User.FindFirst(JwtRegisteredClaimNames.Iss)?.Value, expectedIssuer ?? _issuer); 360 | Assert.AreEqual(model.User.FindFirst(JwtRegisteredClaimNames.Aud)?.Value, expectedAudience ?? _audience); 361 | Assert.AreEqual(model.User.FindFirst(JwtRegisteredClaimNames.NameId)?.Value, expectedSubject ?? _subject); 362 | Assert.AreEqual(model.User.FindFirst(JwtRegisteredClaimNames.GivenName)?.Value, expectedGivenName ?? _givenName); 363 | var scopeClaims = model.User.FindAll("scp"); 364 | foreach (var expectedScope in (expectedScopes ?? _scopes).Split(',')) 365 | { 366 | Assert.IsTrue(scopeClaims.Any(claim => claim.Value == expectedScope)); 367 | } 368 | } 369 | } 370 | } --------------------------------------------------------------------------------