├── .gitignore
├── CWiz.ClientCertificateMiddleware
├── CWiz.ClientCertificateMiddleware.csproj
├── CertficateAuthenticationOptions.cs
├── CertificateAuthenticationDefaults.cs
├── CertificateAuthenticationExtensions.cs
├── CertificateAuthenticationHandler.cs
└── CertificateAuthenticationPostConfigureOptions.cs
├── ClientCertificateMiddlewareDemo.sln
├── ClientCertificateMiddlewareDemo
├── ClientCertificateMiddlewareDemo.csproj
├── Controllers
│ ├── AdminController.cs
│ ├── AnyoneController.cs
│ └── UserController.cs
├── Program.cs
├── Properties
│ └── launchSettings.json
├── Startup.cs
├── app.config
├── appsettings.Development.json
├── appsettings.Staging.json
└── appsettings.json
├── LICENSE
├── README.md
└── project.props
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 | [Ll]og/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | artifacts/
46 |
47 | *_i.c
48 | *_p.c
49 | *_i.h
50 | *.ilk
51 | *.meta
52 | *.obj
53 | *.pch
54 | *.pdb
55 | *.pgc
56 | *.pgd
57 | *.rsp
58 | *.sbr
59 | *.tlb
60 | *.tli
61 | *.tlh
62 | *.tmp
63 | *.tmp_proj
64 | *.log
65 | *.vspscc
66 | *.vssscc
67 | .builds
68 | *.pidb
69 | *.svclog
70 | *.scc
71 |
72 | # Chutzpah Test files
73 | _Chutzpah*
74 |
75 | # Visual C++ cache files
76 | ipch/
77 | *.aps
78 | *.ncb
79 | *.opendb
80 | *.opensdf
81 | *.sdf
82 | *.cachefile
83 | *.VC.db
84 | *.VC.VC.opendb
85 |
86 | # Visual Studio profiler
87 | *.psess
88 | *.vsp
89 | *.vspx
90 | *.sap
91 |
92 | # TFS 2012 Local Workspace
93 | $tf/
94 |
95 | # Guidance Automation Toolkit
96 | *.gpState
97 |
98 | # ReSharper is a .NET coding add-in
99 | _ReSharper*/
100 | *.[Rr]e[Ss]harper
101 | *.DotSettings.user
102 |
103 | # JustCode is a .NET coding add-in
104 | .JustCode
105 |
106 | # TeamCity is a build add-in
107 | _TeamCity*
108 |
109 | # DotCover is a Code Coverage Tool
110 | *.dotCover
111 |
112 | # NCrunch
113 | _NCrunch_*
114 | .*crunch*.local.xml
115 | nCrunchTemp_*
116 |
117 | # MightyMoose
118 | *.mm.*
119 | AutoTest.Net/
120 |
121 | # Web workbench (sass)
122 | .sass-cache/
123 |
124 | # Installshield output folder
125 | [Ee]xpress/
126 |
127 | # DocProject is a documentation generator add-in
128 | DocProject/buildhelp/
129 | DocProject/Help/*.HxT
130 | DocProject/Help/*.HxC
131 | DocProject/Help/*.hhc
132 | DocProject/Help/*.hhk
133 | DocProject/Help/*.hhp
134 | DocProject/Help/Html2
135 | DocProject/Help/html
136 |
137 | # Click-Once directory
138 | publish/
139 |
140 | # Publish Web Output
141 | *.[Pp]ublish.xml
142 | *.azurePubxml
143 | # TODO: Comment the next line if you want to checkin your web deploy settings
144 | # but database connection strings (with potential passwords) will be unencrypted
145 | *.pubxml
146 | *.publishproj
147 |
148 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
149 | # checkin your Azure Web App publish settings, but sensitive information contained
150 | # in these scripts will be unencrypted
151 | PublishScripts/
152 |
153 | # NuGet Packages
154 | *.nupkg
155 | # The packages folder can be ignored because of Package Restore
156 | **/packages/*
157 | # except build/, which is used as an MSBuild target.
158 | !**/packages/build/
159 | # Uncomment if necessary however generally it will be regenerated when needed
160 | #!**/packages/repositories.config
161 | # NuGet v3's project.json files produces more ignoreable files
162 | *.nuget.props
163 | *.nuget.targets
164 |
165 | # Microsoft Azure Build Output
166 | csx/
167 | *.build.csdef
168 |
169 | # Microsoft Azure Emulator
170 | ecf/
171 | rcf/
172 |
173 | # Windows Store app package directories and files
174 | AppPackages/
175 | BundleArtifacts/
176 | Package.StoreAssociation.xml
177 | _pkginfo.txt
178 |
179 | # Visual Studio cache files
180 | # files ending in .cache can be ignored
181 | *.[Cc]ache
182 | # but keep track of directories ending in .cache
183 | !*.[Cc]ache/
184 |
185 | # Others
186 | ClientBin/
187 | ~$*
188 | *~
189 | *.dbmdl
190 | *.dbproj.schemaview
191 | *.pfx
192 | *.publishsettings
193 | node_modules/
194 | orleans.codegen.cs
195 |
196 | # Since there are multiple workflows, uncomment next line to ignore bower_components
197 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
198 | #bower_components/
199 |
200 | # RIA/Silverlight projects
201 | Generated_Code/
202 |
203 | # Backup & report files from converting an old project file
204 | # to a newer Visual Studio version. Backup files are not needed,
205 | # because we have git ;-)
206 | _UpgradeReport_Files/
207 | Backup*/
208 | UpgradeLog*.XML
209 | UpgradeLog*.htm
210 |
211 | # SQL Server files
212 | *.mdf
213 | *.ldf
214 |
215 | # Business Intelligence projects
216 | *.rdl.data
217 | *.bim.layout
218 | *.bim_*.settings
219 |
220 | # Microsoft Fakes
221 | FakesAssemblies/
222 |
223 | # GhostDoc plugin setting file
224 | *.GhostDoc.xml
225 |
226 | # Node.js Tools for Visual Studio
227 | .ntvs_analysis.dat
228 |
229 | # Visual Studio 6 build log
230 | *.plg
231 |
232 | # Visual Studio 6 workspace options file
233 | *.opt
234 |
235 | # Visual Studio LightSwitch build output
236 | **/*.HTMLClient/GeneratedArtifacts
237 | **/*.DesktopClient/GeneratedArtifacts
238 | **/*.DesktopClient/ModelManifest.xml
239 | **/*.Server/GeneratedArtifacts
240 | **/*.Server/ModelManifest.xml
241 | _Pvt_Extensions
242 |
243 | # Paket dependency manager
244 | .paket/paket.exe
245 | paket-files/
246 |
247 | # FAKE - F# Make
248 | .fake/
249 |
250 | # JetBrains Rider
251 | .idea/
252 | *.sln.iml
253 |
--------------------------------------------------------------------------------
/CWiz.ClientCertificateMiddleware/CWiz.ClientCertificateMiddleware.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Xavier John
5 | $(Company)
6 | Client Certificate Middleware for .net core.
7 | netstandard2.0
8 | True
9 | Client Certificate Middleware
10 | $(Product)
11 | https://github.com/xavierjohn/ClientCertificateMiddleware
12 | https://github.com/xavierjohn/ClientCertificateMiddleware
13 | C#
14 | https://github.com/xavierjohn/ClientCertificateMiddleware/blob/master/LICENSE
15 | 2017 $(Company)
16 | 2.0.0
17 | AspNetCore;Authentication;Authorization;Client;Certificate;
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/CWiz.ClientCertificateMiddleware/CertficateAuthenticationOptions.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authentication;
2 |
3 | namespace CWiz.ClientCertificateMiddleware
4 | {
5 | public class CertficateAuthenticationOptions : AuthenticationSchemeOptions
6 | {
7 | ///
8 | /// Gets or sets the challenge to put in the "WWW-Authenticate" header.
9 | ///
10 | public string Challenge { get; set; } = CertificateAuthenticationDefaults.AuthenticationScheme;
11 |
12 | public CertificateAndRoles[] CertificatesAndRoles { get; set; }
13 |
14 | public class CertificateAndRoles
15 | {
16 | public string Subject { get; set; }
17 | public string Issuer { get; set; }
18 | public string[] Roles { get; set; }
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/CWiz.ClientCertificateMiddleware/CertificateAuthenticationDefaults.cs:
--------------------------------------------------------------------------------
1 |
2 | namespace CWiz.ClientCertificateMiddleware
3 | {
4 | ///
5 | /// Default values used by Certificate authentication.
6 | ///
7 | public static class CertificateAuthenticationDefaults
8 | {
9 | ///
10 | /// Default value for AuthenticationScheme property in the CertificateAuthenticationOptions
11 | ///
12 | public const string AuthenticationScheme = "Certificate";
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/CWiz.ClientCertificateMiddleware/CertificateAuthenticationExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Microsoft.AspNetCore.Authentication;
3 | using Microsoft.Extensions.DependencyInjection.Extensions;
4 | using Microsoft.Extensions.Options;
5 | using Microsoft.Extensions.DependencyInjection;
6 |
7 | namespace CWiz.ClientCertificateMiddleware
8 | {
9 | public static class CertificateAuthenticationExtensions
10 | {
11 | public static AuthenticationBuilder AddCertificateAuthentication(this AuthenticationBuilder builder, Action configureOptions)
12 | {
13 | builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton, CertificateAuthenticationPostConfigureOptions>());
14 | return builder.AddScheme(CertificateAuthenticationDefaults.AuthenticationScheme, "Certificate Authentication", configureOptions);
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/CWiz.ClientCertificateMiddleware/CertificateAuthenticationHandler.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Authentication;
2 | using Microsoft.AspNetCore.DataProtection;
3 | using Microsoft.Extensions.Logging;
4 | using Microsoft.Extensions.Options;
5 | using System.Collections.Generic;
6 | using System.Linq;
7 | using System.Security.Claims;
8 | using System.Security.Cryptography.X509Certificates;
9 | using System.Text.Encodings.Web;
10 | using System.Threading.Tasks;
11 |
12 | namespace CWiz.ClientCertificateMiddleware
13 | {
14 | internal class CertificateAuthenticationHandler : AuthenticationHandler
15 | {
16 | public CertificateAuthenticationHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, IDataProtectionProvider dataProtection, ISystemClock clock)
17 | : base(options, logger, encoder, clock)
18 | { }
19 |
20 | protected override Task HandleAuthenticateAsync()
21 | {
22 | var certificate = Context.Connection.ClientCertificate;
23 | if (certificate != null && certificate.Verify())
24 | {
25 | var roles = GetRolesFromFirstMatchingCertificate(certificate);
26 | if (roles?.Length > 0)
27 | {
28 | var claims = new List();
29 | foreach (var role in roles)
30 | {
31 | claims.Add(new Claim(ClaimTypes.Role, role));
32 | }
33 |
34 | var userIdentity = new ClaimsIdentity(claims, Options.Challenge);
35 | var userPrincipal = new ClaimsPrincipal(userIdentity);
36 | var ticket = new AuthenticationTicket(userPrincipal, new AuthenticationProperties(), Options.Challenge);
37 | return Task.FromResult(AuthenticateResult.Success(ticket));
38 | }
39 | }
40 |
41 | return Task.FromResult(AuthenticateResult.NoResult());
42 | }
43 |
44 | private string[] GetRolesFromFirstMatchingCertificate(X509Certificate2 certificate)
45 | {
46 | var roles = (Options.CertificatesAndRoles
47 | .Where(r => r.Issuer == certificate.Issuer && r.Subject == certificate.Subject)
48 | .Select(r => r.Roles)).FirstOrDefault();
49 |
50 | return roles;
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/CWiz.ClientCertificateMiddleware/CertificateAuthenticationPostConfigureOptions.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.Options;
2 |
3 | namespace CWiz.ClientCertificateMiddleware
4 | {
5 | ///
6 | /// Used to setup defaults for all .
7 | ///
8 | public class CertificateAuthenticationPostConfigureOptions : IPostConfigureOptions
9 | {
10 | ///
11 | /// Invoked to post configure a CertficateAuthenticationOptions instance.
12 | ///
13 | /// The name of the options instance being configured.
14 | /// The options instance to configure.
15 | public void PostConfigure(string name, CertficateAuthenticationOptions options)
16 | {
17 |
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/ClientCertificateMiddlewareDemo.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.26730.3
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClientCertificateMiddlewareDemo", "ClientCertificateMiddlewareDemo\ClientCertificateMiddlewareDemo.csproj", "{125815E9-7A68-4F9D-9F0A-5891C6707436}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CWiz.ClientCertificateMiddleware", "CWiz.ClientCertificateMiddleware\CWiz.ClientCertificateMiddleware.csproj", "{4A3ADE26-00AC-4610-BC8D-F003C6410307}"
9 | EndProject
10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C8BBE2B1-8B75-46C7-A9B3-0E7E21826BD2}"
11 | ProjectSection(SolutionItems) = preProject
12 | project.props = project.props
13 | README.md = README.md
14 | EndProjectSection
15 | EndProject
16 | Global
17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
18 | Debug|Any CPU = Debug|Any CPU
19 | Release|Any CPU = Release|Any CPU
20 | EndGlobalSection
21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
22 | {125815E9-7A68-4F9D-9F0A-5891C6707436}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {125815E9-7A68-4F9D-9F0A-5891C6707436}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {125815E9-7A68-4F9D-9F0A-5891C6707436}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {125815E9-7A68-4F9D-9F0A-5891C6707436}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {4A3ADE26-00AC-4610-BC8D-F003C6410307}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {4A3ADE26-00AC-4610-BC8D-F003C6410307}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {4A3ADE26-00AC-4610-BC8D-F003C6410307}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {4A3ADE26-00AC-4610-BC8D-F003C6410307}.Release|Any CPU.Build.0 = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(SolutionProperties) = preSolution
32 | HideSolutionNode = FALSE
33 | EndGlobalSection
34 | GlobalSection(ExtensibilityGlobals) = postSolution
35 | SolutionGuid = {A200B8D7-401C-4CE1-9995-31EAB137A6D4}
36 | EndGlobalSection
37 | EndGlobal
38 |
--------------------------------------------------------------------------------
/ClientCertificateMiddlewareDemo/ClientCertificateMiddlewareDemo.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net461
5 | win7-x86
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/ClientCertificateMiddlewareDemo/Controllers/AdminController.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using Microsoft.AspNetCore.Mvc;
6 | using Microsoft.AspNetCore.Authorization;
7 |
8 | namespace ClientCertificateMiddlewareDemo.Controllers
9 | {
10 | [Route("api/[controller]")]
11 | [Authorize(Policy = "CanAccessAdminMethods")]
12 | public class AdminController : Controller
13 | {
14 | // GET api/values
15 | [HttpGet]
16 | public IEnumerable Get()
17 | {
18 | return new string[] { "admin1", "admin2" };
19 | }
20 |
21 | // GET api/values/5
22 | [HttpGet("{id}")]
23 | public string Get(int id)
24 | {
25 | return "admin";
26 | }
27 |
28 | // POST api/values
29 | [HttpPost]
30 | public void Post([FromBody]string value)
31 | {
32 | }
33 |
34 | // PUT api/values/5
35 | [HttpPut("{id}")]
36 | public void Put(int id, [FromBody]string value)
37 | {
38 | }
39 |
40 | // DELETE api/values/5
41 | [HttpDelete("{id}")]
42 | public void Delete(int id)
43 | {
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/ClientCertificateMiddlewareDemo/Controllers/AnyoneController.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using Microsoft.AspNetCore.Mvc;
6 |
7 | namespace ClientCertificateMiddlewareDemo.Controllers
8 | {
9 | [Route("api/[controller]")]
10 | public class AnyoneController : Controller
11 | {
12 | // GET api/values
13 | [HttpGet]
14 | public IEnumerable Get()
15 | {
16 | return new string[] { "anyone1", "anyone2" };
17 | }
18 |
19 | // GET api/values/5
20 | [HttpGet("{id}")]
21 | public string Get(int id)
22 | {
23 | return "anyone";
24 | }
25 |
26 | // POST api/values
27 | [HttpPost]
28 | public void Post([FromBody]string value)
29 | {
30 | }
31 |
32 | // PUT api/values/5
33 | [HttpPut("{id}")]
34 | public void Put(int id, [FromBody]string value)
35 | {
36 | }
37 |
38 | // DELETE api/values/5
39 | [HttpDelete("{id}")]
40 | public void Delete(int id)
41 | {
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/ClientCertificateMiddlewareDemo/Controllers/UserController.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using Microsoft.AspNetCore.Mvc;
6 | using Microsoft.AspNetCore.Authorization;
7 |
8 | namespace ClientCertificateMiddlewareDemo.Controllers
9 | {
10 | [Route("api/[controller]")]
11 | [Authorize(Policy = "CanAccessUserMethods")]
12 | public class UserController : Controller
13 | {
14 | // GET api/values
15 | [HttpGet]
16 | public IEnumerable Get()
17 | {
18 | return new string[] { "user1", "user2" };
19 | }
20 |
21 | // GET api/values/5
22 | [HttpGet("{id}")]
23 | public string Get(int id)
24 | {
25 | return "user";
26 | }
27 |
28 | // POST api/values
29 | [HttpPost]
30 | public void Post([FromBody]string value)
31 | {
32 | }
33 |
34 | // PUT api/values/5
35 | [HttpPut("{id}")]
36 | public void Put(int id, [FromBody]string value)
37 | {
38 | }
39 |
40 | // DELETE api/values/5
41 | [HttpDelete("{id}")]
42 | public void Delete(int id)
43 | {
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/ClientCertificateMiddlewareDemo/Program.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore;
2 | using Microsoft.AspNetCore.Builder;
3 | using Microsoft.AspNetCore.Hosting;
4 | using Microsoft.AspNetCore.Server.Kestrel.Https;
5 | using Microsoft.Extensions.Configuration;
6 | using System.IO;
7 | using System.Net;
8 | using System.Security.Cryptography.X509Certificates;
9 |
10 | namespace ClientCertificateMiddlewareDemo
11 | {
12 | public class Program
13 | {
14 | public static void Main(string[] args)
15 | {
16 | var whb = WebHost.CreateDefaultBuilder(args);
17 |
18 | var environment = whb.GetSetting("environment");
19 | var subjectName = GetCertificateSubjectNameBasedOnEnvironment(environment);
20 | var certificate = GetServiceCertificate(subjectName);
21 |
22 | var host = whb.UseStartup()
23 | .UseKestrel(options =>
24 | {
25 | options.Listen(new IPEndPoint(IPAddress.Loopback, 4430), listenOptions =>
26 | {
27 | var httpsConnectionAdapterOptions = new HttpsConnectionAdapterOptions()
28 | {
29 | ClientCertificateMode = ClientCertificateMode.AllowCertificate,
30 | SslProtocols = System.Security.Authentication.SslProtocols.Tls,
31 | ServerCertificate = certificate
32 | };
33 | listenOptions.UseHttps(httpsConnectionAdapterOptions);
34 | });
35 | })
36 | .Build();
37 | host.Run();
38 | }
39 |
40 | private static X509Certificate2 GetServiceCertificate(string subjectName)
41 | {
42 | using (var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser))
43 | {
44 | certStore.Open(OpenFlags.ReadOnly);
45 | var certCollection = certStore.Certificates.Find(
46 | X509FindType.FindBySubjectDistinguishedName, subjectName, true);
47 | // Get the first certificate
48 | X509Certificate2 certificate = null;
49 | if (certCollection.Count > 0)
50 | {
51 | certificate = certCollection[0];
52 | }
53 | return certificate;
54 | }
55 | }
56 |
57 | private static string GetCertificateSubjectNameBasedOnEnvironment(string environment)
58 | {
59 | var builder = new ConfigurationBuilder()
60 | .SetBasePath(Directory.GetCurrentDirectory())
61 | .AddJsonFile($"appsettings.{environment}.json", optional: false);
62 |
63 | var configuration = builder.Build();
64 | return configuration["ServerCertificateSubject"];
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/ClientCertificateMiddlewareDemo/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "iisSettings": {
3 | "windowsAuthentication": false,
4 | "anonymousAuthentication": true,
5 | "iisExpress": {
6 | "applicationUrl": "http://localhost:1647/",
7 | "sslPort": 44306
8 | }
9 | },
10 | "profiles": {
11 | "IIS Express": {
12 | "commandName": "IISExpress",
13 | "launchBrowser": true,
14 | "launchUrl": "api/values",
15 | "environmentVariables": {
16 | "ASPNETCORE_ENVIRONMENT": "Development"
17 | }
18 | },
19 | "ClientCertificateMiddlewareDemo": {
20 | "commandName": "Project",
21 | "launchBrowser": true,
22 | "launchUrl": "api/values",
23 | "environmentVariables": {
24 | "ASPNETCORE_ENVIRONMENT": "Development"
25 | },
26 | "applicationUrl": "http://localhost:1648"
27 | }
28 | }
29 | }
--------------------------------------------------------------------------------
/ClientCertificateMiddlewareDemo/Startup.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using Microsoft.AspNetCore.Builder;
3 | using Microsoft.AspNetCore.Hosting;
4 | using Microsoft.Extensions.Configuration;
5 | using Microsoft.Extensions.DependencyInjection;
6 | using Microsoft.Extensions.Logging;
7 | using CWiz.ClientCertificateMiddleware;
8 | using System;
9 |
10 | namespace ClientCertificateMiddlewareDemo
11 | {
12 | public class Startup
13 | {
14 | public Startup(IHostingEnvironment env)
15 | {
16 | var builder = new ConfigurationBuilder()
17 | .SetBasePath(env.ContentRootPath)
18 | .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
19 | .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
20 | .AddEnvironmentVariables();
21 | Configuration = builder.Build();
22 | }
23 |
24 | public IConfigurationRoot Configuration { get; }
25 |
26 |
27 | // This method gets called by the runtime. Use this method to add services to the container.
28 | public void ConfigureServices(IServiceCollection services)
29 | {
30 | // Add framework services.
31 | services.AddMvc();
32 | services.AddAuthentication(options =>
33 | {
34 | options.DefaultAuthenticateScheme = CertificateAuthenticationDefaults.AuthenticationScheme;
35 | options.DefaultChallengeScheme = CertificateAuthenticationDefaults.AuthenticationScheme;
36 | })
37 | .AddCertificateAuthentication(certOptions =>
38 | {
39 | var certificateAndRoles = new List();
40 | Configuration.GetSection("AuthorizedCertficatesAndRoles:CertificateAndRoles").Bind(certificateAndRoles);
41 | certOptions.CertificatesAndRoles = certificateAndRoles.ToArray();
42 | });
43 |
44 | services.AddAuthorization(options =>
45 | {
46 | options.AddPolicy("CanAccessAdminMethods", policy => policy.RequireRole("Admin"));
47 | options.AddPolicy("CanAccessUserMethods", policy => policy.RequireRole("User"));
48 | });
49 | }
50 |
51 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
52 | public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
53 | {
54 | loggerFactory.AddConsole(Configuration.GetSection("Logging"));
55 | loggerFactory.AddDebug();
56 | app.UseAuthentication();
57 |
58 | app.UseMvc();
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/ClientCertificateMiddlewareDemo/app.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/ClientCertificateMiddlewareDemo/appsettings.Development.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "IncludeScopes": false,
4 | "LogLevel": {
5 | "Default": "Debug",
6 | "System": "Information",
7 | "Microsoft": "Information"
8 | }
9 | },
10 |
11 | "ServerCertificateSubject": "CN=localhost",
12 |
13 | "AuthorizedCertficatesAndRoles": {
14 | "CertificateAndRoles": [
15 | {
16 | "Subject": "CN=http://user.mylocalmachine",
17 | "Issuer": "CN=http://user.mylocalmachine",
18 | "Roles": [ "User" ]
19 | },
20 | {
21 | "Subject": "CN=http://admin.mylocalmachine",
22 | "Issuer": "CN=http://admin.mylocalmachine",
23 | "Roles": [ "Admin" ]
24 | }
25 | ]
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/ClientCertificateMiddlewareDemo/appsettings.Staging.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "IncludeScopes": false,
4 | "LogLevel": {
5 | "Default": "Debug",
6 | "System": "Information",
7 | "Microsoft": "Information"
8 | }
9 | },
10 |
11 | "ServerCertificateSubject": "CN=localhost",
12 |
13 | "AuthorizedCertficatesAndRoles": {
14 | "CertificateAndRoles": [
15 | {
16 | "Subject": "CN=http://client.localhost.home",
17 | "Issuer": "CN=http://client.localhost.home",
18 | "Roles": [ "User" ]
19 | }
20 | ]
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/ClientCertificateMiddlewareDemo/appsettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "Logging": {
3 | "IncludeScopes": false,
4 | "LogLevel": {
5 | "Default": "Warning"
6 | }
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2017 Xavier
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://www.nuget.org/packages/CWiz.ClientCertificateMiddleware)
2 |
3 | # Client Certificate Authorization Middleware for ASP.NET Core
4 | The Client Certificate Middleware will authorize a request based on the configured AuthorizedCertficatesAndRoles
5 |
6 | Example:
7 | ```sh
8 | "AuthorizedCertficatesAndRoles": {
9 | "CertificateAndRoles": [
10 | {
11 | "Subject": "CN=http://user.mylocalmachine",
12 | "Issuer": "CN=http://user.mylocalmachine",
13 | "Roles": [ "User" ]
14 | },
15 | {
16 | "Subject": "CN=http://admin.mylocalmachine",
17 | "Issuer": "CN=http://admin.mylocalmachine",
18 | "Roles": [ "Admin" ]
19 | }
20 | ]
21 | }
22 | ```
23 |
24 | To run the demonstration, you need to install a certificate and gives its subject in the configuration.
25 | ```sh
26 | "ServerCertificateSubject": "CN=localhost",
27 | ```
28 |
29 | To create a certificate you can run PowerShell as admin and run
30 | ```sh
31 | # Generate server certificate
32 | $cert = New-SelfSignedCertificate -DnsName http://clientcertificatemiddlewaredemo.azurewebsites.net -CertStoreLocation "cert:\LocalMachine\My"
33 | $password = ConvertTo-SecureString -String "your-password" -Force -AsPlainText
34 | Export-PfxCertificate -Cert $cert -FilePath "\temp\clientcertificatemiddlewaredemo.pfx" -Password $password
35 |
36 | # Generate user certificates
37 | $password = ConvertTo-SecureString -String "password" -Force -AsPlainText
38 | $certUser = New-SelfSignedCertificate -DnsName http://user.mylocalmachine -CertStoreLocation "cert:\LocalMachine\My"
39 | $certAdmin = New-SelfSignedCertificate -DnsName http://admin.mylocalmachine -CertStoreLocation "cert:\LocalMachine\My"
40 | Export-PfxCertificate -Cert $certUser -FilePath "\temp\user.mylocalmachine.pfx" -Password $password
41 | Export-PfxCertificate -Cert $certAdmin -FilePath "\temp\admin.mylocalmachine.pfx" -Password $password
42 | ```
43 | On Dev machine, you have to install the certificate to Current User -> Trusted Root Certification Authorities
44 | Otherwise you will see the exception "The remote certificate is invalid according to the validation procedure."
45 |
46 | ## Azure
47 |
48 | ### Import the SSL into Azure.
49 | Go to your Azure Web application
50 | > SSL Certificates
51 | >> Upload Certificate.
52 | >> Note the Thumbprint
53 |
54 | > Application Setting
55 | >> Add WEBSITE_LOAD_CERTIFICATES and the Thumbprint
56 | >> Add ASPNETCORE_ENVIRONMENT and setting like 'Staging'
57 |
58 |
59 | To get the certificates to work, don't run the demo under IIS Express. Instead run under the app 'ClientCertificateMiddlewareDemo'
60 | Refer here for more information.
61 | http://www.blinkingcaret.com/2017/03/01/https-asp-net-core/
62 |
63 |
64 | Here is the code that sets up the use of client certificate
65 | ```sh
66 | .UseKestrel(options =>
67 | {
68 | options.Listen(new IPEndPoint(IPAddress.Loopback, 4430), listenOptions =>
69 | {
70 | var httpsConnectionAdapterOptions = new HttpsConnectionAdapterOptions()
71 | {
72 | ClientCertificateMode = ClientCertificateMode.AllowCertificate,
73 | SslProtocols = System.Security.Authentication.SslProtocols.Tls,
74 | ServerCertificate = certificate
75 | };
76 | listenOptions.UseHttps(httpsConnectionAdapterOptions);
77 | });
78 | })
79 | ```
80 |
--------------------------------------------------------------------------------
/project.props:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | @(ReleaseNotes->'• %(Identity)','%0D%0A')
6 |
7 |
8 |
--------------------------------------------------------------------------------