示例#1
0
        public async Task <IActionResult> Create(string returnUrl = null)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageOpenIdApplications))
            {
                return(Unauthorized());
            }

            var openIdSettings = await _openIdService.GetOpenIdSettingsAsync();

            if (!_openIdService.IsValidOpenIdSettings(openIdSettings))
            {
                _notifier.Warning(H["OpenID Connect settings are not properly configured."]);
            }

            var model = new CreateOpenIdApplicationViewModel()
            {
                RoleEntries = (await _roleProvider.GetRoleNamesAsync()).Select(r => new RoleEntry()
                {
                    Name = r
                }).ToList()
            };

            ViewData["OpenIdSettings"] = openIdSettings;
            ViewData["ReturnUrl"]      = returnUrl;
            return(View(model));
        }
        public async Task ConfidentionalClientNeedsSecret(string clientType, string clientSecret, bool allowAuthFlow, bool allowPasswordFlow, bool expectValidModel)
        {
            var controller = new ApplicationController(
                Mock.Of <IShapeFactory>(),
                Mock.Of <ISiteService>(),
                MockStringLocalizer().Object,
                MockAuthorizationServiceMock().Object,
                Mock.Of <IOpenIdApplicationManager>(),
                Mock.Of <IOpenIdScopeManager>(),
                Mock.Of <IHtmlLocalizer <ApplicationController> >(),
                Mock.Of <INotifier>(),
                Mock.Of <ShellDescriptor>());

            controller.ControllerContext = CreateControllerContext();

            var model = new CreateOpenIdApplicationViewModel();

            model.Type         = clientType;
            model.ClientSecret = clientSecret;
            model.AllowAuthorizationCodeFlow = allowAuthFlow;
            model.AllowPasswordFlow          = allowPasswordFlow;
            var result = await controller.Create(model);

            if (expectValidModel)
            {
                Assert.IsType <RedirectToActionResult>(result);
            }
            else
            {
                Assert.IsType <ViewResult>(result);
            }
            Assert.Equal(expectValidModel, controller.ModelState.IsValid);
        }
        public async Task <IActionResult> Create(string returnUrl = null)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageApplications))
            {
                return(Unauthorized());
            }

            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
            {
                _notifier.Warning(H["There are no registered services to provide roles."]);
            }

            ViewData[nameof(OpenIdServerSettings)] = await GetServerSettingsAsync();

            ViewData["ReturnUrl"] = returnUrl;
            return(View(model));
        }
        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,
                AllowLogoutEndpoint        = model.AllowLogoutEndpoint,
                AllowPasswordFlow          = model.AllowPasswordFlow,
                AllowRefreshTokenFlow      = model.AllowRefreshTokenFlow,
                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
            };

            await _applicationManager.UpdateDescriptorFromSettings(settings);

            if (string.IsNullOrEmpty(returnUrl))
            {
                return(RedirectToAction(nameof(Index)));
            }

            return(this.LocalRedirect(returnUrl, true));
        }
示例#5
0
        public async Task RedirectUrisAreValid(string uris, bool expectValidModel)
        {
            var controller = new ApplicationController(
                Mock.Of <IShapeFactory>(),
                Mock.Of <ISiteService>(),
                MockStringLocalizer().Object,
                MockAuthorizationServiceMock().Object,
                Mock.Of <IRoleProvider>(),
                Mock.Of <IOpenIdApplicationManager>(),
                Mock.Of <IHtmlLocalizer <ApplicationController> >(),
                Mock.Of <INotifier>(),
                Mock.Of <ShellDescriptor>());

            controller.ControllerContext = CreateControllerContext();

            var model = new CreateOpenIdApplicationViewModel();

            model.Type = OpenIddictConstants.ClientTypes.Public;
            model.AllowAuthorizationCodeFlow = true;
            model.RedirectUris = uris;
            var result = await controller.Create(model);

            if (expectValidModel)
            {
                Assert.IsType <RedirectToActionResult>(result);
            }
            else
            {
                Assert.IsType <ViewResult>(result);
            }
            Assert.Equal(expectValidModel, controller.ModelState.IsValid);
        }
