예제 #1
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            using IServiceScope scope = _serviceProvider.CreateScope();

            QuorraDbContext context = scope.ServiceProvider.GetRequiredService <QuorraDbContext>();
            await context.Database.EnsureCreatedAsync(cancellationToken);

            IOpenIddictApplicationManager manager = scope.ServiceProvider.GetRequiredService <IOpenIddictApplicationManager>();

            if (await manager.FindByClientIdAsync("console", cancellationToken) is null)
            {
                await manager.CreateAsync(new OpenIddictApplicationDescriptor
                {
                    ClientId     = "console",
                    ClientSecret = "388D45FA-B36B-4988-BA59-B187D329C207",
                    DisplayName  = "My client application",
                    Permissions  =
                    {
                        OpenIddictConstants.Permissions.Endpoints.Token,
                        OpenIddictConstants.Permissions.GrantTypes.ClientCredentials,
                        OpenIddictConstants.Permissions.GrantTypes.RefreshToken,
                        OpenIddictConstants.Permissions.Prefixes.Scope + "api"
                    }
                }, cancellationToken);
            }

            if (await manager.FindByClientIdAsync("postman", cancellationToken) is null)
            {
                await manager.CreateAsync(new OpenIddictApplicationDescriptor
                {
                    ClientId     = "postman",
                    ClientSecret = "postman-secret",
                    DisplayName  = "Postman",
                    RedirectUris = { new Uri("https://oauth.pstmn.io/v1/callback") },
                    Permissions  =
                    {
                        OpenIddictConstants.Permissions.Endpoints.Authorization,
                        OpenIddictConstants.Permissions.Endpoints.Token,

                        OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode,
                        OpenIddictConstants.Permissions.GrantTypes.ClientCredentials,
                        OpenIddictConstants.Permissions.GrantTypes.RefreshToken,

                        OpenIddictConstants.Permissions.Prefixes.Scope + "api",
                        OpenIddictConstants.Permissions.ResponseTypes.Code
                    }
                }, cancellationToken);
            }
        }
예제 #2
0
        public async Task <IActionResult> Authorize()
        {
            var request = HttpContext.GetOpenIddictServerRequest() ??
                          throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");

            if (string.IsNullOrEmpty(request.ClientId))
            {
                throw new InvalidOperationException("Details concerning the calling client application are not valid.");
            }

            var result = await HttpContext.AuthenticateAsync(IdentityConstants.ApplicationScheme);

            if (!result.Succeeded || (request.MaxAge != null && result.Properties?.IssuedUtc != null && DateTimeOffset.UtcNow - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value)))
            {
                return(Challenge(
                           authenticationSchemes: IdentityConstants.ApplicationScheme,
                           properties: new AuthenticationProperties
                {
                    RedirectUri = Request.PathBase + Request.Path + QueryString.Create(
                        Request.HasFormContentType ? Request.Form.ToList() : Request.Query.ToList())
                }));
            }

            var user = await _user.GetUserAsync(result.Principal) ??
                       throw new InvalidOperationException("The user details cannot be retrieved.");

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

            if (application == null)
            {
                throw new InvalidOperationException("Details concerning the calling client application cannot be found.");
            }

            var principal = await _sign.CreateUserPrincipalAsync(user) ??
                            throw new InvalidOperationException("Cannot construct principal for the current user.");

            principal.SetScopes(request.GetScopes());
            principal.SetResources(await _scope.ListResourcesAsync(request.GetScopes()).ToListAsync());

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

            var authorization = await _authorization.CreateAsync(
                principal : principal,
                subject : user.Id,
                client : await _application.GetIdAsync(application) ?? throw new InvalidOperationException(),
                type : OpenIddictConstants.AuthorizationTypes.Permanent,
                scopes : principal.GetScopes());

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

            return(SignIn(principal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));
        }
