-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
ApplicationController.cs
397 lines (345 loc) · 17.1 KB
/
ApplicationController.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
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using OpenIddict.Abstractions;
using OrchardCore.Admin;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Environment.Shell.Descriptor.Models;
using OrchardCore.Modules;
using OrchardCore.Navigation;
using OrchardCore.OpenId.Abstractions.Managers;
using OrchardCore.OpenId.Services;
using OrchardCore.OpenId.Settings;
using OrchardCore.OpenId.ViewModels;
using OrchardCore.Security.Services;
namespace OrchardCore.OpenId.Controllers;
[Feature(OpenIdConstants.Features.Management)]
[Admin("OpenId/Application/{action}/{id?}", "OpenIdApplication{action}")]
public sealed class ApplicationController : Controller
{
private readonly IAuthorizationService _authorizationService;
private readonly IShapeFactory _shapeFactory;
private readonly PagerOptions _pagerOptions;
private readonly IOpenIdApplicationManager _applicationManager;
private readonly IOpenIdScopeManager _scopeManager;
private readonly INotifier _notifier;
private readonly ShellDescriptor _shellDescriptor;
internal readonly IStringLocalizer S;
internal readonly IHtmlLocalizer H;
public ApplicationController(
IShapeFactory shapeFactory,
IOptions<PagerOptions> pagerOptions,
IStringLocalizer<ApplicationController> stringLocalizer,
IAuthorizationService authorizationService,
IOpenIdApplicationManager applicationManager,
IOpenIdScopeManager scopeManager,
IHtmlLocalizer<ApplicationController> htmlLocalizer,
INotifier notifier,
ShellDescriptor shellDescriptor)
{
_shapeFactory = shapeFactory;
_pagerOptions = pagerOptions.Value;
S = stringLocalizer;
H = htmlLocalizer;
_authorizationService = authorizationService;
_applicationManager = applicationManager;
_scopeManager = scopeManager;
_notifier = notifier;
_shellDescriptor = shellDescriptor;
}
[Admin("OpenId/Application", "OpenIdApplication")]
public async Task<ActionResult> Index(PagerParameters pagerParameters)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageApplications))
{
return Forbid();
}
var pager = new Pager(pagerParameters, _pagerOptions.GetPageSize());
var count = await _applicationManager.CountAsync();
var applications = new List<OpenIdApplicationEntry>();
await foreach (var application in _applicationManager.ListAsync(pager.PageSize, pager.GetStartIndex()))
{
applications.Add(new OpenIdApplicationEntry
{
DisplayName = await _applicationManager.GetDisplayNameAsync(application),
Id = await _applicationManager.GetPhysicalIdAsync(application)
});
}
var model = new OpenIdApplicationsIndexViewModel
{
Pager = await _shapeFactory.PagerAsync(pager, (int)count),
Applications = applications.OrderBy(x => x.DisplayName)
.ThenBy(x => x.Id)
.ToArray(),
};
return View(model);
}
[HttpGet]
public async Task<IActionResult> Create(string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageApplications))
{
return Forbid();
}
var model = new CreateOpenIdApplicationViewModel();
var roleService = HttpContext.RequestServices?.GetService<IRoleService>();
if (roleService != null)
{
foreach (var role in await roleService.GetRoleNamesAsync())
{
model.RoleEntries.Add(new CreateOpenIdApplicationViewModel.RoleEntry
{
Name = role
});
}
}
else
{
await _notifier.WarningAsync(H["There are no registered services to provide roles."]);
}
await foreach (var scope in _scopeManager.ListAsync(null, null, default))
{
model.ScopeEntries.Add(new CreateOpenIdApplicationViewModel.ScopeEntry
{
Name = await _scopeManager.GetNameAsync(scope)
});
}
ViewData[nameof(OpenIdServerSettings)] = await GetServerSettingsAsync();
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
[HttpPost]
public async Task<IActionResult> Create(CreateOpenIdApplicationViewModel model, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageApplications))
{
return Forbid();
}
if (!string.IsNullOrEmpty(model.ClientSecret) &&
string.Equals(model.Type, OpenIddictConstants.ClientTypes.Public, StringComparison.OrdinalIgnoreCase))
{
ModelState.AddModelError(nameof(model.ClientSecret), S["No client secret can be set for public applications."]);
}
else if (string.IsNullOrEmpty(model.ClientSecret) &&
string.Equals(model.Type, OpenIddictConstants.ClientTypes.Confidential, StringComparison.OrdinalIgnoreCase))
{
ModelState.AddModelError(nameof(model.ClientSecret), S["The client secret is required for confidential applications."]);
}
if (!string.IsNullOrEmpty(model.ClientId) && await _applicationManager.FindByClientIdAsync(model.ClientId) != null)
{
ModelState.AddModelError(nameof(model.ClientId), S["The client identifier is already taken by another application."]);
}
if (!ModelState.IsValid)
{
ViewData[nameof(OpenIdServerSettings)] = await GetServerSettingsAsync();
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
var settings = new OpenIdApplicationSettings()
{
AllowAuthorizationCodeFlow = model.AllowAuthorizationCodeFlow,
AllowClientCredentialsFlow = model.AllowClientCredentialsFlow,
AllowHybridFlow = model.AllowHybridFlow,
AllowImplicitFlow = model.AllowImplicitFlow,
AllowIntrospectionEndpoint = model.AllowIntrospectionEndpoint,
AllowLogoutEndpoint = model.AllowLogoutEndpoint,
AllowPasswordFlow = model.AllowPasswordFlow,
AllowRefreshTokenFlow = model.AllowRefreshTokenFlow,
AllowRevocationEndpoint = model.AllowRevocationEndpoint,
ClientId = model.ClientId,
ClientSecret = model.ClientSecret,
ConsentType = model.ConsentType,
DisplayName = model.DisplayName,
PostLogoutRedirectUris = model.PostLogoutRedirectUris,
RedirectUris = model.RedirectUris,
Roles = model.RoleEntries.Where(x => x.Selected).Select(x => x.Name).ToArray(),
Scopes = model.ScopeEntries.Where(x => x.Selected).Select(x => x.Name).ToArray(),
Type = model.Type,
RequireProofKeyForCodeExchange = model.RequireProofKeyForCodeExchange
};
await _applicationManager.UpdateDescriptorFromSettings(settings);
if (string.IsNullOrEmpty(returnUrl))
{
return RedirectToAction(nameof(Index));
}
return this.LocalRedirect(returnUrl, true);
}
public async Task<IActionResult> Edit(string id, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageApplications))
{
return Forbid();
}
var application = await _applicationManager.FindByPhysicalIdAsync(id);
if (application == null)
{
return NotFound();
}
ValueTask<bool> HasPermissionAsync(string permission) => _applicationManager.HasPermissionAsync(application, permission);
ValueTask<bool> HasRequirementAsync(string requirement) => _applicationManager.HasRequirementAsync(application, requirement);
var model = new EditOpenIdApplicationViewModel
{
AllowAuthorizationCodeFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode) &&
await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.Code),
AllowClientCredentialsFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.ClientCredentials),
// Note: the hybrid flow doesn't have a dedicated grant_type but is treated as a combination
// of both the authorization code and implicit grants. As such, to determine whether the hybrid
// flow is enabled, both the authorization code grant and the implicit grant MUST be enabled.
AllowHybridFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode) &&
await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.Implicit) &&
(await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.CodeIdToken) ||
await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.CodeIdTokenToken) ||
await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.CodeToken)),
AllowImplicitFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.Implicit) &&
(await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.IdToken) ||
await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.IdTokenToken) ||
await HasPermissionAsync(OpenIddictConstants.Permissions.ResponseTypes.Token)),
AllowPasswordFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.Password),
AllowRefreshTokenFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.RefreshToken),
AllowLogoutEndpoint = await HasPermissionAsync(OpenIddictConstants.Permissions.Endpoints.Logout),
AllowIntrospectionEndpoint = await HasPermissionAsync(OpenIddictConstants.Permissions.Endpoints.Introspection),
AllowRevocationEndpoint = await HasPermissionAsync(OpenIddictConstants.Permissions.Endpoints.Revocation),
ClientId = await _applicationManager.GetClientIdAsync(application),
ConsentType = await _applicationManager.GetConsentTypeAsync(application),
DisplayName = await _applicationManager.GetDisplayNameAsync(application),
Id = await _applicationManager.GetPhysicalIdAsync(application),
PostLogoutRedirectUris = string.Join(" ", await _applicationManager.GetPostLogoutRedirectUrisAsync(application)),
RedirectUris = string.Join(" ", await _applicationManager.GetRedirectUrisAsync(application)),
Type = await _applicationManager.GetClientTypeAsync(application),
RequireProofKeyForCodeExchange = await HasRequirementAsync(OpenIddictConstants.Requirements.Features.ProofKeyForCodeExchange)
};
var roleService = HttpContext.RequestServices?.GetService<IRoleService>();
if (roleService != null)
{
var roles = await _applicationManager.GetRolesAsync(application);
foreach (var role in await roleService.GetRoleNamesAsync())
{
model.RoleEntries.Add(new EditOpenIdApplicationViewModel.RoleEntry
{
Name = role,
Selected = roles.Contains(role, StringComparer.OrdinalIgnoreCase)
});
}
}
else
{
await _notifier.WarningAsync(H["There are no registered services to provide roles."]);
}
var permissions = await _applicationManager.GetPermissionsAsync(application);
await foreach (var scope in _scopeManager.ListAsync())
{
var scopeName = await _scopeManager.GetNameAsync(scope);
model.ScopeEntries.Add(new EditOpenIdApplicationViewModel.ScopeEntry
{
Name = scopeName,
Selected = await _applicationManager.HasPermissionAsync(application, OpenIddictConstants.Permissions.Prefixes.Scope + scopeName)
});
}
ViewData[nameof(OpenIdServerSettings)] = await GetServerSettingsAsync();
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
[HttpPost]
public async Task<IActionResult> Edit(EditOpenIdApplicationViewModel model, string returnUrl = null)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageApplications))
{
return Forbid();
}
var application = await _applicationManager.FindByPhysicalIdAsync(model.Id);
if (application == null)
{
return NotFound();
}
// If the application was a public client and is now a confidential client, ensure a client secret was provided.
if (string.IsNullOrEmpty(model.ClientSecret) &&
!string.Equals(model.Type, OpenIddictConstants.ClientTypes.Public, StringComparison.OrdinalIgnoreCase) &&
await _applicationManager.HasClientTypeAsync(application, OpenIddictConstants.ClientTypes.Public))
{
ModelState.AddModelError(nameof(model.ClientSecret), S["Setting a new client secret is required."]);
}
if (!string.IsNullOrEmpty(model.ClientSecret) &&
string.Equals(model.Type, OpenIddictConstants.ClientTypes.Public, StringComparison.OrdinalIgnoreCase))
{
ModelState.AddModelError(nameof(model.ClientSecret), S["No client secret can be set for public applications."]);
}
if (ModelState.IsValid)
{
var other = await _applicationManager.FindByClientIdAsync(model.ClientId);
if (other != null && !string.Equals(
await _applicationManager.GetIdAsync(other),
await _applicationManager.GetIdAsync(application), StringComparison.Ordinal))
{
ModelState.AddModelError(nameof(model.ClientId), S["The client identifier is already taken by another application."]);
}
}
if (!ModelState.IsValid)
{
ViewData[nameof(OpenIdServerSettings)] = await GetServerSettingsAsync();
ViewData["ReturnUrl"] = returnUrl;
return View(model);
}
var settings = new OpenIdApplicationSettings()
{
AllowAuthorizationCodeFlow = model.AllowAuthorizationCodeFlow,
AllowClientCredentialsFlow = model.AllowClientCredentialsFlow,
AllowHybridFlow = model.AllowHybridFlow,
AllowImplicitFlow = model.AllowImplicitFlow,
AllowIntrospectionEndpoint = model.AllowIntrospectionEndpoint,
AllowLogoutEndpoint = model.AllowLogoutEndpoint,
AllowPasswordFlow = model.AllowPasswordFlow,
AllowRefreshTokenFlow = model.AllowRefreshTokenFlow,
AllowRevocationEndpoint = model.AllowRevocationEndpoint,
ClientId = model.ClientId,
ClientSecret = model.ClientSecret,
ConsentType = model.ConsentType,
DisplayName = model.DisplayName,
PostLogoutRedirectUris = model.PostLogoutRedirectUris,
RedirectUris = model.RedirectUris,
Roles = model.RoleEntries.Where(x => x.Selected).Select(x => x.Name).ToArray(),
Scopes = model.ScopeEntries.Where(x => x.Selected).Select(x => x.Name).ToArray(),
Type = model.Type,
RequireProofKeyForCodeExchange = model.RequireProofKeyForCodeExchange
};
await _applicationManager.UpdateDescriptorFromSettings(settings, application);
if (string.IsNullOrEmpty(returnUrl))
{
return RedirectToAction(nameof(Index));
}
return this.LocalRedirect(returnUrl, true);
}
[HttpPost]
public async Task<IActionResult> Delete(string id)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageApplications))
{
return Forbid();
}
var application = await _applicationManager.FindByPhysicalIdAsync(id);
if (application == null)
{
return NotFound();
}
await _applicationManager.DeleteAsync(application);
return RedirectToAction(nameof(Index));
}
private async Task<OpenIdServerSettings> GetServerSettingsAsync()
{
if (_shellDescriptor.Features.Any(feature => feature.Id == OpenIdConstants.Features.Server))
{
var service = HttpContext.RequestServices.GetRequiredService<IOpenIdServerService>();
var settings = await service.GetSettingsAsync();
if ((await service.ValidateSettingsAsync(settings)).Any(result => result != ValidationResult.Success))
{
await _notifier.WarningAsync(H["OpenID Connect settings are not properly configured."]);
}
return settings;
}
return null;
}
}