-
Notifications
You must be signed in to change notification settings - Fork 332
Expand file tree
/
Copy pathWebHostBuilderHelper.cs
More file actions
244 lines (226 loc) · 11.9 KB
/
WebHostBuilderHelper.cs
File metadata and controls
244 lines (226 loc) · 11.9 KB
1
2
3
4
5
6
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Abstractions.TestingHelpers;
using System.Net;
using System.Threading.Tasks;
using Azure.DataApiBuilder.Config;
using Azure.DataApiBuilder.Config.ObjectModel;
using Azure.DataApiBuilder.Core.AuthenticationHelpers;
using Azure.DataApiBuilder.Core.AuthenticationHelpers.AuthenticationSimulator;
using Azure.DataApiBuilder.Core.Authorization;
using Azure.DataApiBuilder.Core.Configurations;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Microsoft.IdentityModel.Tokens;
namespace Azure.DataApiBuilder.Service.Tests.Authentication.Helpers
{
/// <summary>
/// Helps create web host with customized authentication and authorization settings
/// for usage in unit test classes.
/// </summary>
public static class WebHostBuilderHelper
{
private const string AUDIENCE = "d727a7e8-1af4-4ce0-8c56-f3107f10bbfd";
private const string LOCAL_ISSUER = "https://fabrikam.com";
/// <summary>
/// Creates customized webhost with:
/// - DAB's Simulator/ EasyAuth authentication middleware and ClientRoleHeader middleware
/// - dotnet's authorization middleware.
/// </summary>
/// <param name="provider">Runtime configured identity provider name. This is different than the
/// authentication scheme name because the configured value is simpler.</param>
/// <param name="useAuthorizationMiddleware">Whether to include authorization middleware in request pipeline.</param>
/// <returns>IHost to be used to create a TestServer</returns>
public static async Task<IHost> CreateWebHost(
string provider,
bool useAuthorizationMiddleware)
{
MockFileSystem fileSystem = new();
FileSystemRuntimeConfigLoader fileSystemRuntimeConfigLoader = new(new MockFileSystem());
AuthenticationOptions authOptions = new()
{
Provider = provider
};
RuntimeConfig runtimeConfig = RuntimeConfigAuthHelper.CreateTestConfigWithAuthNProvider(authOptions);
fileSystemRuntimeConfigLoader.RuntimeConfig = runtimeConfig;
RuntimeConfigProvider runtimeConfigProvider = new(fileSystemRuntimeConfigLoader);
return await new HostBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder
.UseTestServer()
.ConfigureServices(services =>
{
if (string.Equals(provider, AuthenticationOptions.SIMULATOR_AUTHENTICATION, StringComparison.OrdinalIgnoreCase))
{
services.AddAuthentication(defaultScheme: SimulatorAuthenticationDefaults.AUTHENTICATIONSCHEME)
.AddSimulatorAuthentication();
}
else
{
EasyAuthType easyAuthProvider = (EasyAuthType)Enum.Parse(typeof(EasyAuthType), provider, ignoreCase: true);
services.AddAuthentication()
.AddEasyAuthAuthentication(easyAuthProvider);
}
services.AddSingleton<RuntimeConfigProvider>(sp => runtimeConfigProvider);
// https://github.com/dotnet/aspnetcore/issues/53332#issuecomment-2091861884
// AddRouting() adds required services that .NET8 does not add by default
// Without this, .NET8 fails to resolve the required services for the middleware
// and tests fail.
services.AddRouting();
if (useAuthorizationMiddleware)
{
services.AddAuthorization();
}
})
.ConfigureLogging(o =>
{
o.AddFilter(levelFilter => levelFilter <= LogLevel.Information);
o.AddDebug();
o.AddConsole();
})
.Configure(app =>
{
app.UseAuthentication();
app.UseClientRoleHeaderAuthenticationMiddleware();
if (useAuthorizationMiddleware)
{
app.UseAuthorization();
app.UseClientRoleHeaderAuthorizationMiddleware();
}
// app.Run acts as terminating middleware to return 200 if we reach it. Without this,
// the Middleware pipeline will return 404 by default.
app.Run(async (context) =>
{
context.Response.StatusCode = (int)HttpStatusCode.OK;
await context.Response.WriteAsync("Successful Request");
await context.Response.StartAsync();
});
});
})
.StartAsync();
}
/// <summary>
/// Creates a webhost with
/// - dotnet's authentication/authorization middleware configured with
/// the JwtBearer authentication scheme. Expects a key to be
/// provided which is used to validate the JWT token.
/// - DAB's ClientRoleHeader middleware
/// </summary>
/// <param name="key">Issuer Signing key for JwtBearerOptions</param>
/// <returns>IHost to be used to create a TestServer</returns>
public static async Task<IHost> CreateWebHostCustomIssuer(SecurityKey key)
{
MockFileSystem fileSystem = new();
FileSystemRuntimeConfigLoader fileSystemRuntimeConfigLoader = new(new MockFileSystem());
AuthenticationOptions authOptions = new()
{
Provider = "AzureAD",
Jwt = new(Audience: AUDIENCE, Issuer: LOCAL_ISSUER)
};
RuntimeConfig runtimeConfig = RuntimeConfigAuthHelper.CreateTestConfigWithAuthNProvider(authOptions);
fileSystemRuntimeConfigLoader.RuntimeConfig = runtimeConfig;
RuntimeConfigProvider runtimeConfigProvider = new(fileSystemRuntimeConfigLoader);
return await new HostBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddAuthentication(defaultScheme: JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
// .NET8 change that required and is compatible with .NET6.
// Required so that legacy URL claim types are used.
// https://github.com/dotnet/aspnetcore/issues/52075#issuecomment-1815584839
options.MapInboundClaims = false;
options.Audience = AUDIENCE;
options.TokenValidationParameters = new()
{
// Valiate the JWT Audience (aud) claim
ValidAudience = AUDIENCE,
ValidateAudience = true,
// Validate the JWT Issuer (iss) claim
ValidIssuer = LOCAL_ISSUER,
ValidateIssuer = true,
// The signing key must match
ValidateIssuerSigningKey = true,
IssuerSigningKey = key,
// Lifetime
ValidateLifetime = true,
// Instructs the asp.net core middleware to use the data in the "roles" claim for User.IsInRole()
// See https://learn.microsoft.com/en-us/dotnet/api/system.security.claims.claimsprincipal.isinrole#remarks
RoleClaimType = AuthenticationOptions.ROLE_CLAIM_TYPE
};
});
services.AddAuthorization();
services.AddSingleton<RuntimeConfigProvider>(sp => runtimeConfigProvider);
})
.ConfigureLogging(o =>
{
o.AddFilter(levelFilter => levelFilter <= LogLevel.Information);
o.AddDebug();
o.AddConsole();
})
.Configure(app =>
{
app.UseAuthentication();
app.UseClientRoleHeaderAuthenticationMiddleware();
// app.Run acts as terminating middleware to return 200 if we reach it. Without this,
// the Middleware pipeline will return 404 by default.
app.Run(async (context) =>
{
context.Response.StatusCode = (int)HttpStatusCode.OK;
await context.Response.WriteAsync("Successfully validated token!");
await context.Response.StartAsync();
});
});
})
.StartAsync();
}
/// <summary>
/// Creates the TestServer with the minimum middleware setup necessary to
/// test JwtAuthenticationMiddlware
/// Sends a request with the passed in token to the TestServer created.
/// </summary>
/// <param name="key">The JST signing key to setup the TestServer</param>
/// <param name="token">The JWT value to test against the TestServer</param>
/// <returns>HttpContext with ClaimsPrincipal to inspect.</returns>
public static async Task<HttpContext> SendRequestAndGetHttpContextState(
SecurityKey key,
string token,
string? clientRoleHeader = null)
{
using IHost host = await CreateWebHostCustomIssuer(key);
TestServer server = host.GetTestServer();
return await server.SendAsync(context =>
{
if (token is not null)
{
StringValues headerValue = new(new string[] { $"Bearer {token}" });
KeyValuePair<string, StringValues> authHeader = new("Authorization", headerValue);
context.Request.Headers.Add(authHeader);
}
if (clientRoleHeader is not null)
{
KeyValuePair<string, StringValues> easyAuthHeader =
new(AuthorizationResolver.CLIENT_ROLE_HEADER, clientRoleHeader);
context.Request.Headers.Add(easyAuthHeader);
}
context.Request.Scheme = "https";
});
}
}
}