示例#6
0
        public async Task <IActionResult> Create(CreateOpenIdApplicationViewModel model, string returnUrl = null)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageOpenIdApplications))
            {
                return(Unauthorized());
            }

            if (model.Type == ClientType.Confidential)
            {
                var user = await _userManager.FindByNameAsync(User.Identity.Name);
                await ValidateClientSecretAsync(user, model.ClientSecret, (key, message) => ModelState.AddModelError(key, message));
            }
            else if (model.Type == ClientType.Public && !string.IsNullOrEmpty(model.ClientSecret))
            {
                ModelState.AddModelError(nameof(model.ClientSecret), T["No client secret can be set for public applications."]);
            }

            if (!model.AllowAuthorizationCodeFlow && !model.AllowClientCredentialsFlow &&
                !model.AllowImplicitFlow && !model.AllowPasswordFlow && !model.AllowRefreshTokenFlow)
            {
                ModelState.AddModelError(string.Empty, "At least one flow must be enabled.");
            }

            if (await _applicationManager.FindByClientIdAsync(model.ClientId) != null)
            {
                ModelState.AddModelError(nameof(model.ClientId), T["The client identifier is already taken by another application."]);
            }

            if (!ModelState.IsValid)
            {
                var openIdSettings = await _openIdService.GetOpenIdSettingsAsync();

                if (!_openIdService.IsValidOpenIdSettings(openIdSettings))
                {
                    _notifier.Warning(H["OpenID Connect settings are not properly configured."]);
                }

                ViewData["OpenIdSettings"] = openIdSettings;
                ViewData["ReturnUrl"]      = returnUrl;
                return(View("Create", model));
            }

            await _applicationManager.CreateAsync(model);

            if (string.IsNullOrEmpty(returnUrl))
            {
                return(RedirectToAction("Index"));
            }

            return(LocalRedirect(returnUrl));
        }
        public async Task RedirectUrisAreValid(string uris, bool expectValidModel)
        {
            var controller = new ApplicationController(
                Mock.Of <IShapeFactory>(),
                Mock.Of <ISiteService>(),
                MockStringLocalizer().Object,
                MockAuthorizationServiceMock().Object,
                Mock.Of <IOpenIdApplicationManager>(),
                Mock.Of <IOpenIdScopeManager>(),
                Mock.Of <IHtmlLocalizer <ApplicationController> >(),
                Mock.Of <INotifier>(),
                Mock.Of <ShellDescriptor>());

            controller.ControllerContext = CreateControllerContext();

            var model = new CreateOpenIdApplicationViewModel();

            model.Type = OpenIddictConstants.ClientTypes.Public;
            model.AllowAuthorizationCodeFlow = true;
            model.RedirectUris = uris;

            var validationContext = new ValidationContext(model);
            var localizerMock     = new Mock <IStringLocalizer <CreateOpenIdApplicationViewModel> >();

            localizerMock.Setup(x => x[It.IsAny <string>(), It.IsAny <object[]>()])
            .Returns((string name, object[] args) => new LocalizedString(name, string.Format(name, args)));
            validationContext.InitializeServiceProvider((t) => localizerMock.Object);

            foreach (var validation in model.Validate(validationContext))
            {
                controller.ModelState.AddModelError(validation.MemberNames.First(), validation.ErrorMessage);
            }

            var result = await controller.Create(model);

            if (expectValidModel)
            {
                Assert.IsType <RedirectToActionResult>(result);
            }
            else
            {
                Assert.IsType <ViewResult>(result);
            }
            Assert.Equal(expectValidModel, controller.ModelState.IsValid);
        }
示例#8
0
        public async Task <IActionResult> Create(string returnUrl = null)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageApplications))
            {
                return(Unauthorized());
            }

            var model = new CreateOpenIdApplicationViewModel();

            foreach (var role in await _roleProvider.GetRoleNamesAsync())
            {
                model.RoleEntries.Add(new CreateOpenIdApplicationViewModel.RoleEntry
                {
                    Name = role
                });
            }

            ViewData[nameof(OpenIdServerSettings)] = await GetServerSettingsAsync();

            ViewData["ReturnUrl"] = returnUrl;
            return(View(model));
        }