예제 #3
0
        private async static Task CreateIfNotExistAndSeedDatabase(IOpenIddictApplicationManager applicationManager)
        {
            var clientId = "BlazorApp13";
            var app      = await applicationManager.FindByClientIdAsync(clientId);

            if (app is null)
            {
                if (await applicationManager.FindByClientIdAsync(clientId) is null)
                {
                    var descriptor = new OpenIddictApplicationDescriptor
                    {
                        ClientId               = clientId,
                        DisplayName            = "Blazor App 13",
                        RedirectUris           = { new Uri($"{HOSTNAME}/authentication/login-callback") },
                        PostLogoutRedirectUris = { new Uri($"{HOSTNAME}/authentication/logout-callback") },
                        //ConsentType = OpenIddictConstants.ConsentTypes.Implicit,
                        Permissions =
                        {
                            OpenIddictConstants.Permissions.Endpoints.Authorization,
                            OpenIddictConstants.Permissions.Endpoints.Token,
                            OpenIddictConstants.Permissions.Endpoints.Logout,
                            OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode,
                            OpenIddictConstants.Permissions.GrantTypes.RefreshToken,
                            OpenIddictConstants.Permissions.Scopes.Email,
                            OpenIddictConstants.Permissions.Scopes.Profile,
                            OpenIddictConstants.Permissions.Scopes.Roles
                        },
                        Requirements =
                        {
                            OpenIddictConstants.Requirements.Features.ProofKeyForCodeExchange
                        }
                    };

                    await applicationManager.CreateAsync(descriptor);
                }
            }
        }
        public async Task <IActionResult> Verify()
        {
            var request = HttpContext.GetOpenIddictServerRequest() ??
                          throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");

            // If the user code was not specified in the query string (e.g as part of the verification_uri_complete),
            // render a form to ask the user to enter the user code manually (non-digit chars are automatically ignored).
            if (string.IsNullOrEmpty(request.UserCode))
            {
                return(View("/Pages/_Verify.cshtml", new VerifyViewModel()));
            }

            // Retrieve the claims principal associated with the user code.
            var result = await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);

            if (result.Succeeded)
            {
                // Retrieve the application details from the database using the client_id stored in the principal.
                var application = await _applicationManager.FindByClientIdAsync(result.Principal.GetClaim(Claims.ClientId)) ??
                                  throw new InvalidOperationException("Details concerning the calling client application cannot be found.");

                // Render a form asking the user to confirm the authorization demand.
                return(View("/Pages/_Verify.cshtml", new VerifyViewModel
                {
                    ApplicationName = await _applicationManager.GetLocalizedDisplayNameAsync(application),
                    Scope = string.Join(" ", result.Principal.GetScopes()),
                    UserCode = request.UserCode
                }));
            }

            // Redisplay the form when the user code is not valid.
            return(View("/Pages/_Verify.cshtml", new VerifyViewModel
            {
                Error = Errors.InvalidToken,
                ErrorDescription = "The specified user code is not valid. Please make sure you typed it correctly."
            }));
        }
        public async Task DeleteAsync(string clientId)
        {
            var userTenantId = _tenantIdProvider.GetTenantId().ToString();

            var app = (await _oidcAppManager.FindByClientIdAsync(clientId) as PskApplication);

            if (app != null && app.TenantId == userTenantId)
            {
                await _oidcAppManager.DeleteAsync(app);

                return;
            }

            throw new ItemNotFoundException(clientId, "Workplace");
        }
예제 #6
0
        public static async Task AddClient(this IOpenIddictApplicationManager manager, Action <OpenIddictApplicationDescriptor> descriptor, CancellationToken cancellationToken = default)
        {
            var application = new OpenIddictApplicationDescriptor();

            descriptor(application);

            if (string.IsNullOrEmpty(application.ClientId))
            {
                throw new ArgumentNullException();
            }

            if (await manager.FindByClientIdAsync(application.ClientId, cancellationToken) is not null)
            {
                return;
            }

            await manager.CreateAsync(application, cancellationToken);
        }
