Example #1
0
        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());
            }

            Task <bool> HasPermissionAsync(string permission) => _applicationManager.HasPermissionAsync(application, permission);

            var model = new EditOpenIdApplicationViewModel
            {
                AllowAuthorizationCodeFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode),
                AllowClientCredentialsFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.ClientCredentials),
                AllowImplicitFlow          = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.Implicit),
                AllowPasswordFlow          = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.Password),
                AllowRefreshTokenFlow      = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.RefreshToken),
                AllowLogoutEndpoint        = await HasPermissionAsync(OpenIddictConstants.Permissions.Endpoints.Logout),
                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)
            };

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

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

            ViewData["ReturnUrl"] = returnUrl;
            return(View(model));
        }
Example #2
0
        public async Task <IActionResult> Edit(string id, string returnUrl = null)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageApplications))
            {
                return(Unauthorized());
            }

            var application = await _applicationManager.FindByPhysicalIdAsync(id);

            if (application == null)
            {
                return(NotFound());
            }

            Task <bool> HasPermissionAsync(string permission) => _applicationManager.HasPermissionAsync(application, permission);

            var model = new EditOpenIdApplicationViewModel
            {
                AllowAuthorizationCodeFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode),
                AllowClientCredentialsFlow = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.ClientCredentials),
                AllowImplicitFlow          = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.Implicit),
                AllowPasswordFlow          = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.Password),
                AllowRefreshTokenFlow      = await HasPermissionAsync(OpenIddictConstants.Permissions.GrantTypes.RefreshToken),
                AllowLogoutEndpoint        = await HasPermissionAsync(OpenIddictConstants.Permissions.Endpoints.Logout),
                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)
            };

            foreach (var role in await _roleProvider.GetRoleNamesAsync())
            {
                model.RoleEntries.Add(new EditOpenIdApplicationViewModel.RoleEntry
                {
                    Name     = role,
                    Selected = await _applicationManager.IsInRoleAsync(application, role)
                });
            }

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

            ViewData["ReturnUrl"] = returnUrl;
            return(View(model));
        }
Example #3
0
        public async Task <IActionResult> Authorize(OpenIdConnectRequest request)
        {
            // Retrieve the claims stored in the authentication cookie.
            // If they can't be extracted, redirect the user to the login page.
            var result = await HttpContext.AuthenticateAsync();

            if (result == null || !result.Succeeded || request.HasPrompt(OpenIddictConstants.Prompts.Login))
            {
                return(RedirectToLoginPage(request));
            }

            // If a max_age parameter was provided, ensure that the cookie is not too old.
            // If it's too old, automatically redirect the user agent to the login page.
            if (request.MaxAge != null && result.Properties.IssuedUtc != null &&
                DateTimeOffset.UtcNow - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value))
            {
                return(RedirectToLoginPage(request));
            }

            var application = await _applicationManager.FindByClientIdAsync(request.ClientId);

            if (application == null)
            {
                return(View("Error", new ErrorViewModel
                {
                    Error = OpenIddictConstants.Errors.InvalidClient,
                    ErrorDescription = T["The specified 'client_id' parameter is invalid."]
                }));
            }

            var authorizations = await _authorizationManager.FindAsync(
                subject : _userManager.GetUserId(result.Principal),
                client : await _applicationManager.GetIdAsync(application),
                status : OpenIddictConstants.Statuses.Valid,
                type : OpenIddictConstants.AuthorizationTypes.Permanent,
                scopes : ImmutableArray.CreateRange(request.GetScopes()));

            switch (await _applicationManager.GetConsentTypeAsync(application))
            {
            case OpenIddictConstants.ConsentTypes.External when authorizations.IsEmpty:
                return(RedirectToClient(new OpenIdConnectResponse
                {
                    Error = OpenIddictConstants.Errors.ConsentRequired,
                    ErrorDescription = T["The logged in user is not allowed to access this client application."]
                }));

            case OpenIddictConstants.ConsentTypes.Implicit:
            case OpenIddictConstants.ConsentTypes.External when authorizations.Any():
            case OpenIddictConstants.ConsentTypes.Explicit when authorizations.Any() &&
                !request.HasPrompt(OpenIddictConstants.Prompts.Consent):
                return(await IssueTokensAsync(result.Principal, request, application, authorizations.LastOrDefault()));

            case OpenIddictConstants.ConsentTypes.Explicit when request.HasPrompt(OpenIddictConstants.Prompts.None):
                return(RedirectToClient(new OpenIdConnectResponse
                {
                    Error = OpenIddictConstants.Errors.ConsentRequired,
                    ErrorDescription = T["Interactive user consent is required."]
                }));

            default:
                return(View(new AuthorizeViewModel
                {
                    ApplicationName = await _applicationManager.GetDisplayNameAsync(application),
                    RequestId = request.RequestId,
                    Scope = request.Scope
                }));
            }
        }