示例#9
0
        public async Task <IActionResult> Create(CreateOpenIdApplicationViewModel model, string returnUrl = null)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageOpenIdApplications))
            {
                return(Unauthorized());
            }

            if (model.Type == ClientType.Confidential)
            {
                var user = await _userManager.FindByNameAsync(User.Identity.Name);
                await ValidateClientSecretAsync(user, model.ClientSecret, (key, message) => ModelState.AddModelError(key, message));
            }
            else if (model.Type == ClientType.Public && !string.IsNullOrEmpty(model.ClientSecret))
            {
                ModelState.AddModelError(nameof(model.ClientSecret), T["No client secret can be set for public applications."]);
            }

            if (!ModelState.IsValid)
            {
                var openIdSettings = await _openIdService.GetOpenIdSettingsAsync();

                if (!_openIdService.IsValidOpenIdSettings(openIdSettings))
                {
                    _notifier.Warning(H["OpenID Connect settings are not properly configured."]);
                }

                ViewData["OpenIdSettings"] = openIdSettings;
                ViewData["ReturnUrl"]      = returnUrl;
                return(View("Create", model));
            }

            var roleNames = new List <string>();

            if (model.Type == ClientType.Confidential && model.AllowClientCredentialsFlow)
            {
                roleNames = model.RoleEntries.Where(r => r.Selected).Select(r => r.Name).ToList();
            }

            var application = new OpenIdApplication
            {
                DisplayName       = model.DisplayName,
                RedirectUri       = model.RedirectUri,
                LogoutRedirectUri = model.LogoutRedirectUri,
                ClientId          = model.ClientId,
                Type        = model.Type,
                SkipConsent = model.SkipConsent,
                RoleNames   = roleNames,
                AllowAuthorizationCodeFlow = model.AllowAuthorizationCodeFlow,
                AllowClientCredentialsFlow = model.AllowClientCredentialsFlow,
                AllowImplicitFlow          = model.AllowImplicitFlow,
                AllowPasswordFlow          = model.AllowPasswordFlow,
                AllowRefreshTokenFlow      = model.AllowRefreshTokenFlow,
                AllowHybridFlow            = model.AllowHybridFlow
            };

            await _applicationManager.CreateAsync(application, model.ClientSecret, HttpContext.RequestAborted);

            if (string.IsNullOrEmpty(returnUrl))
            {
                return(RedirectToAction("Index"));
            }
            return(LocalRedirect(returnUrl));
        }
        public async Task <IActionResult> Create(CreateOpenIdApplicationViewModel model, string returnUrl = null)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageApplications))
            {
                return(Unauthorized());
            }

            if (!string.IsNullOrEmpty(model.ClientSecret) &&
                string.Equals(model.Type, OpenIddictConstants.ClientTypes.Public, StringComparison.OrdinalIgnoreCase))
            {
                ModelState.AddModelError(nameof(model.ClientSecret), T["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), T["The client secret is required for confidential applications."]);
            }

            if (!string.IsNullOrEmpty(model.ClientId) && await _applicationManager.FindByClientIdAsync(model.ClientId) != null)
            {
                ModelState.AddModelError(nameof(model.ClientId), T["The client identifier is already taken by another application."]);
            }

            if (!ModelState.IsValid)
            {
                ViewData[nameof(OpenIdServerSettings)] = await GetServerSettingsAsync();

                ViewData["ReturnUrl"] = returnUrl;
                return(View(model));
            }

            var descriptor = new OpenIdApplicationDescriptor
            {
                ClientId     = model.ClientId,
                ClientSecret = model.ClientSecret,
                ConsentType  = model.ConsentType,
                DisplayName  = model.DisplayName,
                Type         = model.Type
            };

            if (model.AllowLogoutEndpoint)
            {
                descriptor.Permissions.Add(OpenIddictConstants.Permissions.Endpoints.Logout);
            }
            else
            {
                descriptor.Permissions.Remove(OpenIddictConstants.Permissions.Endpoints.Logout);
            }

            if (model.AllowAuthorizationCodeFlow)
            {
                descriptor.Permissions.Add(OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode);
            }
            if (model.AllowClientCredentialsFlow)
            {
                descriptor.Permissions.Add(OpenIddictConstants.Permissions.GrantTypes.ClientCredentials);
            }
            if (model.AllowImplicitFlow)
            {
                descriptor.Permissions.Add(OpenIddictConstants.Permissions.GrantTypes.Implicit);
            }
            if (model.AllowPasswordFlow)
            {
                descriptor.Permissions.Add(OpenIddictConstants.Permissions.GrantTypes.Password);
            }
            if (model.AllowRefreshTokenFlow)
            {
                descriptor.Permissions.Add(OpenIddictConstants.Permissions.GrantTypes.RefreshToken);
            }
            if (model.AllowAuthorizationCodeFlow || model.AllowImplicitFlow)
            {
                descriptor.Permissions.Add(OpenIddictConstants.Permissions.Endpoints.Authorization);
            }
            if (model.AllowAuthorizationCodeFlow || model.AllowClientCredentialsFlow ||
                model.AllowPasswordFlow || model.AllowRefreshTokenFlow)
            {
                descriptor.Permissions.Add(OpenIddictConstants.Permissions.Endpoints.Token);
            }

            descriptor.PostLogoutRedirectUris.UnionWith(
                from uri in model.PostLogoutRedirectUris?.Split(new[] { " ", "," }, StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty <string>()
                select new Uri(uri, UriKind.Absolute));

            descriptor.RedirectUris.UnionWith(
                from uri in model.RedirectUris?.Split(new[] { " ", "," }, StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty <string>()
                select new Uri(uri, UriKind.Absolute));

            descriptor.Roles.UnionWith(model.RoleEntries
                                       .Where(role => role.Selected)
                                       .Select(role => role.Name));

            await _applicationManager.CreateAsync(descriptor);

            if (string.IsNullOrEmpty(returnUrl))
            {
                return(RedirectToAction("Index"));
            }

            return(LocalRedirect(returnUrl));
        }
示例#11
0
        public virtual async Task <IOpenIdApplication> CreateAsync(
            CreateOpenIdApplicationViewModel model, CancellationToken cancellationToken = default)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var application = await Store.InstantiateAsync(cancellationToken);

            if (application == null)
            {
                throw new InvalidOperationException("An error occurred while trying to create a new application");
            }

            await Store.SetClientIdAsync(application, model.ClientId, cancellationToken);

            await Store.SetClientSecretAsync(application, model.ClientSecret, cancellationToken);

            await Store.SetClientTypeAsync(application, model.Type.ToString().ToLowerInvariant(), cancellationToken);

            await Store.SetDisplayNameAsync(application, model.DisplayName, cancellationToken);

            await Store.SetConsentTypeAsync(application, model.SkipConsent?
                                            OpenIddictConstants.ConsentTypes.Implicit :
                                            OpenIddictConstants.ConsentTypes.Explicit, cancellationToken);

            if (!string.IsNullOrEmpty(model.LogoutRedirectUri))
            {
                await Store.SetPostLogoutRedirectUrisAsync(application, ImmutableArray.Create(model.LogoutRedirectUri), cancellationToken);
            }

            if (!string.IsNullOrEmpty(model.RedirectUri))
            {
                await Store.SetRedirectUrisAsync(application, ImmutableArray.Create(model.RedirectUri), cancellationToken);
            }

            var permissions = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            if (model.AllowAuthorizationCodeFlow)
            {
                permissions.Add(OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode);
            }

            if (model.AllowClientCredentialsFlow)
            {
                permissions.Add(OpenIddictConstants.Permissions.GrantTypes.ClientCredentials);
            }

            if (model.AllowImplicitFlow)
            {
                permissions.Add(OpenIddictConstants.Permissions.GrantTypes.Implicit);
            }

            if (model.AllowPasswordFlow)
            {
                permissions.Add(OpenIddictConstants.Permissions.GrantTypes.Password);
            }

            if (model.AllowRefreshTokenFlow)
            {
                permissions.Add(OpenIddictConstants.Permissions.GrantTypes.RefreshToken);
            }

            if (model.AllowAuthorizationCodeFlow || model.AllowImplicitFlow)
            {
                permissions.Add(OpenIddictConstants.Permissions.Endpoints.Authorization);
            }

            if (model.AllowAuthorizationCodeFlow || model.AllowClientCredentialsFlow ||
                model.AllowPasswordFlow || model.AllowRefreshTokenFlow)
            {
                permissions.Add(OpenIddictConstants.Permissions.Endpoints.Token);
            }

            await Store.SetPermissionsAsync(application, permissions.ToImmutableArray(), cancellationToken);

            await Store.SetRolesAsync(application, model.RoleEntries
                                      .Where(role => role.Selected)
                                      .Select(role => role.Name)
                                      .ToImmutableArray(), cancellationToken);

            var secret = await Store.GetClientSecretAsync(application, cancellationToken);

            if (!string.IsNullOrEmpty(secret))
            {
                await Store.SetClientSecretAsync(application, /* secret: */ null, cancellationToken);
                await CreateAsync(application, secret, cancellationToken);
            }
            else
            {
                await CreateAsync(application, cancellationToken);
            }

            return(application);
        }