-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathClaimsToHeadersForwardingTests.cs
203 lines (190 loc) · 8.39 KB
/
ClaimsToHeadersForwardingTests.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
203
using IdentityServer4.AccessTokenValidation;
using IdentityServer4.Models;
using IdentityServer4.Test;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Ocelot.Configuration.File;
using System.Security.Claims;
[assembly: CollectionBehavior(DisableTestParallelization = true)]
namespace Ocelot.AcceptanceTests
{
public class ClaimsToHeadersForwardingTests : IDisposable
{
private IWebHost _identityServerBuilder;
private readonly Steps _steps;
private readonly Action<IdentityServerAuthenticationOptions> _options;
private readonly string _identityServerRootUrl;
private readonly ServiceHandler _serviceHandler;
public ClaimsToHeadersForwardingTests()
{
_serviceHandler = new ServiceHandler();
_steps = new Steps();
var identityServerPort = PortFinder.GetRandomPort();
_identityServerRootUrl = $"http://localhost:{identityServerPort}";
_options = o =>
{
o.Authority = _identityServerRootUrl;
o.ApiName = "api";
o.RequireHttpsMetadata = false;
o.SupportedTokens = SupportedTokens.Both;
o.ApiSecret = "secret";
};
}
[Fact]
public void should_return_response_200_and_foward_claim_as_header()
{
var user = new TestUser
{
Username = "test",
Password = "test",
SubjectId = "registered|1231231",
Claims = new List<Claim>
{
new("CustomerId", "123"),
new("LocationId", "1"),
},
};
var port = PortFinder.GetRandomPort();
var configuration = new FileConfiguration
{
Routes = new List<FileRoute>
{
new()
{
DownstreamPathTemplate = "/",
DownstreamHostAndPorts = new List<FileHostAndPort>
{
new()
{
Host = "localhost",
Port = port,
},
},
DownstreamScheme = "http",
UpstreamPathTemplate = "/",
UpstreamHttpMethod = new List<string> { "Get" },
AuthenticationOptions = new FileAuthenticationOptions
{
AuthenticationProviderKey = "Test",
AllowedScopes = new List<string>
{
"api",
},
},
AddHeadersToRequest =
{
{"CustomerId", "Claims[CustomerId] > value"},
{"LocationId", "Claims[LocationId] > value"},
{"UserType", "Claims[sub] > value[0] > |"},
{"UserId", "Claims[sub] > value[1] > |"},
},
},
},
};
this.Given(x => x.GivenThereIsAnIdentityServerOn(_identityServerRootUrl, "api", AccessTokenType.Jwt, user))
.And(x => x.GivenThereIsAServiceRunningOn($"http://localhost:{port}", 200))
.And(x => _steps.GivenIHaveAToken(_identityServerRootUrl))
.And(x => _steps.GivenThereIsAConfiguration(configuration))
.And(x => _steps.GivenOcelotIsRunning(_options, "Test"))
.And(x => _steps.GivenIHaveAddedATokenToMyRequest())
.When(x => _steps.WhenIGetUrlOnTheApiGateway("/"))
.Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK))
.And(x => _steps.ThenTheResponseBodyShouldBe("CustomerId: 123 LocationId: 1 UserType: registered UserId: 1231231"))
.BDDfy();
}
private void GivenThereIsAServiceRunningOn(string url, int statusCode)
{
_serviceHandler.GivenThereIsAServiceRunningOn(url, async context =>
{
var customerId = context.Request.Headers.First(x => x.Key == "CustomerId").Value.First();
var locationId = context.Request.Headers.First(x => x.Key == "LocationId").Value.First();
var userType = context.Request.Headers.First(x => x.Key == "UserType").Value.First();
var userId = context.Request.Headers.First(x => x.Key == "UserId").Value.First();
var responseBody = $"CustomerId: {customerId} LocationId: {locationId} UserType: {userType} UserId: {userId}";
context.Response.StatusCode = statusCode;
await context.Response.WriteAsync(responseBody);
});
}
private async Task GivenThereIsAnIdentityServerOn(string url, string apiName, AccessTokenType tokenType, TestUser user)
{
_identityServerBuilder = TestHostBuilder.Create()
.UseUrls(url)
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseUrls(url)
.ConfigureServices(services =>
{
services.AddLogging();
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiScopes(new List<ApiScope>
{
new(apiName, "test"),
new("openid", "test"),
new("offline_access", "test"),
new("api.readOnly", "test"),
})
.AddInMemoryApiResources(new List<ApiResource>
{
new()
{
Name = apiName,
Description = "My API",
Enabled = true,
DisplayName = "test",
Scopes = new List<string>
{
"api",
"openid",
"offline_access",
},
ApiSecrets = new List<Secret>
{
new()
{
Value = "secret".Sha256(),
},
},
UserClaims = new List<string>
{
"CustomerId", "LocationId", "UserType", "UserId",
},
},
})
.AddInMemoryClients(new List<Client>
{
new()
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
ClientSecrets = new List<Secret> {new("secret".Sha256())},
AllowedScopes = new List<string> { apiName, "openid", "offline_access" },
AccessTokenType = tokenType,
Enabled = true,
RequireClientSecret = false,
},
})
.AddTestUsers(new List<TestUser>
{
user,
});
})
.Configure(app =>
{
app.UseIdentityServer();
})
.Build();
await _identityServerBuilder.StartAsync();
await Steps.VerifyIdentityServerStarted(url);
}
public void Dispose()
{
_serviceHandler?.Dispose();
_steps.Dispose();
_identityServerBuilder?.Dispose();
}
}
}