-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStartup.cs
202 lines (173 loc) · 8.53 KB
/
Startup.cs
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
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;
using System.Linq;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Yarp.ReverseProxy.Transforms;
namespace MaxMelcher.GHEAADProxy
{
// Sets up the ASP.NET application with the reverse proxy enabled.
public class Startup
{
public Startup(IConfiguration configuration)
{
// Default configuration comes from AppSettings.json file in project/output
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add capabilities to
// the web application via services in the DI container.
public void ConfigureServices(IServiceCollection services)
{
// Add the reverse proxy to capability to the server
var proxyBuilder = services.AddReverseProxy().AddTransforms(builderContext =>
{
builderContext.AddRequestTransform(transformContext =>
{
var proxyHeaders = transformContext.ProxyRequest.Headers;
proxyHeaders.Remove("MFA");
if (proxyHeaders.TryGetValues("BASIC", out var basic) &&
proxyHeaders.TryGetValues("AUTHORIZATION", out var auth))
{
proxyHeaders.Remove("AUTHORIZATION");
proxyHeaders.Remove("BASIC");
proxyHeaders.TryAddWithoutValidation("AUTHORIZATION", basic);
Console.WriteLine("!!! REWROTE TOKEN TO GHE");
}
else if (proxyHeaders.TryGetValues("BASIC", out var basic2))
{
proxyHeaders.Remove("BASIC");
proxyHeaders.TryAddWithoutValidation("AUTHORIZATION", basic);
Console.WriteLine("!!! REWROTE TOKEN TO GHE (OAUTH)");
}
else if (proxyHeaders.TryGetValues("AUTHORIZATION", out var auth2))
{
if (auth2.Any(x => x.ToLower().StartsWith("bearer") && x.Length > 50))
{
proxyHeaders.Remove("AUTHORIZATION");
Console.WriteLine("!!! REMOVED OAUTH TOKEN TO GHE");
}
}
foreach (var header in proxyHeaders.ToList())
{
var keys = string.Join(", ", header.Value);
Console.WriteLine($"\tTO GHE: {header.Key}:{keys}");
}
return default;
});
});
// Initialize the reverse proxy from the "ReverseProxy" section of configuration
proxyBuilder.LoadFromConfig(Configuration.GetSection("ReverseProxy"));
services.AddMicrosoftIdentityWebApiAuthentication(Configuration, "AzureAd");
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options =>
{
Configuration.Bind("AzureAd", options);
options.Events.OnAuthorizationCodeReceived = ctx =>
{
Console.WriteLine("### OnAuthorizationCodeReceived");
return Task.CompletedTask;
};
options.Events.OnMessageReceived = ctx =>
{
Console.WriteLine("### OnMessageReceived");
return Task.CompletedTask;
};
options.Events.OnRedirectToIdentityProvider = ctx =>
{
Console.WriteLine("### OnRedirectToIdentityProvider");
return Task.CompletedTask;
};
options.Events.OnTokenValidated = ctx =>
{
Console.WriteLine("### OnTokenValidated");
return Task.CompletedTask;
};
options.Events.OnAuthenticationFailed = ctx =>
{
Console.WriteLine("### OnAuthenticationFailed");
return Task.CompletedTask;
};
options.Events.OnRedirectToIdentityProvider = ctx =>
{
Console.WriteLine("### OnRedirectToIdentityProvider");
return Task.CompletedTask;
};
options.ForwardDefaultSelector = (context =>
{
var authHeader = context.Request.Headers["MFA"].ToArray();
if (authHeader.Length > 0 && authHeader[0].ToLower().StartsWith("bearer"))
{
return JwtBearerDefaults.AuthenticationScheme;
}
return OpenIdConnectDefaults.AuthenticationScheme;
});
});
services.AddAuthorization(options =>
{
options.AddPolicy("authenticated", policy =>
policy.RequireAuthenticatedUser());
});
services.AddHealthChecks();
}
// This method gets called by the runtime. Use this method to configure the HTTP request
// pipeline that handles requests
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Use(async (context, next) =>
{
if (context.Request.Headers.ContainsKey("MFA"))
{
Console.WriteLine("!!! REWRITE AUTH FOR PROXY");
var mfa = context.Request.Headers["MFA"];
var auth = context.Request.Headers["AUTHORIZATION"];
//swapping the auth header with the MFA header
context.Request.Headers.Remove("AUTHORIZATION");
context.Request.Headers.Add("AUTHORIZATION", mfa);
context.Request.Headers.Add("BASIC", auth);
foreach (var h in context.Request.Headers)
{
Console.WriteLine($"\tFROM CLIENT: {h.Key}: {h.Value}");
}
}
else if (context.Request.Headers.ContainsKey("AUTHORIZATION"))
{
var auth = context.Request.Headers["AUTHORIZATION"];
//removing the bearer auth for the endpoint /api/v3/user
//it will be added back later for the proxy call to GHE
if (auth.Any(x => x.ToLower().StartsWith("bearer") && x.Length < 50))
{
context.Request.Headers.Remove("AUTHORIZATION");
context.Request.Headers.Add("BASIC", auth);
}
}
await next();
});
// Enable endpoint routing, required for the reverse proxy
app.UseRouting();
// Require Authentication
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapHealthChecks("/health").WithMetadata(new AllowAnonymousAttribute());
});
// Register the reverse proxy routes
app.UseEndpoints(endpoints =>
{
endpoints.MapReverseProxy();
});
}
}
}