Repository navigation
Expand file tree
/
Copy pathTestSettings.cs
More file actions
230 lines (193 loc) · 9.82 KB
/
Copy pathTestSettings.cs
File metadata and controls
230 lines (193 loc) · 9.82 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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Xml.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.TestHost;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Xunit;
namespace Microsoft.AspNetCore.Authentication.Tests.OpenIdConnect
{
/// <summary>
/// This helper class is used to check that query string parameters are as expected.
/// </summary>
internal class TestSettings
{
private readonly OpenIdConnectOptions _options;
public TestSettings() : this(configure: null)
{
}
public TestSettings(Action<OpenIdConnectOptions> configure)
{
_options = TestServerBuilder.CreateOpenIdConnectOptions(configure);
}
public TestSettings(OpenIdConnectOptions options)
{
_options = options;
}
public OpenIdConnectOptions Options => _options;
public UrlEncoder Encoder => UrlEncoder.Default;
public string ExpectedState { get; set; }
public TestServer CreateTestServer() => TestServerBuilder.CreateServer(Options);
public IDictionary<string, string> ValidateChallengeFormPost(string responseBody, params string[] parametersToValidate)
{
IDictionary<string, string> formInputs = null;
var errors = new List<string>();
var xdoc = XDocument.Parse(responseBody.Replace("doctype", "DOCTYPE"));
var forms = xdoc.Descendants("form");
if (forms.Count() != 1)
{
errors.Add("Only one form element is expected in response body.");
}
else
{
formInputs = forms.Single()
.Elements("input")
.ToDictionary(elem => elem.Attribute("name").Value,
elem => elem.Attribute("value").Value);
ValidateParameters(formInputs, parametersToValidate, errors, htmlEncoded: false);
}
if (errors.Any())
{
var buf = new StringBuilder();
buf.AppendLine($"The challenge form post is not valid.");
// buf.AppendLine();
foreach (var error in errors)
{
buf.AppendLine(error);
}
Debug.WriteLine(buf.ToString());
Assert.True(false, buf.ToString());
}
return formInputs;
}
public IDictionary<string, string> ValidateChallengeRedirect(Uri redirectUri, params string[] parametersToValidate) =>
ValidateRedirectCore(redirectUri, OpenIdConnectRequestType.Authentication, parametersToValidate);
public IDictionary<string, string> ValidateSignoutRedirect(Uri redirectUri, params string[] parametersToValidate) =>
ValidateRedirectCore(redirectUri, OpenIdConnectRequestType.Logout, parametersToValidate);
private IDictionary<string, string> ValidateRedirectCore(Uri redirectUri, OpenIdConnectRequestType requestType, string[] parametersToValidate)
{
var errors = new List<string>();
// Validate the authority
ValidateExpectedAuthority(redirectUri.AbsoluteUri, errors, requestType);
// Convert query to dictionary
var queryDict = string.IsNullOrEmpty(redirectUri.Query) ?
new Dictionary<string, string>() :
redirectUri.Query.TrimStart('?').Split('&').Select(part => part.Split('=')).ToDictionary(parts => parts[0], parts => parts[1]);
// Validate the query string parameters
ValidateParameters(queryDict, parametersToValidate, errors, htmlEncoded: true);
if (errors.Any())
{
var buf = new StringBuilder();
buf.AppendLine($"The redirect uri is not valid.");
buf.AppendLine(redirectUri.AbsoluteUri);
foreach (var error in errors)
{
buf.AppendLine(error);
}
Debug.WriteLine(buf.ToString());
Assert.True(false, buf.ToString());
}
return queryDict;
}
private void ValidateParameters(
IDictionary<string, string> actualValues,
IEnumerable<string> parametersToValidate,
ICollection<string> errors,
bool htmlEncoded)
{
foreach (var paramToValidate in parametersToValidate)
{
switch (paramToValidate)
{
case OpenIdConnectParameterNames.ClientId:
ValidateClientId(actualValues, errors, htmlEncoded);
break;
case OpenIdConnectParameterNames.ResponseType:
ValidateResponseType(actualValues, errors, htmlEncoded);
break;
case OpenIdConnectParameterNames.ResponseMode:
ValidateResponseMode(actualValues, errors, htmlEncoded);
break;
case OpenIdConnectParameterNames.Scope:
ValidateScope(actualValues, errors, htmlEncoded);
break;
case OpenIdConnectParameterNames.RedirectUri:
ValidateRedirectUri(actualValues, errors, htmlEncoded);
break;
case OpenIdConnectParameterNames.Resource:
ValidateResource(actualValues, errors, htmlEncoded);
break;
case OpenIdConnectParameterNames.State:
ValidateState(actualValues, errors, htmlEncoded);
break;
default:
throw new InvalidOperationException($"Unknown parameter \"{paramToValidate}\".");
}
}
}
private void ValidateExpectedAuthority(string absoluteUri, ICollection<string> errors, OpenIdConnectRequestType requestType)
{
string expectedAuthority;
switch (requestType)
{
case OpenIdConnectRequestType.Token:
expectedAuthority = _options.Configuration?.TokenEndpoint ?? _options.Authority + @"/oauth2/token";
break;
case OpenIdConnectRequestType.Logout:
expectedAuthority = _options.Configuration?.EndSessionEndpoint ?? _options.Authority + @"/oauth2/logout";
break;
default:
expectedAuthority = _options.Configuration?.AuthorizationEndpoint ?? _options.Authority + @"/oauth2/authorize";
break;
}
if (!absoluteUri.StartsWith(expectedAuthority))
{
errors.Add($"ExpectedAuthority: {expectedAuthority}");
}
}
private void ValidateClientId(IDictionary<string, string> actualQuery, ICollection<string> errors, bool htmlEncoded) =>
ValidateQueryParameter(OpenIdConnectParameterNames.ClientId, _options.ClientId, actualQuery, errors, htmlEncoded);
private void ValidateResponseType(IDictionary<string, string> actualQuery, ICollection<string> errors, bool htmlEncoded) =>
ValidateQueryParameter(OpenIdConnectParameterNames.ResponseType, _options.ResponseType, actualQuery, errors, htmlEncoded);
private void ValidateResponseMode(IDictionary<string, string> actualQuery, ICollection<string> errors, bool htmlEncoded) =>
ValidateQueryParameter(OpenIdConnectParameterNames.ResponseMode, _options.ResponseMode, actualQuery, errors, htmlEncoded);
private void ValidateScope(IDictionary<string, string> actualQuery, ICollection<string> errors, bool htmlEncoded) =>
ValidateQueryParameter(OpenIdConnectParameterNames.Scope, string.Join(" ", _options.Scope), actualQuery, errors, htmlEncoded);
private void ValidateRedirectUri(IDictionary<string, string> actualQuery, ICollection<string> errors, bool htmlEncoded) =>
ValidateQueryParameter(OpenIdConnectParameterNames.RedirectUri, TestServerBuilder.TestHost + _options.CallbackPath, actualQuery, errors, htmlEncoded);
private void ValidateResource(IDictionary<string, string> actualQuery, ICollection<string> errors, bool htmlEncoded) =>
ValidateQueryParameter(OpenIdConnectParameterNames.RedirectUri, _options.Resource, actualQuery, errors, htmlEncoded);
private void ValidateState(IDictionary<string, string> actualQuery, ICollection<string> errors, bool htmlEncoded) =>
ValidateQueryParameter(OpenIdConnectParameterNames.State, ExpectedState, actualQuery, errors, htmlEncoded);
private void ValidateQueryParameter(
string parameterName,
string expectedValue,
IDictionary<string, string> actualQuery,
ICollection<string> errors,
bool htmlEncoded)
{
string actualValue;
if (actualQuery.TryGetValue(parameterName, out actualValue))
{
if (htmlEncoded)
{
expectedValue = Encoder.Encode(expectedValue);
}
if (actualValue != expectedValue)
{
errors.Add($"Query parameter {parameterName}'s expected value is {expectedValue} but its actual value is {actualValue}");
}
}
else
{
errors.Add($"Query parameter {parameterName} is missing");
}
}
}
}