예제 #7
0
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            if (await _manager.FindByClientIdAsync(model.ClientId) == null)
            {
                var descriptor = new OpenIddictApplicationDescriptor
                {
                    ClientId               = model.ClientId,
                    ClientSecret           = model.ClientSecret,
                    DisplayName            = model.DisplayName,
                    PostLogoutRedirectUris = { model.PostLogoutRedirectUris },
                    RedirectUris           = { model.RedirectUris },
                    Permissions            =
                    {
                        OpenIddictConstants.Permissions.Endpoints.Authorization,
                        OpenIddictConstants.Permissions.Endpoints.Logout,
                        OpenIddictConstants.Permissions.Endpoints.Token,
                        OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode,
                        OpenIddictConstants.Permissions.GrantTypes.RefreshToken,
                        OpenIddictConstants.Permissions.Scopes.Email,
                        CustomScopes.PermissionMeasurements(),
                        CustomScopes.PermissionGender(),
                        CustomScopes.PermissionName()
                    }
                };
                var setApplicationResult = _manager.CreateAsync(descriptor);
                if (!setApplicationResult.IsFaulted)
                {
                    StatusMessage = "Your application has been registered";
                    return(RedirectToAction(nameof(Register)));
                }

                ModelState.AddModelError(String.Empty, setApplicationResult.Exception.Message);
            }
            //if we get here something is wrong re displaying form.
            StatusMessage = "Error: Something went wrong";
            return(RedirectToAction(nameof(Register)));
        }
        public async Task <IActionResult> Authorize()
        {
            var request = HttpContext.GetOpenIddictServerRequest() ??
                          throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");

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

            if (result is null || !result.Succeeded)
            {
                // 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(
                               authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                               properties: new AuthenticationProperties(new Dictionary <string, string>
                    {
                        [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.LoginRequired,
                        [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The user is not logged in."
                    })));
                }

                return(Challenge(
                           authenticationSchemes: IdentityConstants.ApplicationScheme,
                           properties: new AuthenticationProperties
                {
                    RedirectUri = Request.PathBase + Request.Path + QueryString.Create(
                        Request.HasFormContentType ? Request.Form.ToList() : Request.Query.ToList())
                }));
            }

            // If prompt=login was specified by the client application,
            // immediately return the user agent to the login page.
            if (request.HasPrompt(Prompts.Login))
            {
                // To avoid endless login -> authorization redirects, the prompt=login flag
                // is removed from the authorization request payload before redirecting the user.
                var prompt = string.Join(" ", request.GetPrompts().Remove(Prompts.Login));

                var parameters = Request.HasFormContentType ?
                                 Request.Form.Where(parameter => parameter.Key != Parameters.Prompt).ToList() :
                                 Request.Query.Where(parameter => parameter.Key != Parameters.Prompt).ToList();

                parameters.Add(KeyValuePair.Create(Parameters.Prompt, new StringValues(prompt)));

                return(Challenge(
                           authenticationSchemes: IdentityConstants.ApplicationScheme,
                           properties: new AuthenticationProperties
                {
                    RedirectUri = Request.PathBase + Request.Path + QueryString.Create(parameters)
                }));
            }

            // 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 is not null && result.Properties?.IssuedUtc is not null &&
                DateTimeOffset.UtcNow - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value))
            {
                if (request.HasPrompt(Prompts.None))
                {
                    return(Forbid(
                               authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                               properties: new AuthenticationProperties(new Dictionary <string, string>
                    {
                        [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.LoginRequired,
                        [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The user is not logged in."
                    })));
                }

                return(Challenge(
                           authenticationSchemes: IdentityConstants.ApplicationScheme,
                           properties: new AuthenticationProperties
                {
                    RedirectUri = Request.PathBase + Request.Path + QueryString.Create(
                        Request.HasFormContentType ? Request.Form.ToList() : Request.Query.ToList())
                }));
            }

            // Retrieve the profile of the logged in user.
            var user = await _userProvider.GetUserAsync(result.Principal) ??
                       throw new InvalidOperationException("The user details cannot be retrieved.");

            // Retrieve the application details from the database.
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ??
                              throw new InvalidOperationException("Details concerning the calling client application cannot be found.");

            // Retrieve the permanent authorizations associated with the user and the calling client application.
            var authorizations = await _authorizationManager.FindAsync(
                subject : await _userProvider.GetUserIdAsync(user),
                client : await _applicationManager.GetIdAsync(application),
                status : Statuses.Valid,
                type : AuthorizationTypes.Permanent,
                scopes : request.GetScopes()).ToListAsync();

            switch (await _applicationManager.GetConsentTypeAsync(application))
            {
            // If the consent is external (e.g when authorizations are granted by a sysadmin),
            // immediately return an error if no authorization can be found in the database.
            case ConsentTypes.External when !authorizations.Any():
                return(Forbid(
                           authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                           properties: new AuthenticationProperties(new Dictionary <string, string>
                {
                    [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired,
                    [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
                        "The logged in user is not allowed to access this client application."
                })));

            // If the consent is implicit or if an authorization was found,
            // return an authorization response without displaying the consent form.
            case ConsentTypes.Implicit:
            case ConsentTypes.External when authorizations.Any():
            case ConsentTypes.Explicit when authorizations.Any() && !request.HasPrompt(Prompts.Consent):
                var principal = await _userProvider.CreateUserPrincipalAsync(user);

                // Note: in this sample, the granted scopes match the requested scope
                // but you may want to allow the user to uncheck specific scopes.
                // For that, simply restrict the list of scopes before calling SetScopes.
                principal.SetScopes(request.GetScopes());
                principal.SetResources(await _scopeManager.ListResourcesAsync(principal.GetScopes()).ToListAsync());

                // 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 is null)
                {
                    authorization = await _authorizationManager.CreateAsync(
                        principal : principal,
                        subject : await _userProvider.GetUserIdAsync(user),
                        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));

            // At this point, no authorization was found in the database and an error must be returned
            // if the client application specified prompt=none in the authorization request.
            case ConsentTypes.Explicit when request.HasPrompt(Prompts.None):
            case ConsentTypes.Systematic when request.HasPrompt(Prompts.None):
                return(Forbid(
                           authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                           properties: new AuthenticationProperties(new Dictionary <string, string>
                {
                    [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired,
                    [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
                        "Interactive user consent is required."
                })));

            // In every other case, render the consent form.
            default:
                return(View(new AuthorizeViewModel
                {
                    ApplicationName = await _applicationManager.GetLocalizedDisplayNameAsync(application),
                    Scope = request.Scope
                }));
            }
        }
    public async Task <IActionResult> Authorize()
    {
        var request = HttpContext.GetOpenIddictServerRequest() ??
                      throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");

        // Try to retrieve the user principal stored in the authentication cookie and redirect
        // the user agent to the login page (or to an external provider) in the following cases:
        //
        //  - If the user principal can't be extracted or the cookie is too old.
        //  - If prompt=login was specified by the client application.
        //  - If a max_age parameter was provided and the authentication cookie is not considered "fresh" enough.
        var result = await HttpContext.AuthenticateAsync(IdentityConstants.ApplicationScheme);

        if (result == null || !result.Succeeded || request.HasPrompt(Prompts.Login) ||
            (request.MaxAge != null && result.Properties?.IssuedUtc != null &&
             DateTimeOffset.UtcNow - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value)))
        {
            // 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(
                           authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                           properties: new AuthenticationProperties(new Dictionary <string, string>
                {
                    [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.LoginRequired,
                    [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The user is not logged in."
                })));
            }

            // To avoid endless login -> authorization redirects, the prompt=login flag
            // is removed from the authorization request payload before redirecting the user.
            var prompt = string.Join(" ", request.GetPrompts().Remove(Prompts.Login));

            var parameters = Request.HasFormContentType ?
                             Request.Form.Where(parameter => parameter.Key != Parameters.Prompt).ToList() :
                             Request.Query.Where(parameter => parameter.Key != Parameters.Prompt).ToList();

            parameters.Add(KeyValuePair.Create(Parameters.Prompt, new StringValues(prompt)));

            // For applications that want to allow the client to select the external authentication provider
            // that will be used to authenticate the user, the identity_provider parameter can be used for that.
            if (!string.IsNullOrEmpty(request.IdentityProvider))
            {
                var issuer = request.IdentityProvider switch
                {
                    "github" => "https://github.com/",

                    _ => null
                };

                if (string.IsNullOrEmpty(issuer))
                {
                    return(Forbid(
                               authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                               properties: new AuthenticationProperties(new Dictionary <string, string>
                    {
                        [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidRequest,
                        [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
                            "The specified identity provider is not valid."
                    })));
                }

                var properties = _signInManager.ConfigureExternalAuthenticationProperties(
                    provider: issuer,
                    redirectUrl: Url.Action("ExternalLoginCallback", "Account", new
                {
                    ReturnUrl = Request.PathBase + Request.Path + QueryString.Create(parameters)
                }));

                // Note: when only one client is registered in the client options,
                // setting the issuer property is not required and can be omitted.
                properties.SetString(OpenIddictClientAspNetCoreConstants.Properties.Issuer, issuer);

                // Ask the OpenIddict client middleware to redirect the user agent to the identity provider.
                return(Challenge(properties, OpenIddictClientAspNetCoreDefaults.AuthenticationScheme));
            }

            return(Challenge(
                       authenticationSchemes: IdentityConstants.ApplicationScheme,
                       properties: new AuthenticationProperties
            {
                RedirectUri = Request.PathBase + Request.Path + QueryString.Create(parameters)
            }));
        }

        // Retrieve the profile of the logged in user.
        var user = await _userManager.GetUserAsync(result.Principal) ??
                   throw new InvalidOperationException("The user details cannot be retrieved.");

        // Retrieve the application details from the database.
        var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ??
                          throw new InvalidOperationException("Details concerning the calling client application cannot be found.");

        // Retrieve the permanent authorizations associated with the user and the calling client application.
        var authorizations = await _authorizationManager.FindAsync(
            subject : await _userManager.GetUserIdAsync(user),
            client : await _applicationManager.GetIdAsync(application),
            status : Statuses.Valid,
            type : AuthorizationTypes.Permanent,
            scopes : request.GetScopes()).ToListAsync();

        switch (await _applicationManager.GetConsentTypeAsync(application))
        {
        // If the consent is external (e.g when authorizations are granted by a sysadmin),
        // immediately return an error if no authorization can be found in the database.
        case ConsentTypes.External when !authorizations.Any():
            return(Forbid(
                       authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                       properties: new AuthenticationProperties(new Dictionary <string, string>
            {
                [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired,
                [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
                    "The logged in user is not allowed to access this client application."
            })));

        // If the consent is implicit or if an authorization was found,
        // return an authorization response without displaying the consent form.
        case ConsentTypes.Implicit:
        case ConsentTypes.External when authorizations.Any():
        case ConsentTypes.Explicit when authorizations.Any() && !request.HasPrompt(Prompts.Consent):
            // Create the claims-based identity that will be used by OpenIddict to generate tokens.
            var identity = new ClaimsIdentity(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)
                           .AddClaim(Claims.Subject, await _userManager.GetUserIdAsync(user))
                           .AddClaim(Claims.Email, await _userManager.GetEmailAsync(user))
                           .AddClaim(Claims.Name, await _userManager.GetUserNameAsync(user))
                           .AddClaims(Claims.Role, (await _userManager.GetRolesAsync(user)).ToImmutableArray());

            // Note: in this sample, the granted scopes match the requested scope
            // but you may want to allow the user to uncheck specific scopes.
            // For that, simply restrict the list of scopes before calling SetScopes.
            identity.SetScopes(request.GetScopes());
            identity.SetResources(await _scopeManager.ListResourcesAsync(identity.GetScopes()).ToListAsync());

            // 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 is null)
            {
                authorization = await _authorizationManager.CreateAsync(
                    principal : new ClaimsPrincipal(identity),
                    subject : await _userManager.GetUserIdAsync(user),
                    client : await _applicationManager.GetIdAsync(application),
                    type : AuthorizationTypes.Permanent,
                    scopes : identity.GetScopes());
            }

            identity.SetAuthorizationId(await _authorizationManager.GetIdAsync(authorization));
            identity.SetDestinations(GetDestinations);

            return(SignIn(new ClaimsPrincipal(identity), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));

        // At this point, no authorization was found in the database and an error must be returned
        // if the client application specified prompt=none in the authorization request.
        case ConsentTypes.Explicit   when request.HasPrompt(Prompts.None):
        case ConsentTypes.Systematic when request.HasPrompt(Prompts.None):
            return(Forbid(
                       authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
                       properties: new AuthenticationProperties(new Dictionary <string, string>
            {
                [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.ConsentRequired,
                [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
                    "Interactive user consent is required."
            })));

        // In every other case, render the consent form.
        default: return(View(new AuthorizeViewModel
            {
                ApplicationName = await _applicationManager.GetLocalizedDisplayNameAsync(application),
                Scope = request.Scope
            }));
        }
    }
예제 #10
0
        public async Task <IActionResult> Exchange()
        {
            var request = HttpContext.GetOpenIddictServerRequest();

            if (request == null)
            {
                throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");
            }

            if (request.IsAuthorizationCodeGrantType() || request.IsRefreshTokenGrantType() || request.IsImplicitFlow())
            {
                var principal = (await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)).Principal;
                if (principal == null)
                {
                    throw new InvalidOperationException("The user details cannot be retrieved.");
                }

                var user = await userService.GetAsync(principal, HttpContext.RequestAborted);

                if (user == null)
                {
                    return(Forbid(
                               new AuthenticationProperties(new Dictionary <string, string?>
                    {
                        [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidGrant,
                        [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The token is no longer valid."
                    }),
                               OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));
                }

                if (!await SignInManager.CanSignInAsync((IdentityUser)user.Identity))
                {
                    return(Forbid(
                               new AuthenticationProperties(new Dictionary <string, string?>
                    {
                        [OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidGrant,
                        [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = "The user is no longer allowed to sign in."
                    }),
                               OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));
                }

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

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

            if (request.IsClientCredentialsGrantType())
            {
                if (request.ClientId == null)
                {
                    throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");
                }

                var application = await applicationManager.FindByClientIdAsync(request.ClientId, HttpContext.RequestAborted);

                if (application == null)
                {
                    throw new InvalidOperationException("The application details cannot be found in the database.");
                }

                var principal = await CreateApplicationPrincipalAsync(request, application);

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

            throw new InvalidOperationException("The specified grant type is not supported.");
        }
예제 #11
0
        public async Task <ActionResult> Authorize()
        {
            var context = HttpContext.GetOwinContext();
            var request = context.GetOpenIddictServerRequest() ??
                          throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");

            // Retrieve the user principal stored in the authentication cookie.
            // If a max_age parameter was provided, ensure that the cookie is not too old.
            // If the user principal can't be extracted or the cookie is too old, redirect the user to the login page.
            var result = await context.Authentication.AuthenticateAsync(DefaultAuthenticationTypes.ApplicationCookie);

            if (result?.Identity == null || (request.MaxAge != null && result.Properties?.IssuedUtc != null &&
                                             DateTimeOffset.UtcNow - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value)))
            {
                // For applications that want to allow the client to select the external authentication provider
                // that will be used to authenticate the user, the identity_provider parameter can be used for that.
                if (!string.IsNullOrEmpty(request.IdentityProvider))
                {
                    var issuer = request.IdentityProvider switch
                    {
                        "github" => "https://github.com/",

                        _ => null
                    };

                    if (string.IsNullOrEmpty(issuer))
                    {
                        context.Authentication.Challenge(
                            authenticationTypes: OpenIddictServerOwinDefaults.AuthenticationType,
                            properties: new AuthenticationProperties(new Dictionary <string, string>
                        {
                            [OpenIddictServerOwinConstants.Properties.Error]            = Errors.InvalidRequest,
                            [OpenIddictServerOwinConstants.Properties.ErrorDescription] =
                                "The specified identity provider is not valid."
                        }));

                        return(new EmptyResult());
                    }

                    var properties = new AuthenticationProperties(new Dictionary <string, string>
                    {
                        // Note: when only one client is registered in the client options,
                        // setting the issuer property is not required and can be omitted.
                        [OpenIddictClientOwinConstants.Properties.Issuer] = issuer
                    })
                    {
                        // Once the callback is handled, redirect the user agent to the ASP.NET Identity
                        // page responsible for showing the external login confirmation form if necessary.
                        RedirectUri = Url.Action("ExternalLoginCallback", "Account", new
                        {
                            ReturnUrl = Request.RawUrl
                        })
                    };

                    // Ask the OpenIddict client middleware to redirect the user agent to the identity provider.
                    context.Authentication.Challenge(properties, OpenIddictClientOwinDefaults.AuthenticationType);
                    return(new EmptyResult());
                }

                context.Authentication.Challenge(DefaultAuthenticationTypes.ApplicationCookie);
                return(new EmptyResult());
            }

            // Retrieve the profile of the logged in user.
            var user = await context.GetUserManager <ApplicationUserManager>().FindByIdAsync(result.Identity.GetUserId()) ??
                       throw new InvalidOperationException("The user details cannot be retrieved.");

            // Retrieve the application details from the database.
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ??
                              throw new InvalidOperationException("Details concerning the calling client application cannot be found.");

            // Retrieve the permanent authorizations associated with the user and the calling client application.
            var authorizations = await _authorizationManager.FindAsync(
                subject : user.Id,
                client : await _applicationManager.GetIdAsync(application),
                status : Statuses.Valid,
                type : AuthorizationTypes.Permanent,
                scopes : request.GetScopes()).ToListAsync();

            switch (await _applicationManager.GetConsentTypeAsync(application))
            {
            // If the consent is external (e.g when authorizations are granted by a sysadmin),
            // immediately return an error if no authorization can be found in the database.
            case ConsentTypes.External when !authorizations.Any():
                context.Authentication.Challenge(
                    authenticationTypes: OpenIddictServerOwinDefaults.AuthenticationType,
                    properties: new AuthenticationProperties(new Dictionary <string, string>
                {
                    [OpenIddictServerOwinConstants.Properties.Error]            = Errors.ConsentRequired,
                    [OpenIddictServerOwinConstants.Properties.ErrorDescription] =
                        "The logged in user is not allowed to access this client application."
                }));

                return(new EmptyResult());

            // If the consent is implicit or if an authorization was found,
            // return an authorization response without displaying the consent form.
            case ConsentTypes.Implicit:
            case ConsentTypes.External when authorizations.Any():
            case ConsentTypes.Explicit when authorizations.Any() && !request.HasPrompt(Prompts.Consent):
                // Create the claims-based identity that will be used by OpenIddict to generate tokens.
                var identity = new ClaimsIdentity(OpenIddictServerOwinDefaults.AuthenticationType)
                               .AddClaim(Claims.Subject, user.Id)
                               .AddClaim(Claims.Email, user.Email)
                               .AddClaim(Claims.Name, user.UserName)
                               .AddClaims(Claims.Role, (await context.Get <ApplicationUserManager>().GetRolesAsync(user.Id)).ToImmutableArray());

                // Note: in this sample, the granted scopes match the requested scope
                // but you may want to allow the user to uncheck specific scopes.
                // For that, simply restrict the list of scopes before calling SetScopes.
                identity.SetScopes(request.GetScopes());
                identity.SetResources(await _scopeManager.ListResourcesAsync(identity.GetScopes()).ToListAsync());

                // 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 : new ClaimsPrincipal(identity),
                        subject : user.Id,
                        client : await _applicationManager.GetIdAsync(application),
                        type : AuthorizationTypes.Permanent,
                        scopes : identity.GetScopes());
                }

                identity.SetAuthorizationId(await _authorizationManager.GetIdAsync(authorization));
                identity.SetDestinations(GetDestinations);

                context.Authentication.SignIn(new AuthenticationProperties(), identity);

                return(new EmptyResult());

            // At this point, no authorization was found in the database and an error must be returned
            // if the client application specified prompt=none in the authorization request.
            case ConsentTypes.Explicit   when request.HasPrompt(Prompts.None):
            case ConsentTypes.Systematic when request.HasPrompt(Prompts.None):
                context.Authentication.Challenge(
                    authenticationTypes: OpenIddictServerOwinDefaults.AuthenticationType,
                    properties: new AuthenticationProperties(new Dictionary <string, string>
                {
                    [OpenIddictServerOwinConstants.Properties.Error]            = Errors.ConsentRequired,
                    [OpenIddictServerOwinConstants.Properties.ErrorDescription] =
                        "Interactive user consent is required."
                }));

                return(new EmptyResult());

            // In every other case, render the consent form.
            default: return(View(new AuthorizeViewModel
                {
                    ApplicationName = await _applicationManager.GetDisplayNameAsync(application),
                    Scope = request.Scope,

                    // Flow the request parameters so they can be received by the Accept/Reject actions.
                    Parameters = string.Equals(Request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase) ?
                                 from name in Request.Form.AllKeys
                                 from value in Request.Form.GetValues(name)
                                 select new KeyValuePair <string, string>(name, value) :
                                 from name in Request.QueryString.AllKeys
                                 from value in Request.QueryString.GetValues(name)
                                 select new KeyValuePair <string, string>(name, value)
                }));
            }
        }
예제 #12
0
    public async Task SeedAsync(DataSeedContext context)
    {
        if (await _scopeManager.FindByNameAsync("AbpAPI") == null)
        {
            await _scopeManager.CreateAsync(new OpenIddictScopeDescriptor()
            {
                Name         = "AbpAPI",
                DisplayName  = "Abp API access",
                DisplayNames =
                {
                    [CultureInfo.GetCultureInfo("zh-Hans")] = "演示 API 访问",
                    [CultureInfo.GetCultureInfo("tr")]      = "API erişimi"
                },
                Resources =
                {
                    "AbpAPIResource"
                }
            });
        }

        if (await _applicationManager.FindByClientIdAsync("AbpApp") == null)
        {
            await _applicationManager.CreateAsync(new OpenIddictApplicationDescriptor
            {
                ClientId               = "AbpApp",
                ClientSecret           = "1q2w3e*",
                ConsentType            = OpenIddictConstants.ConsentTypes.Explicit,
                DisplayName            = "Abp Application",
                PostLogoutRedirectUris =
                {
                    new Uri("https://localhost:44302/signout-callback-oidc"),
                    new Uri("http://localhost:4200")
                },
                RedirectUris =
                {
                    new Uri("https://localhost:44302/signin-oidc"),
                    new Uri("http://localhost:4200")
                },
                Permissions =
                {
                    OpenIddictConstants.Permissions.Endpoints.Authorization,
                    OpenIddictConstants.Permissions.Endpoints.Token,
                    OpenIddictConstants.Permissions.Endpoints.Device,
                    OpenIddictConstants.Permissions.Endpoints.Introspection,
                    OpenIddictConstants.Permissions.Endpoints.Revocation,
                    OpenIddictConstants.Permissions.Endpoints.Logout,

                    OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode,
                    OpenIddictConstants.Permissions.GrantTypes.Implicit,
                    OpenIddictConstants.Permissions.GrantTypes.Password,
                    OpenIddictConstants.Permissions.GrantTypes.RefreshToken,
                    OpenIddictConstants.Permissions.GrantTypes.DeviceCode,
                    OpenIddictConstants.Permissions.GrantTypes.ClientCredentials,

                    OpenIddictConstants.Permissions.ResponseTypes.Code,
                    OpenIddictConstants.Permissions.ResponseTypes.CodeIdToken,
                    OpenIddictConstants.Permissions.ResponseTypes.CodeIdTokenToken,
                    OpenIddictConstants.Permissions.ResponseTypes.CodeToken,
                    OpenIddictConstants.Permissions.ResponseTypes.IdToken,
                    OpenIddictConstants.Permissions.ResponseTypes.IdTokenToken,
                    OpenIddictConstants.Permissions.ResponseTypes.None,
                    OpenIddictConstants.Permissions.ResponseTypes.Token,

                    OpenIddictConstants.Permissions.Scopes.Roles,
                    OpenIddictConstants.Permissions.Scopes.Profile,
                    OpenIddictConstants.Permissions.Scopes.Email,
                    OpenIddictConstants.Permissions.Scopes.Address,
                    OpenIddictConstants.Permissions.Scopes.Phone,
                    OpenIddictConstants.Permissions.Prefixes.Scope + "AbpAPI"
                }
            });
        }

        if (await _applicationManager.FindByClientIdAsync("AbpBlazorWASMApp") == null)
        {
            await _applicationManager.CreateAsync(new OpenIddictApplicationDescriptor
            {
                ClientId               = "AbpBlazorWASMApp",
                ConsentType            = OpenIddictConstants.ConsentTypes.Explicit,
                DisplayName            = "Abp Blazor WASM Application",
                PostLogoutRedirectUris =
                {
                    new Uri("https://localhost:44304/authentication/logout-callback")
                },
                RedirectUris =
                {
                    new Uri("https://localhost:44304/authentication/login-callback")
                },
                Permissions =
                {
                    OpenIddictConstants.Permissions.Endpoints.Authorization,
                    OpenIddictConstants.Permissions.Endpoints.Token,
                    OpenIddictConstants.Permissions.Endpoints.Device,
                    OpenIddictConstants.Permissions.Endpoints.Introspection,
                    OpenIddictConstants.Permissions.Endpoints.Revocation,
                    OpenIddictConstants.Permissions.Endpoints.Logout,

                    OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode,
                    OpenIddictConstants.Permissions.GrantTypes.Implicit,
                    OpenIddictConstants.Permissions.GrantTypes.Password,
                    OpenIddictConstants.Permissions.GrantTypes.RefreshToken,
                    OpenIddictConstants.Permissions.GrantTypes.DeviceCode,
                    OpenIddictConstants.Permissions.GrantTypes.ClientCredentials,

                    OpenIddictConstants.Permissions.ResponseTypes.Code,
                    OpenIddictConstants.Permissions.ResponseTypes.CodeIdToken,
                    OpenIddictConstants.Permissions.ResponseTypes.CodeIdTokenToken,
                    OpenIddictConstants.Permissions.ResponseTypes.CodeToken,
                    OpenIddictConstants.Permissions.ResponseTypes.IdToken,
                    OpenIddictConstants.Permissions.ResponseTypes.IdTokenToken,
                    OpenIddictConstants.Permissions.ResponseTypes.None,
                    OpenIddictConstants.Permissions.ResponseTypes.Token,

                    OpenIddictConstants.Permissions.Scopes.Roles,
                    OpenIddictConstants.Permissions.Scopes.Profile,
                    OpenIddictConstants.Permissions.Scopes.Email,
                    OpenIddictConstants.Permissions.Scopes.Address,
                    OpenIddictConstants.Permissions.Scopes.Phone,

                    OpenIddictConstants.Permissions.Prefixes.Scope + "AbpAPI"
                }
            });
        }
    }
예제 #13
0
        public async Task <ActionResult> Authorize()
        {
            var context = HttpContext.GetOwinContext();
            var request = context.GetOpenIddictServerRequest() ??
                          throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");

            // Retrieve the user principal stored in the authentication cookie.
            // If a max_age parameter was provided, ensure that the cookie is not too old.
            // If the user principal can't be extracted or the cookie is too old, redirect the user to the login page.
            var result = await context.Authentication.AuthenticateAsync(DefaultAuthenticationTypes.ApplicationCookie);

            if (result?.Identity == null || (request.MaxAge != null && result.Properties?.IssuedUtc != null &&
                                             DateTimeOffset.UtcNow - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value)))
            {
                context.Authentication.Challenge(DefaultAuthenticationTypes.ApplicationCookie);

                return(new EmptyResult());
            }

            // Retrieve the profile of the logged in user.
            var user = await context.GetUserManager <ApplicationUserManager>().FindByIdAsync(result.Identity.GetUserId()) ??
                       throw new InvalidOperationException("The user details cannot be retrieved.");

            // Retrieve the application details from the database.
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ??
                              throw new InvalidOperationException("Details concerning the calling client application cannot be found.");

            // Retrieve the permanent authorizations associated with the user and the calling client application.
            var authorizations = await _authorizationManager.FindAsync(
                subject : user.Id,
                client : await _applicationManager.GetIdAsync(application),
                status : Statuses.Valid,
                type : AuthorizationTypes.Permanent,
                scopes : request.GetScopes()).ToListAsync();

            switch (await _applicationManager.GetConsentTypeAsync(application))
            {
            // If the consent is external (e.g when authorizations are granted by a sysadmin),
            // immediately return an error if no authorization can be found in the database.
            case ConsentTypes.External when !authorizations.Any():
                context.Authentication.Challenge(
                    authenticationTypes: OpenIddictServerOwinDefaults.AuthenticationType,
                    properties: new AuthenticationProperties(new Dictionary <string, string>
                {
                    [OpenIddictServerOwinConstants.Properties.Error]            = Errors.ConsentRequired,
                    [OpenIddictServerOwinConstants.Properties.ErrorDescription] =
                        "The logged in user is not allowed to access this client application."
                }));

                return(new EmptyResult());

            // If the consent is implicit or if an authorization was found,
            // return an authorization response without displaying the consent form.
            case ConsentTypes.Implicit:
            case ConsentTypes.External when authorizations.Any():
            case ConsentTypes.Explicit when authorizations.Any() && !request.HasPrompt(Prompts.Consent):
                var identity = new ClaimsIdentity(OpenIddictServerOwinDefaults.AuthenticationType);

                identity.AddClaims((await context.Get <ApplicationSignInManager>().CreateUserIdentityAsync(user)).Claims);

                identity.AddClaim(new Claim(Claims.Subject, identity.FindFirstValue(ClaimTypes.NameIdentifier)));
                identity.AddClaim(new Claim(Claims.Name, identity.FindFirstValue(ClaimTypes.Name)));

                var principal = new ClaimsPrincipal(identity);

                // Note: in this sample, the granted scopes match the requested scope
                // but you may want to allow the user to uncheck specific scopes.
                // For that, simply restrict the list of scopes before calling SetScopes.
                principal.SetScopes(request.GetScopes());
                principal.SetResources(await _scopeManager.ListResourcesAsync(principal.GetScopes()).ToListAsync());

                // 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 : user.Id,
                        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));
                }

                context.Authentication.SignIn(new AuthenticationProperties(), (ClaimsIdentity)principal.Identity);

                return(new EmptyResult());

            // At this point, no authorization was found in the database and an error must be returned
            // if the client application specified prompt=none in the authorization request.
            case ConsentTypes.Explicit   when request.HasPrompt(Prompts.None):
            case ConsentTypes.Systematic when request.HasPrompt(Prompts.None):
                context.Authentication.Challenge(
                    authenticationTypes: OpenIddictServerOwinDefaults.AuthenticationType,
                    properties: new AuthenticationProperties(new Dictionary <string, string>
                {
                    [OpenIddictServerOwinConstants.Properties.Error]            = Errors.ConsentRequired,
                    [OpenIddictServerOwinConstants.Properties.ErrorDescription] =
                        "Interactive user consent is required."
                }));

                return(new EmptyResult());

            // In every other case, render the consent form.
            default: return(View(new AuthorizeViewModel
                {
                    ApplicationName = await _applicationManager.GetDisplayNameAsync(application),
                    Scope = request.Scope,

                    // Flow the request parameters so they can be received by the Accept/Reject actions.
                    Parameters = string.Equals(Request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase) ?
                                 from name in Request.Form.AllKeys
                                 from value in Request.Form.GetValues(name)
                                 select new KeyValuePair <string, string>(name, value) :
                                 from name in Request.QueryString.AllKeys
                                 from value in Request.QueryString.GetValues(name)
                                 select new KeyValuePair <string, string>(name, value)
                }));
            }
        }
예제 #14
0
        public async Task <IActionResult> Authorize()
        {
            var request = HttpContext.GetOpenIddictServerRequest() ??
                          throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");

            // Retrieve the user principal stored in the authentication cookie. (user logged in using CookieAuthenticationDefaults.AuthenticationScheme in Acccount Controller)
            var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            //var result2 = await HttpContext.AuthenticateAsync();
            //if (!User.Identity.IsAuthenticated)
            //{

            //}

            // If the user principal can't be extracted, redirect the user to the login page.
            if (!result.Succeeded)
            {
                return(Challenge(
                           authenticationSchemes: CookieAuthenticationDefaults.AuthenticationScheme,
                           properties: new AuthenticationProperties
                {
                    RedirectUri = Request.PathBase + Request.Path + QueryString.Create(
                        Request.HasFormContentType ? Request.Form.ToList() : Request.Query.ToList())
                }));
            }

            // To store extra profile information in the identity token, you can add claims in the Authorize method
            // in the AuthorizationController when using the authorization code flow
            // or add claims in the token endpoint if you are using the client credentials flow. Make sure to set the destination to IdentityToken.

            // Create a new claims principal
            var claims = new List <Claim>
            {
                // 'subject' claim which is required
                new Claim(OpenIddictConstants.Claims.Subject, result.Principal.Identity.Name),
                new Claim("quantran2 claim", "quantran2 value").SetDestinations(OpenIddictConstants.Destinations.AccessToken),
                new Claim(OpenIddictConstants.Claims.Email, "*****@*****.**").SetDestinations(OpenIddictConstants.Destinations.IdentityToken)
            };

            var claimsIdentity  = new ClaimsIdentity(claims, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

            // Set requested scopes (this is not done automatically)
            var sc = request.GetScopes();

            claimsPrincipal.SetScopes(sc);
            claimsPrincipal.SetResources(await _scopeManager.ListResourcesAsync(request.GetScopes()).ToListAsync());

            // ////////////// SET AUTHORIZATION ///////////////////
            // Retrieve the application details from the database.
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId) ??
                              throw new InvalidOperationException("Details concerning the calling client application cannot be found.");

            // Retrieve the permanent authorizations associated with the user and the calling client application.
            var authorizations = await _authorizationManager.FindAsync(
                subject : result.Principal.Identity.Name,
                client : await _applicationManager.GetIdAsync(application),
                status : Statuses.Valid,
                type : AuthorizationTypes.Permanent,
                scopes : request.GetScopes()).ToListAsync();

            // 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 is null)
            {
                authorization = await _authorizationManager.CreateAsync(
                    principal : claimsPrincipal,
                    subject : result.Principal.Identity.Name,
                    client : await _applicationManager.GetIdAsync(application),
                    type : AuthorizationTypes.Permanent,
                    scopes : claimsPrincipal.GetScopes());
            }

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

            // ////////////// SET AUTHORIZATION ///////////////////

            // Signing in with the OpenIddict authentiction scheme trigger OpenIddict to issue a code (which can be exchanged for an access token)
            return(SignIn(claimsPrincipal, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme));

            // Create a new authentication ticket holding the user identity.
            //var ticket = new AuthenticationTicket(claimsPrincipal,
            //    new AuthenticationProperties(),
            //    OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);

            //// Returning a SignInResult will ask OpenIddict to issue the appropriate access/identity tokens.
            //return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
        }