forked from OrchardCMS/OrchardCore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenIdServerConfiguration.cs
More file actions
249 lines (203 loc) · 9.92 KB
/
OpenIdServerConfiguration.cs
File metadata and controls
249 lines (203 loc) · 9.92 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
245
246
247
248
249
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using OpenIddict.Server;
using OpenIddict.Server.AspNetCore;
using OpenIddict.Server.DataProtection;
using OrchardCore.Environment.Shell;
using OrchardCore.OpenId.Services;
using OrchardCore.OpenId.Settings;
using static OpenIddict.Abstractions.OpenIddictConstants;
namespace OrchardCore.OpenId.Configuration;
public sealed class OpenIdServerConfiguration : IConfigureOptions<AuthenticationOptions>,
IConfigureOptions<OpenIddictServerOptions>,
IConfigureOptions<OpenIddictServerDataProtectionOptions>,
IConfigureNamedOptions<OpenIddictServerAspNetCoreOptions>
{
private readonly IOpenIdServerService _serverService;
private readonly ShellSettings _shellSettings;
private readonly ILogger _logger;
public OpenIdServerConfiguration(
IOpenIdServerService serverService,
ShellSettings shellSettings,
ILogger<OpenIdServerConfiguration> logger)
{
_serverService = serverService;
_shellSettings = shellSettings;
_logger = logger;
}
public void Configure(AuthenticationOptions options)
{
var settings = GetServerSettingsAsync().GetAwaiter().GetResult();
if (settings == null)
{
return;
}
options.AddScheme<OpenIddictServerAspNetCoreHandler>(
OpenIddictServerAspNetCoreDefaults.AuthenticationScheme, displayName: null);
}
public void Configure(OpenIddictServerOptions options)
{
var settings = GetServerSettingsAsync().GetAwaiter().GetResult();
if (settings == null)
{
return;
}
options.Issuer = settings.Authority;
options.DisableAccessTokenEncryption = settings.DisableAccessTokenEncryption;
options.DisableRollingRefreshTokens = settings.DisableRollingRefreshTokens;
options.UseReferenceAccessTokens = settings.UseReferenceAccessTokens;
foreach (var key in _serverService.GetEncryptionKeysAsync().GetAwaiter().GetResult())
{
options.EncryptionCredentials.Add(new EncryptingCredentials(key,
SecurityAlgorithms.RsaOAEP, SecurityAlgorithms.Aes256CbcHmacSha512));
}
foreach (var key in _serverService.GetSigningKeysAsync().GetAwaiter().GetResult())
{
options.SigningCredentials.Add(new SigningCredentials(key, SecurityAlgorithms.RsaSha256));
}
// Note: while endpoint paths in OrchardCore are stored as PathString instances,
// OpenIddict uses System.Uri. To ensure the System.Uri instances created from
// a PathString don't represent root-relative URIs (which would break path-based
// multi-tenancy support), the leading '/' that is always present in PathString
// instances is manually removed from the endpoint path before URIs are created.
if (settings.AuthorizationEndpointPath.HasValue)
{
options.AuthorizationEndpointUris.Add(new Uri(
settings.AuthorizationEndpointPath.ToUriComponent()[1..], UriKind.Relative));
}
if (settings.LogoutEndpointPath.HasValue)
{
options.EndSessionEndpointUris.Add(new Uri(
settings.LogoutEndpointPath.ToUriComponent()[1..], UriKind.Relative));
}
if (settings.TokenEndpointPath.HasValue)
{
options.TokenEndpointUris.Add(new Uri(
settings.TokenEndpointPath.ToUriComponent()[1..], UriKind.Relative));
}
if (settings.UserinfoEndpointPath.HasValue)
{
options.UserInfoEndpointUris.Add(new Uri(
settings.UserinfoEndpointPath.ToUriComponent()[1..], UriKind.Relative));
}
if (settings.IntrospectionEndpointPath.HasValue)
{
options.IntrospectionEndpointUris.Add(new Uri(
settings.IntrospectionEndpointPath.ToUriComponent()[1..], UriKind.Relative));
}
if (settings.RevocationEndpointPath.HasValue)
{
options.RevocationEndpointUris.Add(new Uri(
settings.RevocationEndpointPath.ToUriComponent()[1..], UriKind.Relative));
}
// For now, response types and response modes are not directly
// configurable and are inferred from the selected flows.
if (settings.AllowAuthorizationCodeFlow)
{
options.CodeChallengeMethods.Add(CodeChallengeMethods.Plain);
options.CodeChallengeMethods.Add(CodeChallengeMethods.Sha256);
options.GrantTypes.Add(GrantTypes.AuthorizationCode);
options.ResponseModes.Add(ResponseModes.FormPost);
options.ResponseModes.Add(ResponseModes.Fragment);
options.ResponseModes.Add(ResponseModes.Query);
options.ResponseTypes.Add(ResponseTypes.Code);
}
if (settings.AllowClientCredentialsFlow)
{
options.GrantTypes.Add(GrantTypes.ClientCredentials);
}
if (settings.AllowHybridFlow)
{
options.CodeChallengeMethods.Add(CodeChallengeMethods.Plain);
options.CodeChallengeMethods.Add(CodeChallengeMethods.Sha256);
options.GrantTypes.Add(GrantTypes.AuthorizationCode);
options.GrantTypes.Add(GrantTypes.Implicit);
options.ResponseModes.Add(ResponseModes.FormPost);
options.ResponseModes.Add(ResponseModes.Fragment);
options.ResponseTypes.Add(ResponseTypes.Code + ' ' + ResponseTypes.IdToken);
options.ResponseTypes.Add(ResponseTypes.Code + ' ' + ResponseTypes.IdToken + ' ' + ResponseTypes.Token);
options.ResponseTypes.Add(ResponseTypes.Code + ' ' + ResponseTypes.Token);
}
if (settings.AllowImplicitFlow)
{
options.GrantTypes.Add(GrantTypes.Implicit);
options.ResponseModes.Add(ResponseModes.FormPost);
options.ResponseModes.Add(ResponseModes.Fragment);
options.ResponseTypes.Add(ResponseTypes.IdToken);
options.ResponseTypes.Add(ResponseTypes.IdToken + ' ' + ResponseTypes.Token);
options.ResponseTypes.Add(ResponseTypes.Token);
}
if (settings.AllowPasswordFlow)
{
options.GrantTypes.Add(GrantTypes.Password);
}
if (settings.AllowRefreshTokenFlow)
{
options.GrantTypes.Add(GrantTypes.RefreshToken);
options.Scopes.Add(Scopes.OfflineAccess);
}
options.RequireProofKeyForCodeExchange = settings.RequireProofKeyForCodeExchange;
options.Scopes.Add(Scopes.Email);
options.Scopes.Add(Scopes.Phone);
options.Scopes.Add(Scopes.Profile);
options.Scopes.Add(Scopes.Roles);
// Note: caching is enabled for both authorization and end session requests to allow sending
// large POST authorization and end session requests, but can be programmatically disabled, as the
// authorization and end session views support flowing the entire payload and not just the request_uri.
options.EnableAuthorizationRequestCaching = true;
options.EnableEndSessionRequestCaching = true;
}
public void Configure(OpenIddictServerDataProtectionOptions options)
{
var settings = GetServerSettingsAsync().GetAwaiter().GetResult();
if (settings == null)
{
return;
}
// All the tokens produced by the server feature use ASP.NET Core Data Protection as the default
// token format, but an option is provided to allow switching to JWT for access tokens only.
options.PreferDefaultAccessTokenFormat = settings.AccessTokenFormat == OpenIdServerSettings.TokenFormat.JsonWebToken;
}
public void Configure(string name, OpenIddictServerAspNetCoreOptions options)
{
// Note: the OpenID module handles the authorization, end session, token and userinfo requests
// in its dedicated ASP.NET Core MVC controller, which requires enabling the pass-through mode.
options.EnableAuthorizationEndpointPassthrough = true;
options.EnableEndSessionEndpointPassthrough = true;
options.EnableTokenEndpointPassthrough = true;
options.EnableUserInfoEndpointPassthrough = true;
// Note: error pass-through is enabled to allow the actions of the MVC authorization controller
// to handle the errors returned by the interactive endpoints without relying on the generic
// status code pages middleware to rewrite the response later in the request processing.
options.EnableErrorPassthrough = true;
// Note: in Orchard, transport security is usually configured via the dedicated HTTPS module.
// To make configuration easier and avoid having to configure it in two different features,
// the transport security requirement enforced by OpenIddict by default is always turned off.
options.DisableTransportSecurityRequirement = true;
}
public void Configure(OpenIddictServerAspNetCoreOptions options)
=> Debug.Fail("This infrastructure method shouldn't be called.");
private async Task<OpenIdServerSettings> GetServerSettingsAsync()
{
var settings = await _serverService.GetSettingsAsync();
var result = await _serverService.ValidateSettingsAsync(settings);
if (result.Any(result => result != ValidationResult.Success))
{
if (_shellSettings.IsRunning())
{
if (_logger.IsEnabled(LogLevel.Warning))
{
var errors = result.Where(x => x != ValidationResult.Success)
.Select(x => x.ErrorMessage);
_logger.LogWarning("The OpenID server settings are invalid: {Errors}", string.Join(System.Environment.NewLine, errors));
}
return null;
}
}
return settings;
}
}