Example #4
0
        public async Task <IActionResult> Authorize()
        {
            var response = HttpContext.GetOpenIddictServerResponse();

            if (response != null)
            {
                return(View("Error", new ErrorViewModel
                {
                    Error = response.Error,
                    ErrorDescription = response.ErrorDescription
                }));
            }

            var request = HttpContext.GetOpenIddictServerRequest();

            if (request == null)
            {
                return(NotFound());
            }

            // Retrieve the claims stored in the authentication cookie.
            // If they can't be extracted, redirect the user to the login page.
            var result = await HttpContext.AuthenticateAsync();

            if (result == null || !result.Succeeded || request.HasPrompt(Prompts.Login))
            {
                return(RedirectToLoginPage(request));
            }

            // If a max_age parameter was provided, ensure that the cookie is not too old.
            // If it's too old, automatically redirect the user agent to the login page.
            if (request.MaxAge != null && result.Properties.IssuedUtc != null &&
                DateTimeOffset.UtcNow - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value))
            {
                return(RedirectToLoginPage(request));
            }

            var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ??
                              throw new InvalidOperationException("The application details cannot be found.");

            var authorizations = await _authorizationManager.FindAsync(
                subject : result.Principal.GetUserIdentifier(),
                client : await _applicationManager.GetIdAsync(application),
                status : Statuses.Valid,
                type : AuthorizationTypes.Permanent,
                scopes : request.GetScopes()).ToListAsync();

            switch (await _applicationManager.GetConsentTypeAsync(application))
            {
            case ConsentTypes.External when !authorizations.Any():
                return(Forbid(new AuthenticationProperties(new Dictionary <string, string>
                {
                    [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired,
                    [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
                        S["The logged in user is not allowed to access this client application."]
                }), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));

            case ConsentTypes.Implicit:
            case ConsentTypes.External when authorizations.Any():
            case ConsentTypes.Explicit when authorizations.Any() && !request.HasPrompt(Prompts.Consent):
                var identity = new ClaimsIdentity(result.Principal.Claims, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);

                var principal = new ClaimsPrincipal(identity);

                identity.AddClaim(OpenIdConstants.Claims.EntityType, OpenIdConstants.EntityTypes.User,
                                  Destinations.AccessToken, Destinations.IdentityToken);

                // Note: while ASP.NET Core Identity uses the legacy WS-Federation claims (exposed by the ClaimTypes class),
                // OpenIddict uses the newer JWT claims defined by the OpenID Connect specification. To ensure the mandatory
                // subject claim is correctly populated (and avoid an InvalidOperationException), it's manually added here.
                if (string.IsNullOrEmpty(result.Principal.FindFirst(Claims.Subject)?.Value))
                {
                    identity.AddClaim(new Claim(Claims.Subject, result.Principal.GetUserIdentifier()));
                }

                principal.SetScopes(request.GetScopes());
                principal.SetResources(await GetResourcesAsync(request.GetScopes()));

                // Automatically create a permanent authorization to avoid requiring explicit consent
                // for future authorization or token requests containing the same scopes.
                var authorization = authorizations.LastOrDefault();
                if (authorization == null)
                {
                    authorization = await _authorizationManager.CreateAsync(
                        principal : principal,
                        subject : principal.GetUserIdentifier(),
                        client : await _applicationManager.GetIdAsync(application),
                        type : AuthorizationTypes.Permanent,
                        scopes : principal.GetScopes());
                }

                principal.SetAuthorizationId(await _authorizationManager.GetIdAsync(authorization));

                foreach (var claim in principal.Claims)
                {
                    claim.SetDestinations(GetDestinations(claim, principal));
                }

                return(SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));

            case ConsentTypes.Explicit when request.HasPrompt(Prompts.None):
                return(Forbid(new AuthenticationProperties(new Dictionary <string, string>
                {
                    [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired,
                    [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
                        S["Interactive user consent is required."]
                }), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));

            default:
                return(View(new AuthorizeViewModel
                {
                    ApplicationName = await _applicationManager.GetLocalizedDisplayNameAsync(application),
                    RequestId = request.RequestId,
                    Scope = request.Scope
                }));
            }

            IActionResult RedirectToLoginPage(OpenIddictRequest request)
            {
                // If the client application requested promptless authentication,
                // return an error indicating that the user is not logged in.
                if (request.HasPrompt(Prompts.None))
                {
                    return(Forbid(new AuthenticationProperties(new Dictionary <string, string>
                    {
                        [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.LoginRequired,
                        [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
                            S["The user is not logged in."]
                    }), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));
                }

                string GetRedirectUrl()
                {
                    // Override the prompt parameter to prevent infinite authentication/authorization loops.
                    var parameters = Request.Query.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

                    parameters[Parameters.Prompt] = "continue";

                    return(Request.PathBase + Request.Path + QueryString.Create(parameters));
                }

                return(Challenge(new AuthenticationProperties
                {
                    RedirectUri = GetRedirectUrl()
                }));
            }
        }
        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);

            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),
                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)
            };

            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));
        }