├── .assets
└── icon.png
├── .build
└── release.props
├── .editorconfig
├── .gitignore
├── ChangeLog.md
├── Functions-Authorize.sln
├── LICENSE
├── NuGet.Config
├── README.md
├── sample
├── SampleInProcFunctions.V4
│ ├── .gitignore
│ ├── HelperFunctions.cs
│ ├── Properties
│ │ ├── serviceDependencies.json
│ │ └── serviceDependencies.local.json
│ ├── SampleInProcFunctions.V4.csproj
│ ├── Startup.cs
│ ├── TestFunction.cs
│ └── host.json
├── SampleIsolatedFunctions.V4
│ ├── .gitignore
│ ├── HelperFunctions.cs
│ ├── Program.cs
│ ├── Properties
│ │ ├── serviceDependencies.json
│ │ └── serviceDependencies.local.json
│ ├── SampleIsolatedFunctions.V4.csproj
│ ├── TestFunction.cs
│ └── host.json
└── SampleIsolatedFunctionsFSharp.V4
│ ├── .vscode
│ └── extensions.json
│ ├── HelperFunctions.fs
│ ├── Program.fs
│ ├── Properties
│ ├── serviceDependencies.json
│ └── serviceDependencies.local.json
│ ├── SampleIsolatedFunctionsFSharp_V4.fsproj
│ ├── TestFunction.fs
│ ├── host.json
│ └── local.settings.json
├── src
├── abstractions
│ ├── Cache
│ │ ├── FunctionsAuthorizationFilterCache.cs
│ │ └── IFunctionsAuthorizationFilterCache.cs
│ ├── Constants.cs
│ ├── DarkLoop.Azure.Functions.Authorization.Abstractions.csproj
│ ├── EmptySchemeStrategy.cs
│ ├── FunctionAuthorizationContext.cs
│ ├── FunctionAuthorizationFeature.cs
│ ├── FunctionAuthorizationFilter.cs
│ ├── FunctionAuthorizationMetadata.cs
│ ├── FunctionAuthorizationMetadataCollection.cs
│ ├── FunctionAuthorizationTypeMap.cs
│ ├── FunctionsAuthenticationBuilder.cs
│ ├── FunctionsAuthenticationBuilderExtensions.cs
│ ├── FunctionsAuthorizationBuilder.cs
│ ├── FunctionsAuthorizationCoreServiceCollectionExtensions.cs
│ ├── FunctionsAuthorizationOptions.cs
│ ├── FunctionsAuthorizationProvider.cs
│ ├── FunctionsAuthorizationResultHandler.cs
│ ├── IFunctionsAuthorizationProvider.cs
│ ├── IFunctionsAuthorizationResultHandler.cs
│ ├── Internal
│ │ ├── Check.cs
│ │ ├── FunctionsAuthorizationOptionsExtensions.cs
│ │ ├── FunctionsFeatureCollectionExtension.cs
│ │ └── KeyedMonitor.cs
│ ├── JwtFunctionsBearerDefaults.cs
│ ├── Properties
│ │ ├── Messages.Designer.cs
│ │ └── Messages.resx
│ ├── README.md
│ └── Security
│ │ └── AuthorizationBuilderExtensions.cs
├── in-proc
│ ├── .gitignore
│ ├── Bindings
│ │ └── FunctionsAuthorizeBindingProvider.cs
│ ├── DarkLoop.Azure.Functions.Authorization.InProcess.csproj
│ ├── FunctionAuthorizationContextInternal.cs
│ ├── FunctionAuthorizationException.cs
│ ├── FunctionAuthorizeAttribute.cs
│ ├── FunctionExecutingContextExtensions.cs
│ ├── FunctionsAuthExtension.cs
│ ├── FunctionsAuthorizationExecutor.cs
│ ├── FunctionsAuthorizationHostBuilderExtensions.cs
│ ├── FunctionsAuthorizeStartup.cs
│ ├── IFunctionsAuthorizationExecutor.cs
│ ├── Properties
│ │ ├── Strings.Designer.cs
│ │ ├── Strings.resx
│ │ ├── serviceDependencies.json
│ │ └── serviceDependencies.local.json
│ ├── README.md
│ ├── Security
│ │ ├── FunctionsAuthenticationBuilderExtensions.cs
│ │ ├── FunctionsAuthenticationServiceCollectionExtensions.cs
│ │ └── FunctionsAuthorizationServiceCollectionExtensions.cs
│ └── Utils
│ │ └── HostUtils.cs
└── isolated
│ ├── DarkLoop.Azure.Functions.Authorization.Isolated.csproj
│ ├── Extensions
│ └── FunctionContextExtensions.cs
│ ├── Features
│ ├── FunctionsAuthorizationFeature.cs
│ └── IFunctionsAuthorizationFeature.cs
│ ├── FunctionAuthorizeAttribute.cs
│ ├── FunctionsAuthorizationExtensionStartup.cs
│ ├── FunctionsAuthorizationMiddleware.cs
│ ├── FunctionsAuthorizationServiceCollectionExtensions.cs
│ ├── FunctionsAuthorizationWorkerAppBuilderExtensions.cs
│ ├── Metadata
│ └── FunctionsAuthorizationMetadataMiddleware.cs
│ ├── Properties
│ ├── IsolatedMessages.Designer.cs
│ └── IsolatedMessages.resx
│ └── README.md
└── test
├── Abstractions.Tests
├── Abstractions.Tests.csproj
├── Fakes
│ └── AuthorizeDataFake.cs
├── FunctionAuthorizationMetadataCollectionTests.cs
├── FunctionAuthorizationMetadataTests.cs
├── FunctionAuthorizationTypeMapTests.cs
├── FunctionsAuthorizationFilterCacheTests.cs
├── FunctionsAuthorizationProviderTests.cs
├── FunctionsAuthorizationResultHandlerTests.cs
├── Internal
│ └── KeyedMonitorTests.cs
└── Usings.cs
├── Common.Tests
├── Common.Tests.csproj
├── HttpUtils.cs
├── JwtUtils.cs
├── LoggerUtils.cs
└── TestTokenValidator.cs
├── InProc.Tests
├── FunctionsAuthorizationExecutorTests.cs
├── GlobalUsings.cs
└── InProc.Tests.csproj
└── Isolated.Tests
├── ConcurrentTests.cs
├── Fakes
├── FakeFunctionClass.cs
└── FakeInvocationFeatures.cs
├── Features
└── FunctionsAuthorizationFeatureTests.cs
├── FunctionContextExtensionsTests.cs
├── FunctionsAuthorizationMiddlewareTests.cs
├── GlobalUsings.cs
├── Isolated.Tests.csproj
└── Metadata
└── FunctionsAuthorizationMetadataMiddlewareTests.cs
/.assets/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dark-loop/functions-authorize/6d3e390231c1778c037b4ce71c68273c607684e9/.assets/icon.png
--------------------------------------------------------------------------------
/.build/release.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | $(AssmeblyName)
5 | DarkLoop
6 | DarkLoop
7 | DarkLoop - All rights reserved
8 | DarkLoop's Azure Functions Authorization
9 | false
10 | 4.0.0.0
11 | 4.2.0
12 | $(Version).0
13 | https://github.com/dark-loop/functions-authorize
14 | https://github.com/dark-loop/functions-authorize/blob/master/LICENSE
15 | Git
16 | AuthorizeAttribute, Authorize, Azure Functions, Azure, Bearer, JWT, Policy based authorization
17 | icons/icon.png
18 | https://en.gravatar.com/userimage/22176525/45f25acea686a783e5b2ca172d72db71.png
19 | true
20 | ../dl-sftwr-sn-key.snk
21 | 0024000004800000940000000602000000240000525341310004000001000100791e7f618a12452d7ced5310f6203d0d227f9d26b146555e7e67a1801695dcf7c552421620a662f54b072f7be1efa885c074d4b9c76a4d6d154721d1c3b1f39164cfaf9ebdf9b7672ff320c89c5a64c90e25330f90a12bf42a1c57b70523e785167dbbfb7a0fdc9eb8d15112f758b89bab51953b08cfb2218095bc45171c99c5
22 | true
23 | true
24 | README.md
25 |
26 |
27 |
28 | $(BuildNumber.Substring($([MSBuild]::Add($(BuildNumber.LastIndexOf('.')), 1))))
29 | $([System.DateTime]::Now.ToString('yyMMdd'))
30 | $(DateNumber)-$(Revision)
31 | -preview-$(BuildIDNumber)
32 | $(Version)$(PreviewVersion)
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | [*.cs]
2 |
3 | file_header_template = \n Copyright (c) DarkLoop. All rights reserved.\n
4 |
5 | # CS0618: Type or member is obsolete
6 | dotnet_diagnostic.CS0618.severity = silent
7 |
--------------------------------------------------------------------------------
/NuGet.Config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # functions-authorize
2 | Extension bringing AuthorizeAttribute Behavior to Azure Functions In-Proc and Isolated mode. For the latter is only available with ASPNET Core integration.
3 |
4 | It hooks into .NET Core dependency injection container to enable authentication and authorization in the same way ASP.NET Core does.
5 |
6 | > **Breaking for current package consumers**
7 | > Starting with version 4.1.0, due to security changes made on the Functions runtime, the Bearer scheme is no longer supported for your app functions.
8 | > Use `AddJwtFunctionsBearer(Action)` instead of `AddJwtBearer(Action)` when setting up authentication.
9 | Using `AddJwtBearer` will generate a compilation error when used against `FunctionsAuthenticationBuilder`.
10 | We are introducing `JwtFunctionsBearerDefaults` to refer to the suggested new custom scheme name.
11 | No changes should be required if already using a custom scheme name.
12 | > Refer to respective README documentation for isolated and in-process for more information.
13 |
14 | ## Getting Started
15 | - [Azure Functions V3+ In-Proc mode](./src/in-proc/README.md)
16 | - [Azure Functions V4 Isolated mode with ASPNET Core integration](./src/isolated/README.md)
17 |
18 | ## License
19 | This projects is open source and may be redistributed under the terms of the [Apache 2.0](http://opensource.org/licenses/Apache-2.0) license.
20 |
21 | ## Package Status
22 | ### Releases
23 | [](https://www.nuget.org/packages/DarkLoop.Azure.Functions.Authorization.Abstractions)
24 |
25 | ### Builds
26 | 
27 |
28 | ## Change Log
29 | You can access the change log [here](https://github.com/dark-loop/functions-authorize/blob/master/ChangeLog.md).
--------------------------------------------------------------------------------
/sample/SampleInProcFunctions.V4/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # Azure Functions localsettings file
5 | local.settings.json
6 |
7 | # User-specific files
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Build results
17 | [Dd]ebug/
18 | [Dd]ebugPublic/
19 | [Rr]elease/
20 | [Rr]eleases/
21 | x64/
22 | x86/
23 | bld/
24 | [Bb]in/
25 | [Oo]bj/
26 | [Ll]og/
27 |
28 | # Visual Studio 2015 cache/options directory
29 | .vs/
30 | # Uncomment if you have tasks that create the project's static files in wwwroot
31 | #wwwroot/
32 |
33 | # MSTest test Results
34 | [Tt]est[Rr]esult*/
35 | [Bb]uild[Ll]og.*
36 |
37 | # NUNIT
38 | *.VisualState.xml
39 | TestResult.xml
40 |
41 | # Build Results of an ATL Project
42 | [Dd]ebugPS/
43 | [Rr]eleasePS/
44 | dlldata.c
45 |
46 | # DNX
47 | project.lock.json
48 | project.fragment.lock.json
49 | artifacts/
50 |
51 | *_i.c
52 | *_p.c
53 | *_i.h
54 | *.ilk
55 | *.meta
56 | *.obj
57 | *.pch
58 | *.pdb
59 | *.pgc
60 | *.pgd
61 | *.rsp
62 | *.sbr
63 | *.tlb
64 | *.tli
65 | *.tlh
66 | *.tmp
67 | *.tmp_proj
68 | *.log
69 | *.vspscc
70 | *.vssscc
71 | .builds
72 | *.pidb
73 | *.svclog
74 | *.scc
75 |
76 | # Chutzpah Test files
77 | _Chutzpah*
78 |
79 | # Visual C++ cache files
80 | ipch/
81 | *.aps
82 | *.ncb
83 | *.opendb
84 | *.opensdf
85 | *.sdf
86 | *.cachefile
87 | *.VC.db
88 | *.VC.VC.opendb
89 |
90 | # Visual Studio profiler
91 | *.psess
92 | *.vsp
93 | *.vspx
94 | *.sap
95 |
96 | # TFS 2012 Local Workspace
97 | $tf/
98 |
99 | # Guidance Automation Toolkit
100 | *.gpState
101 |
102 | # ReSharper is a .NET coding add-in
103 | _ReSharper*/
104 | *.[Rr]e[Ss]harper
105 | *.DotSettings.user
106 |
107 | # JustCode is a .NET coding add-in
108 | .JustCode
109 |
110 | # TeamCity is a build add-in
111 | _TeamCity*
112 |
113 | # DotCover is a Code Coverage Tool
114 | *.dotCover
115 |
116 | # NCrunch
117 | _NCrunch_*
118 | .*crunch*.local.xml
119 | nCrunchTemp_*
120 |
121 | # MightyMoose
122 | *.mm.*
123 | AutoTest.Net/
124 |
125 | # Web workbench (sass)
126 | .sass-cache/
127 |
128 | # Installshield output folder
129 | [Ee]xpress/
130 |
131 | # DocProject is a documentation generator add-in
132 | DocProject/buildhelp/
133 | DocProject/Help/*.HxT
134 | DocProject/Help/*.HxC
135 | DocProject/Help/*.hhc
136 | DocProject/Help/*.hhk
137 | DocProject/Help/*.hhp
138 | DocProject/Help/Html2
139 | DocProject/Help/html
140 |
141 | # Click-Once directory
142 | publish/
143 |
144 | # Publish Web Output
145 | *.[Pp]ublish.xml
146 | *.azurePubxml
147 | # TODO: Comment the next line if you want to checkin your web deploy settings
148 | # but database connection strings (with potential passwords) will be unencrypted
149 | #*.pubxml
150 | *.publishproj
151 |
152 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
153 | # checkin your Azure Web App publish settings, but sensitive information contained
154 | # in these scripts will be unencrypted
155 | PublishScripts/
156 |
157 | # NuGet Packages
158 | *.nupkg
159 | # The packages folder can be ignored because of Package Restore
160 | **/packages/*
161 | # except build/, which is used as an MSBuild target.
162 | !**/packages/build/
163 | # Uncomment if necessary however generally it will be regenerated when needed
164 | #!**/packages/repositories.config
165 | # NuGet v3's project.json files produces more ignoreable files
166 | *.nuget.props
167 | *.nuget.targets
168 |
169 | # Microsoft Azure Build Output
170 | csx/
171 | *.build.csdef
172 |
173 | # Microsoft Azure Emulator
174 | ecf/
175 | rcf/
176 |
177 | # Windows Store app package directories and files
178 | AppPackages/
179 | BundleArtifacts/
180 | Package.StoreAssociation.xml
181 | _pkginfo.txt
182 |
183 | # Visual Studio cache files
184 | # files ending in .cache can be ignored
185 | *.[Cc]ache
186 | # but keep track of directories ending in .cache
187 | !*.[Cc]ache/
188 |
189 | # Others
190 | ClientBin/
191 | ~$*
192 | *~
193 | *.dbmdl
194 | *.dbproj.schemaview
195 | *.jfm
196 | *.pfx
197 | *.publishsettings
198 | node_modules/
199 | orleans.codegen.cs
200 |
201 | # Since there are multiple workflows, uncomment next line to ignore bower_components
202 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
203 | #bower_components/
204 |
205 | # RIA/Silverlight projects
206 | Generated_Code/
207 |
208 | # Backup & report files from converting an old project file
209 | # to a newer Visual Studio version. Backup files are not needed,
210 | # because we have git ;-)
211 | _UpgradeReport_Files/
212 | Backup*/
213 | UpgradeLog*.XML
214 | UpgradeLog*.htm
215 |
216 | # SQL Server files
217 | *.mdf
218 | *.ldf
219 |
220 | # Business Intelligence projects
221 | *.rdl.data
222 | *.bim.layout
223 | *.bim_*.settings
224 |
225 | # Microsoft Fakes
226 | FakesAssemblies/
227 |
228 | # GhostDoc plugin setting file
229 | *.GhostDoc.xml
230 |
231 | # Node.js Tools for Visual Studio
232 | .ntvs_analysis.dat
233 |
234 | # Visual Studio 6 build log
235 | *.plg
236 |
237 | # Visual Studio 6 workspace options file
238 | *.opt
239 |
240 | # Visual Studio LightSwitch build output
241 | **/*.HTMLClient/GeneratedArtifacts
242 | **/*.DesktopClient/GeneratedArtifacts
243 | **/*.DesktopClient/ModelManifest.xml
244 | **/*.Server/GeneratedArtifacts
245 | **/*.Server/ModelManifest.xml
246 | _Pvt_Extensions
247 |
248 | # Paket dependency manager
249 | .paket/paket.exe
250 | paket-files/
251 |
252 | # FAKE - F# Make
253 | .fake/
254 |
255 | # JetBrains Rider
256 | .idea/
257 | *.sln.iml
258 |
259 | # CodeRush
260 | .cr/
261 |
262 | # Python Tools for Visual Studio (PTVS)
263 | __pycache__/
264 | *.pyc
--------------------------------------------------------------------------------
/sample/SampleInProcFunctions.V4/HelperFunctions.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using System;
6 | using System.Security.Claims;
7 | using System.Threading.Tasks;
8 | using Common.Tests;
9 | using Microsoft.AspNetCore.Http;
10 | using Microsoft.AspNetCore.Mvc;
11 | using Microsoft.Azure.WebJobs;
12 | using Microsoft.Azure.WebJobs.Extensions.Http;
13 | using Microsoft.Extensions.Logging;
14 |
15 | namespace SampleInProcFunctions.V4
16 | {
17 | public static class HelperFunctions
18 | {
19 | [FunctionName("GetTestToken")]
20 | public static async Task Run(
21 | [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
22 | ILogger log)
23 | {
24 | var firstName = "Test";
25 | var lastName = "User";
26 | var email = "test.user@domain.com";
27 | var token = JwtUtils.GenerateJwtToken(new[] {
28 | new Claim("aud", "api://default"),
29 | new Claim("iss", "https://localhost/jwt/"),
30 | new Claim("scp", "user_impersonation"),
31 | new Claim("tid", Guid.NewGuid().ToString()),
32 | new Claim("oid", Guid.NewGuid().ToString()),
33 | new Claim("name", $"{firstName} {lastName}"),
34 | new Claim(ClaimTypes.Name, email),
35 | new Claim(ClaimTypes.Upn, email),
36 | new Claim(ClaimTypes.Email, email),
37 | new Claim(ClaimTypes.GivenName, firstName),
38 | new Claim(ClaimTypes.Surname, lastName),
39 | new Claim("role", "Just a user"),
40 | new Claim("role", "another user"),
41 | });
42 |
43 | return await Task.FromResult(new OkObjectResult(token));
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/sample/SampleInProcFunctions.V4/Properties/serviceDependencies.json:
--------------------------------------------------------------------------------
1 | {
2 | "dependencies": {
3 | "appInsights1": {
4 | "type": "appInsights"
5 | },
6 | "storage1": {
7 | "type": "storage",
8 | "connectionId": "AzureWebJobsStorage"
9 | }
10 | }
11 | }
--------------------------------------------------------------------------------
/sample/SampleInProcFunctions.V4/Properties/serviceDependencies.local.json:
--------------------------------------------------------------------------------
1 | {
2 | "dependencies": {
3 | "appInsights1": {
4 | "type": "appInsights.sdk"
5 | },
6 | "storage1": {
7 | "type": "storage.emulator",
8 | "connectionId": "AzureWebJobsStorage"
9 | }
10 | }
11 | }
--------------------------------------------------------------------------------
/sample/SampleInProcFunctions.V4/SampleInProcFunctions.V4.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net8.0
4 | v4
5 | 51dc0b9d-8e74-45ec-aebc-1d3d6934faf5
6 | false
7 |
8 |
9 |
10 | <_FunctionsSkipCleanOutput>true
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 | PreserveNewest
32 |
33 |
34 | PreserveNewest
35 | Never
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/sample/SampleInProcFunctions.V4/Startup.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using Common.Tests;
6 | using DarkLoop.Azure.Functions.Authorization;
7 | using DarkLoop.Azure.Functions.Authorize.SampleFunctions.V4;
8 | using Microsoft.AspNetCore.Authentication.JwtBearer;
9 | using Microsoft.Azure.Functions.Extensions.DependencyInjection;
10 | using Microsoft.Extensions.Configuration;
11 | using Microsoft.Extensions.DependencyInjection;
12 | using Microsoft.IdentityModel.Tokens;
13 |
14 | [assembly: FunctionsStartup(typeof(Startup))]
15 |
16 | namespace DarkLoop.Azure.Functions.Authorize.SampleFunctions.V4
17 | {
18 | class Startup : FunctionsStartup
19 | {
20 | public IConfigurationRoot Configuration { get; private set; }
21 |
22 | public override void Configure(IFunctionsHostBuilder builder)
23 | {
24 | builder.Services
25 | .AddFunctionsAuthentication(options =>
26 | {
27 | options.DefaultScheme = JwtFunctionsBearerDefaults.AuthenticationScheme;
28 | options.DefaultAuthenticateScheme = JwtFunctionsBearerDefaults.AuthenticationScheme;
29 | options.DefaultChallengeScheme = JwtFunctionsBearerDefaults.AuthenticationScheme;
30 | })
31 | .AddJwtFunctionsBearer(options =>
32 | {
33 | // this line is here to bypass the token validation
34 | // and test the functionality of this library.
35 | // you can create a dummy token by executing the GetTestToken function in HelperFunctions.cs
36 | // THE FOLLOWING LINE SHOULD BE REMOVED IN A REAL-WORLD SCENARIO
37 | options.SecurityTokenValidators.Add(new TestTokenValidator());
38 |
39 | // this is what you should look for in a real-world scenario
40 | // comment the lines if you cloned this repository and want to test the library
41 | //options.Authority = "https://login.microsoftonline.com/";
42 | //options.Audience = "";
43 | //options.TokenValidationParameters = new TokenValidationParameters
44 | //{
45 | // ValidateIssuer = true,
46 | // ValidateAudience = true,
47 | // ValidateLifetime = true,
48 | // ValidateIssuerSigningKey = true,
49 | //};
50 | });
51 |
52 | builder.Services.AddFunctionsAuthorization(options =>
53 | {
54 | // Add your policies here
55 | });
56 |
57 | // If you want to disable authorization for all functions
58 | // decorated with FunctionAuthorizeAttribute you can add the following configuration.
59 | // If you bind it to configuration, you can modify the setting remotely using
60 | // Azure App Configuration or other configuration providers without the need to restart app.
61 | if (builder.IsLocalAuthorizationContext())
62 | {
63 | builder.Services.Configure(Configuration.GetSection("AuthOptions"));
64 | }
65 | }
66 |
67 | public override void ConfigureAppConfiguration(IFunctionsConfigurationBuilder builder)
68 | {
69 | builder.ConfigurationBuilder.AddUserSecrets(true, reloadOnChange: true);
70 |
71 | Configuration = builder.ConfigurationBuilder.Build();
72 |
73 | base.ConfigureAppConfiguration(builder);
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/sample/SampleInProcFunctions.V4/TestFunction.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using System.Text;
6 | using System.Threading.Tasks;
7 | using Microsoft.AspNetCore.Authentication;
8 | using Microsoft.AspNetCore.Http;
9 | using Microsoft.AspNetCore.Mvc;
10 | using Microsoft.Azure.WebJobs;
11 | using Microsoft.Azure.WebJobs.Extensions.Http;
12 | using Microsoft.Extensions.DependencyInjection;
13 | using Microsoft.Extensions.Logging;
14 |
15 | namespace DarkLoop.Azure.Functions.Authorize.SampleFunctions.V4
16 | {
17 | public static class TestFunction
18 | {
19 | [FunctionName("TestFunction")]
20 | [FunctionAuthorize]
21 | public static async Task Run(
22 | [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
23 | ILogger log)
24 | {
25 | log.LogInformation("C# HTTP trigger function processed a request.");
26 |
27 | var provider = req.HttpContext.RequestServices;
28 | var schProvider = provider.GetService();
29 |
30 | var sb = new StringBuilder();
31 | sb.AppendLine("Authentication schemes:");
32 |
33 | if (schProvider is not null)
34 | {
35 | foreach (var scheme in await schProvider.GetAllSchemesAsync())
36 | sb.AppendLine($" {scheme.Name} -> {scheme.HandlerType}");
37 | }
38 |
39 | sb.AppendLine();
40 | sb.AppendLine($"User:");
41 | sb.AppendLine($" Name -> {req.HttpContext.User.Identity!.Name}");
42 | sb.AppendLine($" Email -> {req.HttpContext.User.FindFirst("email")?.Value}");
43 |
44 | return new OkObjectResult(sb.ToString());
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/sample/SampleInProcFunctions.V4/host.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0",
3 | "logging": {
4 | "applicationInsights": {
5 | "samplingSettings": {
6 | "isEnabled": true,
7 | "excludedTypes": "Request"
8 | }
9 | },
10 | "logLevel": {
11 | "Darkloop": "Information",
12 | "Microsoft": "Information"
13 | }
14 | }
15 | }
--------------------------------------------------------------------------------
/sample/SampleIsolatedFunctions.V4/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # Azure Functions localsettings file
5 | local.settings.json
6 |
7 | # User-specific files
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Build results
17 | [Dd]ebug/
18 | [Dd]ebugPublic/
19 | [Rr]elease/
20 | [Rr]eleases/
21 | x64/
22 | x86/
23 | bld/
24 | [Bb]in/
25 | [Oo]bj/
26 | [Ll]og/
27 |
28 | # Visual Studio 2015 cache/options directory
29 | .vs/
30 | # Uncomment if you have tasks that create the project's static files in wwwroot
31 | #wwwroot/
32 |
33 | # MSTest test Results
34 | [Tt]est[Rr]esult*/
35 | [Bb]uild[Ll]og.*
36 |
37 | # NUNIT
38 | *.VisualState.xml
39 | TestResult.xml
40 |
41 | # Build Results of an ATL Project
42 | [Dd]ebugPS/
43 | [Rr]eleasePS/
44 | dlldata.c
45 |
46 | # DNX
47 | project.lock.json
48 | project.fragment.lock.json
49 | artifacts/
50 |
51 | *_i.c
52 | *_p.c
53 | *_i.h
54 | *.ilk
55 | *.meta
56 | *.obj
57 | *.pch
58 | *.pdb
59 | *.pgc
60 | *.pgd
61 | *.rsp
62 | *.sbr
63 | *.tlb
64 | *.tli
65 | *.tlh
66 | *.tmp
67 | *.tmp_proj
68 | *.log
69 | *.vspscc
70 | *.vssscc
71 | .builds
72 | *.pidb
73 | *.svclog
74 | *.scc
75 |
76 | # Chutzpah Test files
77 | _Chutzpah*
78 |
79 | # Visual C++ cache files
80 | ipch/
81 | *.aps
82 | *.ncb
83 | *.opendb
84 | *.opensdf
85 | *.sdf
86 | *.cachefile
87 | *.VC.db
88 | *.VC.VC.opendb
89 |
90 | # Visual Studio profiler
91 | *.psess
92 | *.vsp
93 | *.vspx
94 | *.sap
95 |
96 | # TFS 2012 Local Workspace
97 | $tf/
98 |
99 | # Guidance Automation Toolkit
100 | *.gpState
101 |
102 | # ReSharper is a .NET coding add-in
103 | _ReSharper*/
104 | *.[Rr]e[Ss]harper
105 | *.DotSettings.user
106 |
107 | # JustCode is a .NET coding add-in
108 | .JustCode
109 |
110 | # TeamCity is a build add-in
111 | _TeamCity*
112 |
113 | # DotCover is a Code Coverage Tool
114 | *.dotCover
115 |
116 | # NCrunch
117 | _NCrunch_*
118 | .*crunch*.local.xml
119 | nCrunchTemp_*
120 |
121 | # MightyMoose
122 | *.mm.*
123 | AutoTest.Net/
124 |
125 | # Web workbench (sass)
126 | .sass-cache/
127 |
128 | # Installshield output folder
129 | [Ee]xpress/
130 |
131 | # DocProject is a documentation generator add-in
132 | DocProject/buildhelp/
133 | DocProject/Help/*.HxT
134 | DocProject/Help/*.HxC
135 | DocProject/Help/*.hhc
136 | DocProject/Help/*.hhk
137 | DocProject/Help/*.hhp
138 | DocProject/Help/Html2
139 | DocProject/Help/html
140 |
141 | # Click-Once directory
142 | publish/
143 |
144 | # Publish Web Output
145 | *.[Pp]ublish.xml
146 | *.azurePubxml
147 | *.arm.json
148 | # TODO: Comment the next line if you want to checkin your web deploy settings
149 | # but database connection strings (with potential passwords) will be unencrypted
150 | #*.pubxml
151 | *.publishproj
152 |
153 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
154 | # checkin your Azure Web App publish settings, but sensitive information contained
155 | # in these scripts will be unencrypted
156 | PublishScripts/
157 |
158 | # NuGet Packages
159 | *.nupkg
160 | # The packages folder can be ignored because of Package Restore
161 | **/packages/*
162 | # except build/, which is used as an MSBuild target.
163 | !**/packages/build/
164 | # Uncomment if necessary however generally it will be regenerated when needed
165 | #!**/packages/repositories.config
166 | # NuGet v3's project.json files produces more ignoreable files
167 | *.nuget.props
168 | *.nuget.targets
169 |
170 | # Microsoft Azure Build Output
171 | csx/
172 | *.build.csdef
173 |
174 | # Microsoft Azure Emulator
175 | ecf/
176 | rcf/
177 |
178 | # Windows Store app package directories and files
179 | AppPackages/
180 | BundleArtifacts/
181 | Package.StoreAssociation.xml
182 | _pkginfo.txt
183 |
184 | # Visual Studio cache files
185 | # files ending in .cache can be ignored
186 | *.[Cc]ache
187 | # but keep track of directories ending in .cache
188 | !*.[Cc]ache/
189 |
190 | # Others
191 | ClientBin/
192 | ~$*
193 | *~
194 | *.dbmdl
195 | *.dbproj.schemaview
196 | *.jfm
197 | *.pfx
198 | *.publishsettings
199 | node_modules/
200 | orleans.codegen.cs
201 |
202 | # Since there are multiple workflows, uncomment next line to ignore bower_components
203 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
204 | #bower_components/
205 |
206 | # RIA/Silverlight projects
207 | Generated_Code/
208 |
209 | # Backup & report files from converting an old project file
210 | # to a newer Visual Studio version. Backup files are not needed,
211 | # because we have git ;-)
212 | _UpgradeReport_Files/
213 | Backup*/
214 | UpgradeLog*.XML
215 | UpgradeLog*.htm
216 |
217 | # SQL Server files
218 | *.mdf
219 | *.ldf
220 |
221 | # Business Intelligence projects
222 | *.rdl.data
223 | *.bim.layout
224 | *.bim_*.settings
225 |
226 | # Microsoft Fakes
227 | FakesAssemblies/
228 |
229 | # GhostDoc plugin setting file
230 | *.GhostDoc.xml
231 |
232 | # Node.js Tools for Visual Studio
233 | .ntvs_analysis.dat
234 |
235 | # Visual Studio 6 build log
236 | *.plg
237 |
238 | # Visual Studio 6 workspace options file
239 | *.opt
240 |
241 | # Visual Studio LightSwitch build output
242 | **/*.HTMLClient/GeneratedArtifacts
243 | **/*.DesktopClient/GeneratedArtifacts
244 | **/*.DesktopClient/ModelManifest.xml
245 | **/*.Server/GeneratedArtifacts
246 | **/*.Server/ModelManifest.xml
247 | _Pvt_Extensions
248 |
249 | # Paket dependency manager
250 | .paket/paket.exe
251 | paket-files/
252 |
253 | # FAKE - F# Make
254 | .fake/
255 |
256 | # JetBrains Rider
257 | .idea/
258 | *.sln.iml
259 |
260 | # CodeRush
261 | .cr/
262 |
263 | # Python Tools for Visual Studio (PTVS)
264 | __pycache__/
265 | *.pyc
--------------------------------------------------------------------------------
/sample/SampleIsolatedFunctions.V4/HelperFunctions.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using System.Security.Claims;
6 | using Common.Tests;
7 | using Microsoft.AspNetCore.Http;
8 | using Microsoft.AspNetCore.Mvc;
9 | using Microsoft.Azure.Functions.Worker;
10 | using Microsoft.Extensions.Logging;
11 |
12 | namespace SampleInProcFunctions.V4
13 | {
14 | public static class HelperFunctions
15 | {
16 | [Function("GetTestToken")]
17 | public static async Task Run(
18 | [HttpTrigger("get", Route = null)] HttpRequest req,
19 | ILogger log)
20 | {
21 | var firstName = "Test";
22 | var lastName = "User";
23 | var email = "test.user@domain.com";
24 | var token = JwtUtils.GenerateJwtToken(new[] {
25 | new Claim("aud", "api://default"),
26 | new Claim("iss", "https://localhost/jwt/"),
27 | new Claim("scp", "user_impersonation"),
28 | new Claim("tid", Guid.NewGuid().ToString()),
29 | new Claim("oid", Guid.NewGuid().ToString()),
30 | new Claim("name", $"{firstName} {lastName}"),
31 | new Claim(ClaimTypes.Name, email),
32 | new Claim(ClaimTypes.Upn, email),
33 | new Claim(ClaimTypes.Email, email),
34 | new Claim(ClaimTypes.GivenName, firstName),
35 | new Claim(ClaimTypes.Surname, lastName),
36 | new Claim("role", "Just a user"),
37 | new Claim("role", "admin"),
38 | });
39 |
40 | return await Task.FromResult(new OkObjectResult(token));
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/sample/SampleIsolatedFunctions.V4/Program.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using Common.Tests;
6 | using DarkLoop.Azure.Functions.Authorization;
7 | using Microsoft.Azure.Functions.Worker;
8 | using Microsoft.Extensions.DependencyInjection;
9 | using Microsoft.Extensions.Hosting;
10 | using Microsoft.IdentityModel.Tokens;
11 |
12 | // IMPORTANT: because local.settings.json is not included in the repository, you must create it manually
13 | // If you don't create it. the isolated function will not run. Ensure that the file has the following content:
14 | //
15 | // {
16 | // "IsEncrypted": false,
17 | // "Values": {
18 | // "AzureWebJobsStorage": "UseDevelopmentStorage=true",
19 | // "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated"
20 | // }
21 | // }
22 |
23 | var host = new HostBuilder()
24 | .ConfigureFunctionsWebApplication(builder =>
25 | {
26 | builder.UseFunctionsAuthorization();
27 | })
28 | .ConfigureServices(services =>
29 | {
30 | services
31 | .AddFunctionsAuthentication(JwtFunctionsBearerDefaults.AuthenticationScheme)
32 | .AddJwtFunctionsBearer(options =>
33 | {
34 | // this line is here to bypass the token validation
35 | // and test the functionality of this library.
36 | // you can create a dummy token by executing the GetTestToken function in HelperFunctions.cs
37 | // THE FOLLOWING LINE SHOULD BE REMOVED IN A REAL-WORLD SCENARIO
38 | options.SecurityTokenValidators.Add(new TestTokenValidator());
39 |
40 | // this is what you should look for in a real-world scenario
41 | // comment the lines if you cloned this repository and want to test the library
42 | options.Authority = "https://login.microsoftonline.com/";
43 | options.Audience = "";
44 | options.TokenValidationParameters = new TokenValidationParameters
45 | {
46 | ValidateIssuer = true,
47 | ValidateAudience = true,
48 | ValidateLifetime = true,
49 | ValidateIssuerSigningKey = true,
50 | };
51 | });
52 |
53 | services
54 | .AddFunctionsAuthorization(options =>
55 | {
56 | // Add your policies here
57 | });
58 | })
59 | .Build();
60 |
61 | host.Run();
62 |
--------------------------------------------------------------------------------
/sample/SampleIsolatedFunctions.V4/Properties/serviceDependencies.json:
--------------------------------------------------------------------------------
1 | {
2 | "dependencies": {
3 | "appInsights1": {
4 | "type": "appInsights"
5 | },
6 | "storage1": {
7 | "type": "storage",
8 | "connectionId": "AzureWebJobsStorage"
9 | }
10 | }
11 | }
--------------------------------------------------------------------------------
/sample/SampleIsolatedFunctions.V4/Properties/serviceDependencies.local.json:
--------------------------------------------------------------------------------
1 | {
2 | "dependencies": {
3 | "appInsights1": {
4 | "type": "appInsights.sdk"
5 | },
6 | "storage1": {
7 | "type": "storage.emulator",
8 | "connectionId": "AzureWebJobsStorage"
9 | }
10 | }
11 | }
--------------------------------------------------------------------------------
/sample/SampleIsolatedFunctions.V4/SampleIsolatedFunctions.V4.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net6.0
4 | v4
5 | Exe
6 | enable
7 | enable
8 | false
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 | PreserveNewest
24 |
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/sample/SampleIsolatedFunctions.V4/TestFunction.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using System.Text;
6 | using DarkLoop.Azure.Functions.Authorization;
7 | using Microsoft.AspNetCore.Authentication;
8 | using Microsoft.AspNetCore.Authorization;
9 | using Microsoft.AspNetCore.Http;
10 | using Microsoft.AspNetCore.Mvc;
11 | using Microsoft.Azure.Functions.Worker;
12 | using Microsoft.Extensions.DependencyInjection;
13 | using Microsoft.Extensions.Logging;
14 |
15 | namespace SampleIsolatedFunctions.V4
16 | {
17 | [FunctionAuthorize(AuthenticationSchemes = "FunctionsBearer")]
18 | public class TestFunction
19 | {
20 | private readonly ILogger _logger;
21 |
22 | public TestFunction(ILogger logger)
23 | {
24 | _logger = logger;
25 | }
26 |
27 | [Function("TestFunction")]
28 | [Authorize(Roles = "admin")]
29 | public async Task Run([HttpTrigger("get", "post")] HttpRequest req)
30 | {
31 | _logger.LogInformation("C# HTTP trigger function processed a request.");
32 |
33 | var provider = req.HttpContext.RequestServices;
34 | var schProvider = provider.GetService();
35 |
36 | var sb = new StringBuilder();
37 | sb.AppendLine("Authentication schemes:");
38 |
39 | if (schProvider is not null)
40 | {
41 | foreach (var scheme in await schProvider.GetAllSchemesAsync())
42 | sb.AppendLine($" {scheme.Name} -> {scheme.HandlerType}");
43 | }
44 |
45 | sb.AppendLine();
46 | sb.AppendLine($"User:");
47 | sb.AppendLine($" Name -> {req.HttpContext.User.Identity!.Name}");
48 | sb.AppendLine($" Email -> {req.HttpContext.User.FindFirst("email")?.Value}");
49 |
50 | return new OkObjectResult(sb.ToString());
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/sample/SampleIsolatedFunctions.V4/host.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0",
3 | "logging": {
4 | "applicationInsights": {
5 | "samplingSettings": {
6 | "isEnabled": true,
7 | "excludedTypes": "Request"
8 | },
9 | "enableLiveMetricsFilters": true
10 | }
11 | }
12 | }
--------------------------------------------------------------------------------
/sample/SampleIsolatedFunctionsFSharp.V4/.vscode/extensions.json:
--------------------------------------------------------------------------------
1 | {
2 | "recommendations": [
3 | "ms-azuretools.vscode-azurefunctions"
4 | ]
5 | }
--------------------------------------------------------------------------------
/sample/SampleIsolatedFunctionsFSharp.V4/HelperFunctions.fs:
--------------------------------------------------------------------------------
1 | namespace SampleInProcFunctions.V4
2 |
3 | open System.Security.Claims
4 | open Common.Tests
5 | open Microsoft.AspNetCore.Http
6 | open Microsoft.AspNetCore.Mvc
7 | open Microsoft.Azure.Functions.Worker
8 | open Microsoft.Extensions.Logging
9 | open System
10 |
11 | type HelperFunctions() =
12 |
13 | []
14 | member _.Run(
15 | []
16 | req: HttpRequest,
17 | log: ILogger) =
18 | task {
19 |
20 | let firstName = "Test"
21 | let lastName = "User"
22 | let email = "test.user@domain.com"
23 | let token = JwtUtils.GenerateJwtToken(
24 | [
25 | new Claim("aud", "api://default")
26 | new Claim("iss", "https://localhost/jwt/")
27 | new Claim("scp", "user_impersonation")
28 | new Claim("tid", Guid.NewGuid().ToString())
29 | new Claim("oid", Guid.NewGuid().ToString())
30 | new Claim("name", $"{firstName} {lastName}")
31 | new Claim(ClaimTypes.Name, email)
32 | new Claim(ClaimTypes.Upn, email)
33 | new Claim(ClaimTypes.Email, email)
34 | new Claim(ClaimTypes.GivenName, firstName)
35 | new Claim(ClaimTypes.Surname, lastName)
36 | new Claim("role", "Just a user")
37 | new Claim("role", "admin")
38 | ])
39 |
40 | return OkObjectResult(token)
41 | }
42 |
43 |
44 |
--------------------------------------------------------------------------------
/sample/SampleIsolatedFunctionsFSharp.V4/Program.fs:
--------------------------------------------------------------------------------
1 | module Program
2 |
3 | open Common.Tests
4 | open DarkLoop.Azure.Functions.Authorization
5 | open Microsoft.Azure.Functions.Worker
6 | open Microsoft.Extensions.DependencyInjection
7 | open Microsoft.Extensions.Hosting
8 | open Microsoft.IdentityModel.Tokens
9 |
10 | // IMPORTANT: because local.settings.json is not included in the repository, you must create it manually
11 | // If you don't create it. the isolated function will not run. Ensure that the file has the following content:
12 | //
13 | // {
14 | // "IsEncrypted": false,
15 | // "Values": {
16 | // "AzureWebJobsStorage": "UseDevelopmentStorage=true",
17 | // "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated"
18 | // }
19 | // }
20 |
21 | let host =
22 | HostBuilder()
23 | .ConfigureFunctionsWebApplication(fun builder ->
24 | //This is needed to make F# variants of startup work nicely
25 | FunctionsAuthorizationExtensionStartup().Configure(builder)
26 | builder.UseFunctionsAuthorization() |> ignore )
27 | .ConfigureServices(fun services ->
28 | services
29 | .AddFunctionsAuthentication(JwtFunctionsBearerDefaults.AuthenticationScheme)
30 | .AddJwtFunctionsBearer(fun options ->
31 | // this line is here to bypass the token validation
32 | // and test the functionality of this library.
33 | // you can create a dummy token by executing the GetTestToken function in HelperFunctions.cs
34 | // THE FOLLOWING LINE SHOULD BE REMOVED IN A REAL-WORLD SCENARIO
35 | options.SecurityTokenValidators.Add(TestTokenValidator())
36 |
37 | // this is what you should look for in a real-world scenario
38 | // comment the lines if you cloned this repository and want to test the library
39 | options.Authority <- "https://login.microsoftonline.com/"
40 | options.Audience <- ""
41 | options.TokenValidationParameters <- TokenValidationParameters
42 | (
43 | ValidateIssuer = true,
44 | ValidateAudience = true,
45 | ValidateLifetime = true,
46 | ValidateIssuerSigningKey = true
47 | )
48 | ()
49 | ) |> ignore
50 |
51 | services
52 | .AddFunctionsAuthorization(fun options ->
53 | // Add your policies here
54 | ()
55 | ) |> ignore
56 | )
57 | .Build()
58 |
59 | host.Run()
60 |
--------------------------------------------------------------------------------
/sample/SampleIsolatedFunctionsFSharp.V4/Properties/serviceDependencies.json:
--------------------------------------------------------------------------------
1 | {
2 | "dependencies": {
3 | "appInsights1": {
4 | "type": "appInsights"
5 | },
6 | "storage1": {
7 | "type": "storage",
8 | "connectionId": "AzureWebJobsStorage"
9 | }
10 | }
11 | }
--------------------------------------------------------------------------------
/sample/SampleIsolatedFunctionsFSharp.V4/Properties/serviceDependencies.local.json:
--------------------------------------------------------------------------------
1 | {
2 | "dependencies": {
3 | "appInsights1": {
4 | "type": "appInsights.sdk"
5 | },
6 | "storage1": {
7 | "type": "storage.emulator",
8 | "connectionId": "AzureWebJobsStorage"
9 | }
10 | }
11 | }
--------------------------------------------------------------------------------
/sample/SampleIsolatedFunctionsFSharp.V4/SampleIsolatedFunctionsFSharp_V4.fsproj:
--------------------------------------------------------------------------------
1 |
2 |
3 | net8.0
4 | v4
5 | Exe
6 | 17c2def3-36ba-461c-8cf2-2305557bb98b
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 | PreserveNewest
38 |
39 |
40 | PreserveNewest
41 | Never
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/sample/SampleIsolatedFunctionsFSharp.V4/TestFunction.fs:
--------------------------------------------------------------------------------
1 | namespace SampleIsolatedFunctionsFSharp.V4
2 |
3 | open System.Text
4 | open DarkLoop.Azure.Functions.Authorization
5 | open Microsoft.AspNetCore.Authentication
6 | open Microsoft.AspNetCore.Authorization
7 | open Microsoft.AspNetCore.Http
8 | open Microsoft.AspNetCore.Mvc
9 | open Microsoft.Azure.Functions.Worker
10 | open Microsoft.Extensions.DependencyInjection
11 | open Microsoft.Extensions.Logging
12 |
13 |
14 | []
15 | type TestFunction(logger:ILogger) =
16 | let _logger = logger
17 |
18 | []
19 | []
20 | member _.Run([] req:HttpRequest) =
21 | task {
22 | _logger.LogInformation("F# HTTP trigger function processed a request.")
23 |
24 | let provider = req.HttpContext.RequestServices
25 | let schProvider = provider.GetService()
26 |
27 | let sb = new StringBuilder()
28 | sb.AppendLine("Authentication schemes:") |> ignore
29 |
30 | if (schProvider <> null) then
31 | let! allScheme = schProvider.GetAllSchemesAsync()
32 | for scheme in allScheme do
33 | sb.AppendLine($" {scheme.Name} -> {scheme.HandlerType}") |> ignore
34 |
35 |
36 | sb.AppendLine()|> ignore
37 | sb.AppendLine($"User:")|> ignore
38 | sb.AppendLine($" Name -> {req.HttpContext.User.Identity.Name}")|> ignore
39 | let email = req.HttpContext.User.FindFirst("email")|> Option.ofObj|>Option.map _.Value
40 | sb.AppendLine($" Email -> {email}")|> ignore
41 |
42 | return OkObjectResult(sb.ToString())
43 | }
--------------------------------------------------------------------------------
/sample/SampleIsolatedFunctionsFSharp.V4/host.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0",
3 | "logging": {
4 | "applicationInsights": {
5 | "samplingSettings": {
6 | "isEnabled": true,
7 | "excludedTypes": "Request"
8 | },
9 | "enableLiveMetricsFilters": true
10 | }
11 | }
12 | }
--------------------------------------------------------------------------------
/sample/SampleIsolatedFunctionsFSharp.V4/local.settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "IsEncrypted": false,
3 | "Values": {
4 | "AzureWebJobsStorage": "UseDevelopmentStorage=true",
5 | "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated"
6 | }
7 | }
--------------------------------------------------------------------------------
/src/abstractions/Cache/FunctionsAuthorizationFilterCache.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using System.Collections.Concurrent;
6 |
7 | namespace DarkLoop.Azure.Functions.Authorization.Cache
8 | {
9 | ///
10 | internal sealed class FunctionsAuthorizationFilterCache : IFunctionsAuthorizationFilterCache
11 | where TIdentifier : notnull
12 | {
13 | private readonly ConcurrentDictionary _filters = new();
14 |
15 | ///
16 | public bool TryGetFilter(TIdentifier functionIdentifier, out FunctionAuthorizationFilter? filter)
17 | {
18 | return _filters.TryGetValue(functionIdentifier, out filter);
19 | }
20 |
21 | ///
22 | public bool SetFilter(TIdentifier functionIdentifier, FunctionAuthorizationFilter builder)
23 | {
24 | return _filters.TryAdd(functionIdentifier, builder);
25 | }
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/src/abstractions/Cache/IFunctionsAuthorizationFilterCache.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | namespace DarkLoop.Azure.Functions.Authorization.Cache
6 | {
7 | ///
8 | /// Provides a fully built authorization filter cache for functions.
9 | ///
10 | public interface IFunctionsAuthorizationFilterCache
11 | {
12 | ///
13 | /// Gets the authorization filter for the specified function if exists.
14 | ///
15 | bool TryGetFilter(TIdentifier functionIdentifier, out FunctionAuthorizationFilter? filter);
16 |
17 | ///
18 | /// Sets the authorization filter for the specified function.
19 | ///
20 | /// The function unique identifier
21 | /// The filter to cache.
22 | ///
23 | bool SetFilter(TIdentifier functionIdentifier, FunctionAuthorizationFilter filter);
24 | }
25 | }
--------------------------------------------------------------------------------
/src/abstractions/Constants.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using System.Diagnostics.CodeAnalysis;
6 |
7 | namespace DarkLoop.Azure.Functions.Authorization
8 | {
9 | [ExcludeFromCodeCoverage]
10 | internal class Constants
11 | {
12 | internal const string AuthInvokedKey = "__WebJobAuthInvoked";
13 | internal const string WebJobsAuthScheme = "WebJobsAuthLevel";
14 | internal const string ArmTokenAuthScheme = "ArmToken";
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/abstractions/DarkLoop.Azure.Functions.Authorization.Abstractions.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | DarkLoop.Azure.Functions.Authorization.Abstractions
5 | DarkLoop.Azure.Functions.Authorization
6 | net6.0;net8.0
7 | 0.0.1-preview
8 | DarkLoop's Azure Functions authorization extension shared core functionality for InProc and Isolated modules.
9 | enable
10 |
11 |
12 |
13 | TRACE
14 |
15 |
16 |
17 | DEBUG;TRACE
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 | True
49 | True
50 | Messages.resx
51 |
52 |
53 |
54 |
55 |
56 | ResXFileCodeGenerator
57 | Messages.Designer.cs
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/src/abstractions/EmptySchemeStrategy.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | namespace DarkLoop.Azure.Functions.Authorization
6 | {
7 | ///
8 | /// Strategy to use when schemes are not specified in function authorization definition.
9 | ///
10 | public enum EmptySchemeStrategy
11 | {
12 | ///
13 | /// Use all authentication schemes specified in the application.
14 | ///
15 | ///
16 | /// This does not apply to and within the In-Proc hosting model.
17 | ///
18 | UseAllSchemes,
19 |
20 | ///
21 | /// Use the default authentication scheme specified in the application.
22 | ///
23 | UseDefaultScheme,
24 | }
25 | }
--------------------------------------------------------------------------------
/src/abstractions/FunctionAuthorizationContext.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using System.Diagnostics.CodeAnalysis;
6 | using DarkLoop.Azure.Functions.Authorization.Internal;
7 | using Microsoft.AspNetCore.Authorization;
8 | using Microsoft.AspNetCore.Authorization.Policy;
9 |
10 | namespace DarkLoop.Azure.Functions.Authorization
11 | {
12 | ///
13 | /// Represents the context associated with the current request authorization.
14 | ///
15 | ///
16 | [ExcludeFromCodeCoverage]
17 | public class FunctionAuthorizationContext
18 | where TContext : class
19 | {
20 | ///
21 | /// Initializes a new instance of the class.
22 | ///
23 | /// The name of the function.
24 | /// The platform dependent context associated with the current request.
25 | /// The authorization policy associated with the current request.
26 | /// The authorization result associated with the current request.
27 | public FunctionAuthorizationContext(
28 | string functionName, TContext httpContext, AuthorizationPolicy policy, PolicyAuthorizationResult result)
29 | {
30 | Check.NotNullOrWhiteSpace(functionName, nameof(functionName));
31 | Check.NotNull(httpContext, nameof(httpContext));
32 | Check.NotNull(policy, nameof(policy));
33 | Check.NotNull(result, nameof(result));
34 |
35 | FunctionName = functionName;
36 | UnderlyingContext = httpContext;
37 | Policy = policy;
38 | Result = result;
39 | }
40 |
41 | ///
42 | /// Gets the name of the function.
43 | ///
44 | public string FunctionName { get; }
45 |
46 | ///
47 | /// Gets the underlying context associated with the current request.
48 | ///
49 | public TContext UnderlyingContext { get; }
50 |
51 | ///
52 | /// Gets the authorization policy associated with the current request.
53 | ///
54 | public AuthorizationPolicy Policy { get; set; }
55 |
56 | ///
57 | /// Gets the authorization result associated with the current request.
58 | ///
59 | public PolicyAuthorizationResult Result { get; set; }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/abstractions/FunctionAuthorizationFeature.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using DarkLoop.Azure.Functions.Authorization.Internal;
6 | using Microsoft.AspNetCore.Authentication;
7 | using Microsoft.AspNetCore.Http.Features.Authentication;
8 | using System.Security.Claims;
9 |
10 | namespace DarkLoop.Azure.Functions.Authorization
11 | {
12 | // This was designed with maximum compatibility with ASP.NET core. It keeps
13 | // two separate features in sync with each other automatically.
14 | internal sealed class FunctionAuthorizationFeature : IAuthenticateResultFeature, IHttpAuthenticationFeature
15 | {
16 | private ClaimsPrincipal? _principal;
17 | private AuthenticateResult? _authenticateResult;
18 |
19 | ///
20 | /// Construct an instance of the feature with the given AuthenticateResult
21 | ///
22 | ///
23 | public FunctionAuthorizationFeature(AuthenticateResult result)
24 | {
25 | Check.NotNull(result, nameof(result));
26 |
27 | AuthenticateResult = result;
28 | }
29 |
30 | ///
31 | public AuthenticateResult? AuthenticateResult
32 | {
33 | get => _authenticateResult;
34 | set
35 | {
36 | _authenticateResult = value;
37 | _principal = value?.Principal;
38 | }
39 | }
40 |
41 | ///
42 | public ClaimsPrincipal? User
43 | {
44 | get => _principal;
45 | set
46 | {
47 | _authenticateResult = null;
48 | _principal = value;
49 | }
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/src/abstractions/FunctionAuthorizationFilter.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using System.Diagnostics.CodeAnalysis;
6 | using Microsoft.AspNetCore.Authorization;
7 |
8 | namespace DarkLoop.Azure.Functions.Authorization
9 | {
10 | ///
11 | /// Represents the authorization filter for a function.
12 | ///
13 | [ExcludeFromCodeCoverage]
14 | public sealed class FunctionAuthorizationFilter
15 | {
16 | ///
17 | /// Initializes a new instance of the class.
18 | ///
19 | /// The to be used for the function.
20 | /// A value indicating whether the function allows anonymous access.
21 | public FunctionAuthorizationFilter(AuthorizationPolicy? authorizationPolicy, bool allowAnonymous = false)
22 | {
23 | Policy = authorizationPolicy;
24 | AllowAnonymous = allowAnonymous;
25 | }
26 |
27 | ///
28 | /// A value indicating whether the function allows anonymous access.
29 | ///
30 | public bool AllowAnonymous { get; }
31 |
32 | ///
33 | /// Gets or sets the to be used for the function.
34 | ///
35 | public AuthorizationPolicy? Policy { get; }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/abstractions/FunctionAuthorizationMetadata.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Collections.Immutable;
8 | using DarkLoop.Azure.Functions.Authorization.Internal;
9 | using Microsoft.AspNetCore.Authorization;
10 |
11 | namespace DarkLoop.Azure.Functions.Authorization
12 | {
13 | ///
14 | /// Authorization metadata for a function or type.
15 | ///
16 | public sealed class FunctionAuthorizationMetadata
17 | {
18 | private readonly int _key;
19 | private readonly string? _functionName;
20 | private readonly Type? _declaringType;
21 | private readonly List _authData;
22 |
23 | ///
24 | /// Default authorization rule.
25 | ///
26 | public readonly static FunctionAuthorizationMetadata Empty = new() { AllowsAnonymousAccess = false };
27 |
28 | ///
29 | /// Initializes a new instance of the class.
30 | ///
31 | private FunctionAuthorizationMetadata() => _authData = new List();
32 |
33 | ///
34 | /// Initializes a new instance of the class.
35 | ///
36 | /// The name of the function as specified in the [Function(Name)Attribute].
37 | /// The type declaring the function method.
38 | internal FunctionAuthorizationMetadata(string functionName, Type declaringType) : this()
39 | {
40 | Check.NotNullOrWhiteSpace(functionName, nameof(functionName), "The name of the function must be specified.");
41 | Check.NotNull(declaringType, nameof(declaringType), "The declaring type of the function must be specified.");
42 |
43 | _key = GetId(functionName, declaringType);
44 | _functionName = functionName;
45 | _declaringType = declaringType;
46 | }
47 |
48 | ///
49 | /// Initializes a new instance of the class.
50 | ///
51 | /// The type declaring the function method.
52 | internal FunctionAuthorizationMetadata(Type declaringType) : this()
53 | {
54 | Check.NotNull(declaringType, nameof(declaringType), "The declaring type of the function must be specified.");
55 |
56 | _key = GetId(null, declaringType);
57 | _declaringType = declaringType;
58 | }
59 |
60 | ///
61 | /// Gets the authorization ID for the function or type.
62 | ///
63 | public int AuthorizationId => _key;
64 |
65 | ///
66 | /// Gets the name of the function as specified in the [Function(Name)Attribute].
67 | ///
68 | public string? FunctionName => _functionName;
69 |
70 | ///
71 | /// Gets the name of the type declaring the function method.
72 | ///
73 | /// The returned value is never . Only for
74 | public Type? DeclaringType => _declaringType;
75 |
76 | ///
77 | /// Gets a value indicating whether the function allows anonymous access.
78 | ///
79 | public bool AllowsAnonymousAccess { get; internal set; }
80 |
81 | ///
82 | /// Gets the authorization data for the function or type.
83 | ///
84 | public IReadOnlyList AuthorizationData => _authData.ToImmutableArray();
85 |
86 | ///
87 | /// Adds authorization data to metadata.
88 | ///
89 | /// Authorize data.
90 | public FunctionAuthorizationMetadata AddAuthorizeData(IAuthorizeData authorizeData)
91 | {
92 | Check.NotNull(authorizeData, nameof(authorizeData), "The authorization data must be specified.");
93 |
94 | _authData.Add(authorizeData);
95 |
96 | return this;
97 | }
98 |
99 | ///
100 | /// Adds authorization data to metadata.
101 | ///
102 | /// Authorize data.
103 | public FunctionAuthorizationMetadata AddAuthorizeData(IEnumerable authorizeData)
104 | {
105 | Check.NotNull(authorizeData, nameof(authorizeData), "The authorization data must be specified.");
106 | Check.All(authorizeData, x => Check.NotNull(x, nameof(authorizeData), "All elements in authorization data must be non-null."));
107 |
108 | _authData.AddRange(authorizeData);
109 |
110 | return this;
111 | }
112 |
113 | ///
114 | /// Allows anonymous access to the function.
115 | /// Once the value ise set, it cannot be changed.
116 | ///
117 | public FunctionAuthorizationMetadata AllowAnonymousAccess()
118 | {
119 | AllowsAnonymousAccess = true;
120 |
121 | return this;
122 | }
123 |
124 | ///
125 | /// Gets the metadata ID for a function.
126 | ///
127 | /// The name of the function.
128 | /// The type declaring the function.
129 | internal static int GetId(string? functionName, Type? declaringType) =>
130 | (declaringType?.GetHashCode() ?? 0) ^
131 | (functionName?.GetHashCode(StringComparison.OrdinalIgnoreCase) ?? 0);
132 | }
133 | }
134 |
--------------------------------------------------------------------------------
/src/abstractions/FunctionAuthorizationTypeMap.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using System;
6 | using System.Collections.Concurrent;
7 | using System.Collections.Generic;
8 | using System.Linq;
9 | using System.Text;
10 | using System.Threading.Tasks;
11 |
12 | namespace DarkLoop.Azure.Functions.Authorization
13 | {
14 | internal sealed class FunctionAuthorizationTypeMap
15 | {
16 | private readonly ConcurrentDictionary _typeMap = new(StringComparer.OrdinalIgnoreCase);
17 |
18 | ///
19 | /// Registers the type declaring a function with the specified .
20 | ///
21 | /// The name of the function.
22 | /// The type declaring the function.
23 | /// if the registration was successful; otherwise .
24 | internal bool AddFunctionType(string functionName, Type functionType)
25 | {
26 | return _typeMap.TryAdd(functionName, functionType);
27 | }
28 |
29 | ///
30 | /// Gets the type declaring a function with the specified .
31 | ///
32 | /// The name of the function.
33 | ///
34 | internal Type? this[string functionName]
35 | {
36 | get => _typeMap.GetValueOrDefault(functionName);
37 | }
38 |
39 | ///
40 | /// Returns a value indicating whether the function with the specified is registered.
41 | ///
42 | /// The name of the function.
43 | /// if function is registered; otherwise
44 | internal bool IsFunctionRegistered(string functionName)
45 | {
46 | return _typeMap.ContainsKey(functionName);
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/abstractions/FunctionsAuthenticationBuilder.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using Microsoft.AspNetCore.Authentication;
6 | using Microsoft.Extensions.DependencyInjection;
7 |
8 | namespace DarkLoop.Azure.Functions.Authorization
9 | {
10 | ///
11 | /// An that enhances the built-in authentication behavior for Azure Functions.
12 | ///
13 | public class FunctionsAuthenticationBuilder : AuthenticationBuilder
14 | {
15 | ///
16 | /// Initializes a new instance of the class.
17 | ///
18 | /// The current service collection instance.
19 | internal FunctionsAuthenticationBuilder(IServiceCollection services)
20 | : base(services) { }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/abstractions/FunctionsAuthenticationBuilderExtensions.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using System;
6 | using DarkLoop.Azure.Functions.Authorization;
7 | using Microsoft.AspNetCore.Authentication.JwtBearer;
8 |
9 | namespace Microsoft.Extensions.DependencyInjection
10 | {
11 |
12 | public static class FunctionsAuthenticationBuilderExtensions
13 | {
14 | ///
15 | /// Adds the JWT "FunctionsBearer" scheme to the authentication configuration.
16 | ///
17 | /// The current authentication builder.
18 | /// An action configuring the JWT options for authentication.
19 | /// The authentication scheme to use."
20 | /// A instance of the
21 | public static FunctionsAuthenticationBuilder AddJwtFunctionsBearer(
22 | this FunctionsAuthenticationBuilder builder, string authenticationScheme, Action configureOptions)
23 | {
24 | if (authenticationScheme.Equals(JwtBearerDefaults.AuthenticationScheme, StringComparison.OrdinalIgnoreCase))
25 | {
26 | throw new ArgumentException("Bearer scheme cannot be specified as it conflicts with Azure Functions built-in authentication", nameof(authenticationScheme));
27 | }
28 |
29 | builder.AddJwtBearer(authenticationScheme, configureOptions);
30 |
31 | return builder;
32 | }
33 |
34 | ///
35 | /// Adds the JWT "FunctionsBearer" scheme to the authentication configuration.
36 | ///
37 | /// The current authentication builder.
38 | /// An action configuring the JWT options for authentication.
39 | /// A instance of the
40 | public static FunctionsAuthenticationBuilder AddJwtFunctionsBearer(
41 | this FunctionsAuthenticationBuilder builder, Action configureOptions)
42 | {
43 | builder.AddJwtBearer(JwtFunctionsBearerDefaults.AuthenticationScheme, configureOptions);
44 |
45 | return builder;
46 | }
47 |
48 | ///
49 | /// Adds the JWT "FunctionsBearer" scheme to the authentication configuration.
50 | ///
51 | /// The current authentication builder.
52 | /// A instance of the
53 | public static FunctionsAuthenticationBuilder AddJwtFunctionsBearer(
54 | this FunctionsAuthenticationBuilder builder)
55 | {
56 | return builder.AddJwtFunctionsBearer(_ => { });
57 | }
58 |
59 | ///
60 | /// This is a no-op method to prevent conflicts with the built-in AddJwtBearer used by the functions host.
61 | ///
62 | /// The current builder.
63 | /// JWT options configuration.
64 | ///
65 | [Obsolete("This method should not be called without specifying a name, as it would conflict with the framework's built-in setup. Use AddJwtFunctionsBearer instead, or specify a name other than 'Bearer' for scheme.", true)]
66 | public static FunctionsAuthenticationBuilder AddJwtBearer(
67 | this FunctionsAuthenticationBuilder builder, Action configureOptions)
68 | {
69 | // This method should not be called without specifying a name,
70 | // as it would conflict with the framework's built-in setup.
71 | return builder;
72 | }
73 |
74 | ///
75 | /// This is a no-op method to prevent conflicts with the built-in AddJwtBearer used by the functions host.
76 | ///
77 | /// The current builder.
78 | ///
79 | [Obsolete("This method should not be called without specifying a name, as it would conflict with the framework's built-in setup. Use AddJwtFunctionsBearer instead, or specify a name other than 'Bearer' for scheme.", true)]
80 | public static FunctionsAuthenticationBuilder AddJwtBearer(
81 | this FunctionsAuthenticationBuilder builder)
82 | {
83 | // This method should not be called without specifying a name,
84 | // as it would conflict with the framework's built-in setup.
85 | return builder;
86 | }
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/abstractions/FunctionsAuthorizationBuilder.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | namespace DarkLoop.Azure.Functions.Authorization
6 | {
7 | ///
8 | /// Placeholder class for future functionality.
9 | ///
10 | public class FunctionsAuthorizationBuilder
11 | {
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/abstractions/FunctionsAuthorizationCoreServiceCollectionExtensions.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using DarkLoop.Azure.Functions.Authorization.Cache;
6 | using Microsoft.Extensions.DependencyInjection;
7 | using Microsoft.Extensions.DependencyInjection.Extensions;
8 |
9 | namespace DarkLoop.Azure.Functions.Authorization
10 | {
11 | ///
12 | /// Extension methods for adding the Functions Authorization Core services to the DI container.
13 | ///
14 | internal static class FunctionsAuthorizationCoreServiceCollectionExtensions
15 | {
16 | public static IServiceCollection AddFunctionsAuthorizationCore(this IServiceCollection services)
17 | {
18 | services
19 | .TryAddSingleton();
20 |
21 | return services
22 | .AddSingleton()
23 | .AddSingleton(typeof(IFunctionsAuthorizationFilterCache<>), typeof(FunctionsAuthorizationFilterCache<>));
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/abstractions/FunctionsAuthorizationOptions.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using System.Diagnostics.CodeAnalysis;
6 | using Microsoft.AspNetCore.Authorization;
7 |
8 | namespace DarkLoop.Azure.Functions.Authorization
9 | {
10 | ///
11 | /// Options to manage Authorization functionality for Azure Functions.
12 | ///
13 | [ExcludeFromCodeCoverage]
14 | // Important to keep this class POCO, any special functionality should be done with extension methods.
15 | public sealed class FunctionsAuthorizationOptions
16 | {
17 | internal readonly FunctionAuthorizationMetadataCollection AuthorizationMetadata = new();
18 |
19 | ///
20 | /// Gets or sets a value indicating whether authorization is disabled.
21 | ///
22 | public bool AuthorizationDisabled {get; set;}
23 |
24 | ///
25 | /// Gets or sets a value indicating whether to write the HTTP status
26 | /// to the response when authorization failure occurs.
27 | ///
28 | public bool WriteHttpStatusToResponse { get; set; }
29 |
30 | ///
31 | /// Gets or sets the strategy to use when is empty. Default value is .
32 | ///
33 | public EmptySchemeStrategy EmptySchemeStrategy { get; set; }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/abstractions/FunctionsAuthorizationResultHandler.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using System;
6 | using System.Net;
7 | using System.Threading.Tasks;
8 | using DarkLoop.Azure.Functions.Authorization.Internal;
9 | using Microsoft.AspNetCore.Authentication;
10 | using Microsoft.AspNetCore.Authorization.Policy;
11 | using Microsoft.AspNetCore.Http;
12 | using Microsoft.AspNetCore.Mvc;
13 | using Microsoft.AspNetCore.Mvc.Abstractions;
14 | using Microsoft.AspNetCore.Routing;
15 | using Microsoft.Extensions.Options;
16 |
17 | namespace DarkLoop.Azure.Functions.Authorization
18 | {
19 | ///
20 | internal sealed class FunctionsAuthorizationResultHandler : IFunctionsAuthorizationResultHandler
21 | {
22 | private readonly IOptionsMonitor _options;
23 |
24 | ///
25 | /// Initializes a new instance of the class.
26 | ///
27 | /// The framework options.
28 | public FunctionsAuthorizationResultHandler(
29 | IOptionsMonitor monitoredOptions)
30 | {
31 | _options = monitoredOptions;
32 | }
33 |
34 | private FunctionsAuthorizationOptions Options => _options.CurrentValue;
35 |
36 | ///
37 | public async Task HandleResultAsync(
38 | FunctionAuthorizationContext context,
39 | HttpContext httpContext,
40 | Func? onSuccess = null)
41 | where TContext : class
42 | {
43 | Check.NotNull(context, nameof(context));
44 | Check.NotNull(httpContext, nameof(httpContext));
45 |
46 | if (context.Result.Succeeded)
47 | {
48 | if (onSuccess is not null)
49 | {
50 | await onSuccess(context.UnderlyingContext);
51 | }
52 |
53 | return;
54 | }
55 |
56 | if (context.Result.Challenged)
57 | {
58 | if (context.Policy.AuthenticationSchemes.Count > 0)
59 | {
60 | foreach (var scheme in context.Policy.AuthenticationSchemes)
61 | {
62 | await httpContext.ChallengeAsync(scheme);
63 | }
64 | }
65 | else
66 | {
67 | await httpContext.ChallengeAsync();
68 | }
69 | }
70 | else if (context.Result.Forbidden)
71 | {
72 | if (context.Policy.AuthenticationSchemes.Count > 0)
73 | {
74 | foreach (var scheme in context.Policy.AuthenticationSchemes)
75 | {
76 | await httpContext.ForbidAsync(scheme);
77 | }
78 | }
79 | else
80 | {
81 | await httpContext.ForbidAsync();
82 | }
83 | }
84 |
85 | await HandleFailureAsync(httpContext, context.Result);
86 | }
87 |
88 | // Writing default results for forbidden and challenged
89 | private async Task HandleFailureAsync(HttpContext context, PolicyAuthorizationResult result)
90 | {
91 | if (Options.WriteHttpStatusToResponse && !context.Response.HasStarted)
92 | {
93 | var httpResult = default(IActionResult);
94 |
95 | if (result.Forbidden)
96 | {
97 | httpResult = new AuthorizationFailureResult(HttpStatusCode.Forbidden);
98 | }
99 | else if (result.Challenged)
100 | {
101 | httpResult = new AuthorizationFailureResult(HttpStatusCode.Unauthorized);
102 | }
103 |
104 | await httpResult!.ExecuteResultAsync(new ActionContext(context, context.GetRouteData(), new ActionDescriptor()));
105 | }
106 | }
107 |
108 | private class AuthorizationFailureResult : ObjectResult
109 | {
110 | public AuthorizationFailureResult(HttpStatusCode statusCode) : base(statusCode.ToString())
111 | {
112 | }
113 | }
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/src/abstractions/IFunctionsAuthorizationProvider.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using System.Threading.Tasks;
6 | using Microsoft.AspNetCore.Authorization;
7 |
8 | namespace DarkLoop.Azure.Functions.Authorization
9 | {
10 | ///
11 | /// Provides a bridge between Authorization rules and filter cache.
12 | ///
13 | public interface IFunctionsAuthorizationProvider
14 | {
15 | ///
16 | /// Returns the authorization filter for the given function.
17 | ///
18 | /// The name of the function.
19 | /// The to be used to construct the policy.
20 | /// It's recommended to cache the value in this method before returning it, as this method is called for every function invocation.
21 | /// A non-null authorization filter for the function.
22 | Task GetAuthorizationAsync(string functionName, IAuthorizationPolicyProvider policyProvider);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/abstractions/IFunctionsAuthorizationResultHandler.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using System;
6 | using System.Threading.Tasks;
7 | using Microsoft.AspNetCore.Http;
8 |
9 | namespace DarkLoop.Azure.Functions.Authorization
10 | {
11 | ///
12 | /// Handles the result of the authorization process.
13 | ///
14 | internal interface IFunctionsAuthorizationResultHandler
15 | {
16 | ///
17 | /// Handles the result of the authorization process.
18 | ///
19 | /// The function authorization context.
20 | /// The for the current request.
21 | /// The action to execute if the authorization process succeeded.
22 | ///
23 | Task HandleResultAsync(
24 | FunctionAuthorizationContext authorizationContext, HttpContext httpContext, Func? onSuccess = null)
25 | where TContext : class;
26 | }
27 | }
--------------------------------------------------------------------------------
/src/abstractions/Internal/Check.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using System;
6 | using System.Collections.Generic;
7 | using System.Diagnostics.CodeAnalysis;
8 |
9 | namespace DarkLoop.Azure.Functions.Authorization.Internal
10 | {
11 | [ExcludeFromCodeCoverage]
12 | internal class Check
13 | {
14 | internal static void NotNull(object value, string name, string? message = null)
15 | {
16 | if (value == null)
17 | {
18 | throw new ArgumentNullException(name, message);
19 | }
20 | }
21 |
22 | internal static void NotNullOrWhiteSpace(string value, string name, string? message = null)
23 | {
24 | if (string.IsNullOrWhiteSpace(value))
25 | {
26 | throw new ArgumentException(message, name);
27 | }
28 | }
29 |
30 | internal static void All(IEnumerable sequence, Action action)
31 | {
32 | foreach (var item in sequence)
33 | {
34 | action(item);
35 | }
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/abstractions/Internal/FunctionsAuthorizationOptionsExtensions.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using System;
6 | using System.Linq;
7 | using System.Reflection;
8 | using DarkLoop.Azure.Functions.Authorization.Internal;
9 | using Microsoft.AspNetCore.Authorization;
10 |
11 | namespace DarkLoop.Azure.Functions.Authorization
12 | {
13 | // This functionality can be exposed later through a builder to define the authorization rules for the functions
14 | // without the need to use the attributes making it more performant and flexible.
15 | internal static class FunctionsAuthorizationOptionsExtensions
16 | {
17 | ///
18 | /// Registers all the functions in the specified .
19 | ///
20 | /// The current options.
21 | /// The type containing the functions.
22 | /// A value indicating whether the function declaring type is already registered.
23 | /// Return a to keep configuring.
24 | internal static FunctionAuthorizationMetadata SetTypeAuthorizationInfo(
25 | this FunctionsAuthorizationOptions options, Type declaringType, out bool existing)
26 | {
27 | Check.NotNull(declaringType, nameof(declaringType));
28 |
29 | return options.AuthorizationMetadata.Add(declaringType, out existing);
30 | }
31 |
32 | ///
33 | /// Registers the function with the specified name in
34 | /// in the type specified in .
35 | ///
36 | /// The current options.
37 | /// The name of the function.
38 | /// The type declaring the function.
39 | /// Return a to keep configuring.
40 | internal static FunctionAuthorizationMetadata SetFunctionAuthorizationInfo(
41 | this FunctionsAuthorizationOptions options, string functionName, Type declaringType)
42 | {
43 | Check.NotNullOrWhiteSpace(functionName, nameof(functionName));
44 | Check.NotNull(declaringType, nameof(declaringType));
45 |
46 | return options.AuthorizationMetadata.Add(functionName, declaringType);
47 | }
48 |
49 | ///
50 | internal static bool IsFunctionRegistered(this FunctionsAuthorizationOptions options, string functionName)
51 | {
52 | return options.AuthorizationMetadata.IsFunctionRegistered(functionName);
53 | }
54 |
55 | ///
56 | /// Registers the authorization metadata for the function extracted from attribute.
57 | ///
58 | /// The type of authorization attribute to lookup.
59 | /// The current options.
60 | /// The name of the function.
61 | /// The type declaring the function.
62 | /// The entry point method for the function.
63 | internal static void RegisterFunctionAuthorizationAttributesMetadata(
64 | this FunctionsAuthorizationOptions options, string functionName, Type declaringType, MethodInfo functionMethod)
65 | where TAuthAttribute : Attribute, IAuthorizeData
66 | {
67 | var typeMetadata = options
68 | .SetTypeAuthorizationInfo(declaringType, out var typeAlreadyRegistered);
69 |
70 | if (!typeAlreadyRegistered)
71 | {
72 | var classAuthAttributes = declaringType.GetCustomAttributes().ToArray();
73 | var classAllowAnonymous = declaringType.GetCustomAttribute();
74 |
75 | if (classAuthAttributes.Length > 0)
76 | {
77 | typeMetadata.AddAuthorizeData(classAuthAttributes);
78 | }
79 |
80 | if (classAllowAnonymous is not null)
81 | {
82 | typeMetadata.AllowAnonymousAccess();
83 | }
84 | }
85 |
86 | var methodAuthAttributes = functionMethod.GetCustomAttributes().ToArray();
87 | var methodAllowAnonymous = functionMethod.GetCustomAttribute();
88 | var methodMetadata = options
89 | .SetFunctionAuthorizationInfo(functionName, declaringType);
90 |
91 | if (methodAuthAttributes.Length > 0)
92 | {
93 | methodMetadata.AddAuthorizeData(methodAuthAttributes);
94 | }
95 |
96 | if (methodAllowAnonymous is not null)
97 | {
98 | methodMetadata.AllowAnonymousAccess();
99 | }
100 | }
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/src/abstractions/Internal/FunctionsFeatureCollectionExtension.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using Microsoft.AspNetCore.Authentication;
6 | using Microsoft.AspNetCore.Http.Features;
7 | using Microsoft.AspNetCore.Http.Features.Authentication;
8 |
9 | namespace DarkLoop.Azure.Functions.Authorization.Internal
10 | {
11 | // This functionality is used internally to emulate Asp.net's treatment of AuthenticateResult
12 | internal static class FunctionsFeatureCollectionExtension
13 | {
14 | ///
15 | /// Store the given AuthenticateResult in the IFeatureCollection accessible via
16 | /// IAuthenticateResultFeature and IHttpAuthenticationFeature
17 | ///
18 | /// The feature collection to add to
19 | /// The authentication to expose in the feature collection
20 | /// The object associated with the features
21 | public static FunctionAuthorizationFeature SetAuthenticationFeatures(this IFeatureCollection features, AuthenticateResult result)
22 | {
23 | // A single object is used to handle both of these features so that they stay in sync.
24 | // This is in line with what asp core normally does.
25 | var feature = new FunctionAuthorizationFeature(result);
26 |
27 | features.Set(feature);
28 | features.Set(feature);
29 |
30 | return feature;
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/abstractions/Internal/KeyedMonitor.cs:
--------------------------------------------------------------------------------
1 | //
2 | // Copyright (c) DarkLoop. All rights reserved.
3 | //
4 |
5 | using System;
6 | using System.Collections.Concurrent;
7 | using System.Linq;
8 | using System.Threading;
9 | using System.Threading.Tasks;
10 |
11 | namespace DarkLoop.Azure.Functions.Authorization.Internal
12 | {
13 | ///
14 | /// Provides a way to monitor a key and block other threads from entering the same key.
15 | ///
16 | internal static class KeyedMonitor
17 | {
18 | private static readonly ConcurrentDictionary