@@ -10,12 +10,14 @@ namespace LearningHub.NHS.OpenAPI
1010{
1111 using System . Collections . Generic ;
1212 using System . IO ;
13+ using AspNetCore . Authentication . ApiKey ;
1314 using LearningHub . NHS . OpenAPI . Auth ;
1415 using LearningHub . NHS . OpenAPI . Configuration ;
1516 using LearningHub . NHS . OpenAPI . Middleware ;
1617 using LearningHub . Nhs . OpenApi . Repositories ;
1718 using LearningHub . Nhs . OpenApi . Repositories . EntityFramework ;
1819 using LearningHub . Nhs . OpenApi . Services ;
20+ using Microsoft . AspNetCore . Authentication ;
1921 using Microsoft . AspNetCore . Authentication . JwtBearer ;
2022 using Microsoft . AspNetCore . Builder ;
2123 using Microsoft . AspNetCore . Hosting ;
@@ -57,17 +59,17 @@ public void ConfigureServices(IServiceCollection services)
5759
5860 services . AddApiKeyAuth ( ) ;
5961
60- services . AddAuthentication ( JwtBearerDefaults . AuthenticationScheme )
62+ services . AddAuthentication ( )
6163 . AddJwtBearer ( options =>
6264 {
63- options . Authority = this . Configuration . GetValue < string > ( "LearningHUbAuthServiceConfig:Authority" ) ;
64- options . TokenValidationParameters = new TokenValidationParameters ( )
65- {
66- NameClaimType = "given_name" ,
67- RoleClaimType = "role" ,
68- ValidateAudience = true ,
69- ValidAudiences = new List < string > { "learninghubopenapi" , "learninghubapi" } ,
70- } ;
65+ options . Authority = this . Configuration . GetValue < string > ( "LearningHUbAuthServiceConfig:Authority" ) ;
66+ options . TokenValidationParameters = new TokenValidationParameters ( )
67+ {
68+ NameClaimType = "given_name" ,
69+ RoleClaimType = "role" ,
70+ ValidateAudience = true ,
71+ ValidAudiences = new List < string > { "learninghubopenapi" , "learninghubapi" } ,
72+ } ;
7173 } ) ;
7274
7375 services . AddCustomMiddleware ( ) ;
@@ -151,6 +153,24 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
151153 app . UseDeveloperExceptionPage ( ) ;
152154 }
153155
156+ app . Use ( async ( context , next ) =>
157+ {
158+ // Check context headers to determine which authentication scheme is appropriate
159+ string scheme = ApiKeyDefaults . AuthenticationScheme ;
160+ if ( context . Request . Headers . Keys . Contains ( "Authorization" ) )
161+ {
162+ scheme = JwtBearerDefaults . AuthenticationScheme ;
163+ }
164+
165+ var result = await context . AuthenticateAsync ( scheme ) ;
166+ if ( result . Succeeded )
167+ {
168+ context . User = result . Principal ;
169+ }
170+
171+ await next ( ) ;
172+ } ) ;
173+
154174 app . UseStaticFiles ( new StaticFileOptions
155175 {
156176 FileProvider = new PhysicalFileProvider ( Path . Combine ( env . ContentRootPath , "SwaggerDefinitions" ) ) ,
0 commit comments