public async Task <IActionResult> Authorize(OpenIdConnectRequest request)
        {
            // Retrieve the application details from the database.
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId);

            if (application == null)
            {
                return(View("Error",
                            new ErrorViewModel
                {
                    Error = OpenIddictConstants.Errors.InvalidClient,
                    ErrorDescription =
                        "Details concerning the calling client application cannot be found in the database"
                }));
            }

            var userId = _userManager.GetUserId(User);

            if (!string.IsNullOrEmpty(
                    await OpenIdExtensions.IsUserAuthorized(_authorizationManager, request, userId, application.Id)))
            {
                return(await Authorize(request, "YES", false));
            }

            // Flow the request_id to allow OpenIddict to restore
            // the original authorization request from the cache.
            return(View(new AuthorizeViewModel
            {
                ApplicationName = await _applicationManager.GetDisplayNameAsync(application),
                RequestId = request.RequestId,
                Scope = request.GetScopes()
            }));
        }
        public async Task <IActionResult> Authorize(OpenIdConnectRequest request)
        {
            Debug.Assert(request.IsAuthorizationRequest(),
                         "The OpenIddict binder for ASP.NET Core MVC is not registered. " +
                         "Make sure services.AddOpenIddict().AddServer().UseMvc() is correctly called.");

            // Retrieve the application details from the database.
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId);

            if (application == null)
            {
                return(View("Error", new ErrorViewModel
                {
                    Error = OpenIddictConstants.Errors.InvalidClient,
                    ErrorDescription = "Details concerning the calling client application cannot be found in the database"
                }));
            }

            // Flow the request_id to allow OpenIddict to restore
            // the original authorization request from the cache.
            return(View(new AuthorizeViewModel
            {
                ApplicationName = await _applicationManager.GetDisplayNameAsync(application),
                RequestId = request.RequestId,
                Scope = request.Scope
            }));
        }
Exemple #3
0
        public async Task <IActionResult> Login(OpenIdConnectRequest request, Profile profile)
        {
            if (request.IsClientCredentialsGrantType())
            {
                var application = await _applicationManager.FindByClientIdAsync(request.ClientId, HttpContext.RequestAborted);

                if (application == null)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidClient,
                        ErrorDescription = "Id Клиента не найден в базе данных."
                    }));
                }

                if (!await _repository.GetProfileAsync(profile.Login, profile.Password))
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
                        ErrorDescription = "Login or PAssword не совпадают."
                    }));
                }
                var idprofile = await _repository.GetProfileIdAsync(profile.Login, profile.Password);

                var i = idprofile.ToString();
                request.Username = i.ToString();
                var ticket = CreateTicket(request, application);

                return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
            }

            else if (request.IsRefreshTokenGrantType())
            {
                var info = await HttpContext.AuthenticateAsync(OpenIdConnectServerDefaults.AuthenticationScheme);


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

                if (application == null)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidClient,
                        ErrorDescription = "Id Клиента не найден в базе данных."
                    }));
                }
                var ticket = CreateTicket(request, application);

                return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
            }

            return(BadRequest(new OpenIdConnectResponse
            {
                Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
                ErrorDescription = "The specified grant type is not supported."
            }));
        }
        public async Task <IActionResult> Authorize(OpenIdConnectRequest request, CancellationToken cancellationToken)
        {
            Debug.Assert(request.IsAuthorizationRequest(),
                         "The OpenIddict binder for ASP.NET Core MVC is not registered. " +
                         "Make sure services.AddOpenIddict().AddMvcBinders() is correctly called.");

            // Retrieve the application details from the database.
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId, HttpContext.RequestAborted);

            if (application == null)
            {
                return(View("Error", new ErrorViewModel
                {
                    Error = OpenIdConnectConstants.Errors.InvalidClient,
                    ErrorDescription = "Details concerning the calling client application cannot be found in the database"
                }));
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(View("Error", new ErrorViewModel
                {
                    Error = OpenIdConnectConstants.Errors.ServerError,
                    ErrorDescription = "An internal error has occurred"
                }));
            }

            var authorization = await _authorizationManager.FindAsync(user.Id, application.Id, cancellationToken);

            if (authorization != null)
            {
                // if we didn't ask for any scopes that aren't already authorized
                if (false == request.GetScopes().Except(authorization.Scopes).Any())
                {
                    var ticket = await CreateTicketAsync(request, user);

                    return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
                }
            }

            // Flow the request_id to allow OpenIddict to restore
            // the original authorization request from the cache.
            return(View(new AuthorizeViewModel
            {
                ApplicationName = application.DisplayName,
                RequestId = request.RequestId,
                Scope = request.Scope,
                ClientId = request.ClientId,
                ResponseType = request.ResponseType,
                ResponseMode = request.ResponseMode,
                RedirectUri = request.RedirectUri,
                State = request.State,
                Nonce = request.Nonce
            }));
        }
 public async Task <IActionResult> GetApplications([FromRoute] string clientId)
 {
     return((await ShouldNotNullOrEmpty(clientId).ToEither().MapAsync(async req =>
                                                                      ShouldNotNull(await _oidApplicationManager.FindByClientIdAsync(req))))
            .Match <IActionResult>(res => res
                                   .Match <IActionResult>(data => Ok(_mapper.Map <OpenIddictApplicationViewModel>(data)),
                                                          _ => NotFound()),
                                   errors => BadRequest(errors.Join())));
 }
        public async Task <IActionResult> Authorize()
        {
            var request     = HttpContext.GetOpenIdConnectRequest();
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId);

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

            return(await Accept());
        }
        public async Task <IActionResult> Authorize(OpenIdConnectRequest request)
        {
            Debug.Assert(request.IsAuthorizationRequest(),
                         "The OpenIddict binder for ASP.NET Core MVC is not registered. " +
                         "Make sure services.AddOpenIddict().AddMvcBinders() is correctly called.");

            // Retrieve the application details from the database.
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId, HttpContext.RequestAborted);

            if (application == null)
            {
                return(View("Error", new ErrorViewModel
                {
                    Error = OpenIdConnectConstants.Errors.InvalidClient,
                    ErrorDescription = "Details concerning the calling client application cannot be found in the database"
                }));
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(View("Error", new ErrorViewModel
                {
                    Error = OpenIdConnectConstants.Errors.ServerError,
                    ErrorDescription = "An internal error has occurred"
                }));
            }
            if (user.IsDeleted)
            {
                return(View("Error", new ErrorViewModel
                {
                    Error = OpenIdConnectConstants.Errors.ServerError,
                    ErrorDescription = "An internal error has occurred"
                }));
            }
            // Create a new authentication ticket.
            var ticket = await CreateTicketAsync(request, user);

            // Returning a SignInResult will ask OpenIddict to issue the appropriate access/identity tokens.
            return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
            // Flow the request_id to allow OpenIddict to restore
            // the original authorization request from the cache.
            //return View(new AuthorizeViewModel
            //{
            //    ApplicationName = application.DisplayName,
            //    RequestId = request.RequestId,
            //    Scope = request.Scope
            //});
        }
Exemple #8
0
        private async Task InitializeIdServAsync()
        {
            // Create a new service scope to ensure the database context is correctly disposed when this methods returns.
            if (await _iddictApplicationManager.FindByClientIdAsync("mvc") == null)
            {
                var descriptor = new OpenIddictApplicationDescriptor
                {
                    ClientId               = "mvc",
                    ClientSecret           = "901564A5-E7FE-42CB-B10D-61EF6A8F3654",
                    DisplayName            = "MVC client application",
                    PostLogoutRedirectUris = { new Uri("http://localhost:53507/signout-callback-oidc") },
                    RedirectUris           = { new Uri("http://localhost:53507/signin-oidc") },
                    Permissions            =
                    {
                        OpenIddictConstants.Permissions.Endpoints.Authorization,
                        OpenIddictConstants.Permissions.Endpoints.Logout,
                        OpenIddictConstants.Permissions.Endpoints.Token
                    }
                };

                await _iddictApplicationManager.CreateAsync(descriptor);
            }

            // To test this sample with Postman, use the following settings:
            //
            // * Authorization URL: http://localhost:54540/connect/authorize
            // * Access token URL: http://localhost:54540/connect/token
            // * Client ID: postman
            // * Client secret: [blank] (not used with public clients)
            // * Scope: openid email profile roles
            // * Grant type: authorization code
            // * Request access token locally: yes
            if (await _iddictApplicationManager.FindByClientIdAsync("postman") == null)
            {
                var descriptor = new OpenIddictApplicationDescriptor
                {
                    ClientId     = "postman",
                    DisplayName  = "Postman",
                    RedirectUris = { new Uri("https://www.getpostman.com/oauth2/callback") },
                    Permissions  =
                    {
                        OpenIddictConstants.Permissions.Endpoints.Authorization,
                        OpenIddictConstants.Permissions.Endpoints.Token
                    }
                };

                await _iddictApplicationManager.CreateAsync(descriptor);
            }
        }
Exemple #9
0
        public async Task <IActionResult> Authorize()
        {
            var request = HttpContext.GetOpenIddictServerRequest() ??
                          throw new InvalidOperationException("The OpenID Connect request 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.");

            return(View(new AuthorizeViewModel
            {
                ApplicationName = await _applicationManager.GetDisplayNameAsync(application),
                Scope = request.Scope
            }));
        }
        public async Task <IActionResult> Authorize(OpenIdConnectRequest request)
        {
            Debug.Assert(request.IsAuthorizationRequest(),
                         "The OpenIddict binder for ASP.NET Core MVC is not registered. " +
                         "Make sure services.AddOpenIddict().AddMvcBinders() is correctly called.");

            if (!User.Identity.IsAuthenticated)
            {
                // If the client application request promptless authentication,
                // return an error indicating that the user is not logged in.
                if (request.HasPrompt(OpenIdConnectConstants.Prompts.None))
                {
                    var properties = new AuthenticationProperties(new Dictionary <string, string>
                    {
                        [OpenIdConnectConstants.Properties.Error]            = OpenIdConnectConstants.Errors.LoginRequired,
                        [OpenIdConnectConstants.Properties.ErrorDescription] = "The user is not logged in."
                    });

                    // Ask OpenIddict to return a login_required error to the client application.
                    return(Forbid(properties, OpenIdConnectServerDefaults.AuthenticationScheme));
                }

                return(Challenge());
            }

            // Retrieve the application details from the database.
            var application =
                await applicationManager.FindByClientIdAsync(request.ClientId, HttpContext.RequestAborted);

            if (application == null)
            {
                return(View("Error", new ErrorViewModel
                {
                    Error = OpenIdConnectConstants.Errors.InvalidClient,
                    ErrorDescription =
                        "Details concerning the calling client application cannot be found in the database."
                }));
            }

            // Flow the request_id to allow OpenIddict to restore
            // the original authorization request from the cache.
            return(View(new AuthorizeViewModel
            {
                ApplicationName = application.DisplayName,
                RequestId = request.RequestId,
                Scope = request.Scope
            }));
        }
Exemple #11
0
        public async Task <IActionResult> Authorize([ModelBinder(typeof(OpenIddictMvcBinder))] OpenIdConnectRequest request)
        {
            var application = await applicationManager.FindByClientIdAsync(request.ClientId, HttpContext.RequestAborted);

            if (application == null)
            {
                return(View("Error", new ErrorViewModel
                {
                    Error = OpenIdConnectConstants.Errors.InvalidClient,
                    ErrorDescription = "Детали, соответствующие вызываемому клиентскому приложению не найдены в базе данных"
                }));
            }

            var user = await userManager.GetUserAsync(User);

            if (user != null)
            {
                var authorize = await authorizationManager.FindBySubjectAsync(user.Id);

                if (authorize.Length != 0)
                {
                    var ticket = await CreateTicketAsync(request, user);

                    return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
                }
            }

            return(View(new AuthorizeViewModel
            {
                ApplicationName = application.DisplayName,
                RequestId = request.RequestId
            }));
        }
Exemple #12
0
        public async Task <IActionResult> Authorize(OpenIdConnectRequest request)
        {
            Debug.Assert(request.IsAuthorizationRequest(),
                         "The OpenIddict binder for ASP.NET Core MVC is not registered. " +
                         "Make sure services.AddOpenIddict().AddMvcBinders() is correctly called.");

            // Retrieve the application details from the database.
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId, HttpContext.RequestAborted);

            if (application == null)
            {
                return(new JsonResult(new
                {
                    code = OpenIdConnectConstants.Errors.InvalidClient,
                    message = "Details concerning the calling client application cannot be found in the database"
                }));
            }
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(new JsonResult(new
                {
                    code = OpenIdConnectConstants.Errors.ServerError,
                    message = "An internal error has occurred"
                }));
            }

            // Create a new authentication ticket.
            var ticket = await CreateTicketAsync(request, user);

            // Returning a SignInResult will ask OpenIddict to issue the appropriate access/identity tokens.
            return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
        }
        private async Task AddOpenIdConnectOptions(IConfiguration configuration)
        {
            if (await _openIddictApplicationManager.FindByClientIdAsync("cleanarchitecture") == null)
            {
                var host = configuration["HostUrl"].ToString();

                var descriptor = new OpenIddictApplicationDescriptor
                {
                    ClientId               = "cleanarchitecture",
                    DisplayName            = "CleanArchitecture",
                    PostLogoutRedirectUris = { new Uri($"{host}signout-oidc") },
                    RedirectUris           = { new Uri(host) },
                    Permissions            =
                    {
                        OpenIddictConstants.Permissions.Endpoints.Authorization,
                        OpenIddictConstants.Permissions.Endpoints.Token,
                        OpenIddictConstants.Permissions.GrantTypes.Implicit,
                        OpenIddictConstants.Permissions.GrantTypes.Password,
                        OpenIddictConstants.Permissions.GrantTypes.RefreshToken
                    }
                };

                await _openIddictApplicationManager.CreateAsync(descriptor);
            }
        }
    public async Task <string> CreateAsync(ApplicationParam model)
    {
        if (model == null)
        {
            throw new ArgumentNullException(nameof(model));
        }

        var entity = await _manager.FindByClientIdAsync(model.ClientId);

        if (entity == null)
        {
            // create new entity
            var newEntity = new OpenIddictEntityFrameworkCoreApplication
            {
                ClientId    = model.ClientId,
                DisplayName = model.DisplayName,
                Type        = model.Type
            };

            HandleCustomProperties(model, newEntity);

            await _manager.CreateAsync(newEntity, model.ClientSecret);

            return(newEntity.Id);
        }

        // update existing entity
        model.Id = entity.Id;
        await UpdateAsync(model);

        return(entity.Id);
    }
Exemple #15
0
        public async Task <IActionResult> Authorize()
        {
            var request = HttpContext.GetOpenIddictServerRequest();

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

            // Retrieve the application details from the database.
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId);

            if (application == null)
            {
                return(View("Error", new ErrorViewModel
                {
                    Error = Errors.InvalidClient,
                    ErrorDescription = "Details concerning the calling client application cannot be found in the database"
                }));
            }

            // Flow the request_id to allow OpenIddict to restore
            // the original authorization request from the cache.
            return(View(new AuthorizeViewModel
            {
                ApplicationName = await _applicationManager.GetDisplayNameAsync(application),
                Parameters = request.GetFlattenedParameters(),
                Scope = request.Scope
            }));
        }
        public async Task <IActionResult> Authorize()
        {
            // Extract the authorization request from the ASP.NET environment.
            var request = HttpContext.GetOpenIdConnectRequest();

            // Retrieve the application details from the database.
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId);

            if (application == null)
            {
                return(View("Error", new ErrorViewModel
                {
                    Error = OpenIdConnectConstants.Errors.InvalidClient,
                    ErrorDescription = "Details concerning the calling client application cannot be found in the database"
                }));
            }

            // Flow the request_id to allow OpenIddict to restore
            // the original authorization request from the cache.
            return(View(new AuthorizeViewModel
            {
                ApplicationName = application.DisplayName,
                RequestId = request.RequestId,
                Scope = request.Scope
            }));
        }
        public async Task <IActionResult> Exchange([ModelBinder(BinderType = typeof(OpenIddictMvcBinder))] OpenIdConnectRequest request)
        {
            if (request.IsClientCredentialsGrantType())
            {
                // Note: the client credentials are automatically validated by OpenIddict:
                // if client_id or client_secret are invalid, this action won't be invoked.

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

                if (application == null)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidClient,
                        ErrorDescription = "The client application was not found in the database."
                    }));
                }

                // Create a new authentication ticket.
                var ticket = CreateTicket(application);

                return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
            }

            return(BadRequest(new OpenIdConnectResponse
            {
                Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
                ErrorDescription = "The specified grant type is not supported."
            }));
        }
Exemple #18
0
        public async Task <IActionResult> Exchange(OpenIdConnectRequest request)
        {
            Debug.Assert(request.IsTokenRequest(),
                         "The OpenIddict binder for ASP.NET Core MVC is not registered. " +
                         "Make sure services.AddOpenIddict().AddMvcBinders() is correctly called.");

            if (request.IsClientCredentialsGrantType())
            {
                // Note: the client credentials are automatically validated by OpenIddict:
                // if client_id or client_secret are invalid, this action won't be invoked.

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

                if (application == null)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidClient,
                        ErrorDescription = "The client application was not found in the database."
                    }));
                }

                // Create a new authentication ticket.
                var ticket = CreateTicket(request, application);

                return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
            }

            return(BadRequest(new OpenIdConnectResponse
            {
                Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
                ErrorDescription = "The specified grant type is not supported."
            }));
        }
Exemple #19
0
        public async Task <IActionResult> Authorize(OpenIdConnectRequest req)
        {
            //Debug.Assert(request.IsAuthorizationRequest(),
            //    "The OpenIddict binder for ASP.NET Core MVC is not registered." +
            //    "Make sure services.AddOpenIddict().AddServer().UseMvc() is correctly called.");

            var application = await applicationManager.FindByClientIdAsync(req.ClientId);

            if (application == null)
            {
                var msg = "Details concerning the calling client application cannot be found in the database";
                return(BadRequest(error: new ErrowVm
                {
                    Error = Errors.InvalidClient,
                    ErrorDescription = msg
                }.ToResponse(false, msg)));
            }

            return(Ok(new AuthorizeVm
            {
                ApplicationName = await applicationManager.GetDisplayNameAsync(application),
                RequestId = req.RequestId,
                Scope = req.Scope
            }.ToResponse()));
        }
Exemple #20
0
        public static async Task CreateClientApps(OpenIddictApplicationManager <OpenIddictApplication> manager,
                                                  CancellationToken cancellationToken)
        {
            if (await manager.FindByClientIdAsync(ClientAppHelper.CLIENT_WEB_ID,
                                                  cancellationToken) == null)
            {
                var descriptor = new OpenIddictApplicationDescriptor
                {
                    ClientId               = ClientAppHelper.CLIENT_WEB_ID,
                    ClientSecret           = ClientAppHelper.CLIENT_WEB_SECRET,
                    DisplayName            = "Imanage Web App",
                    PostLogoutRedirectUris = { new Uri("https://imanage.azurewebsites.net/connect/token") },
                    RedirectUris           = { new Uri("https://imanage.azurewebsites.net/connect/token") },
                    Type        = OpenIddictConstants.ClientTypes.Hybrid,
                    Permissions =
                    {
                        OpenIddictConstants.Permissions.Endpoints.Token,
                        OpenIddictConstants.Permissions.GrantTypes.Password,
                        OpenIddictConstants.Permissions.GrantTypes.RefreshToken,
                        OpenIddictConstants.Permissions.Scopes.Email,
                        OpenIddictConstants.Permissions.Scopes.Profile,
                        OpenIddictConstants.Permissions.Scopes.Roles
                    }
                };

                await manager.CreateAsync(descriptor, cancellationToken);
            }
        }
        public async Task <IActionResult> Authorize()
        {
            // Extract the authorization request from the ASP.NET environment.
            var request = HttpContext.GetOpenIdConnectRequest();

            // Retrieve the application details from the database.
            var application = await _applicationManager.FindByClientIdAsync(request.ClientId);

            if (application == null)
            {
                return(View("Error", new ErrorViewModel {
                    Error = OpenIdConnectConstants.Errors.InvalidClient,
                    ErrorDescription = "Details concerning the calling client application cannot be found in the database"
                }));
            }

            // Retrieve the profile of the logged in user.
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(View("Error", new ErrorViewModel {
                    Error = OpenIdConnectConstants.Errors.ServerError,
                    ErrorDescription = "An internal error has occurred"
                }));
            }

            // Create a new authentication ticket.
            var ticket = await CreateTicketAsync(request, user);

            // Returning a SignInResult will ask OpenIddict to issue the appropriate access/identity tokens.
            return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
        }
Exemple #22
0
        public async Task <ActionResult <OpenIddictApplicationDescriptor> > SaveAsync(OpenIddictApplicationDescriptor descriptor)
        {
            descriptor.Permissions.Clear();
            descriptor.Permissions.AddRange(_defaultPermissions);

            var app = await _manager.FindByClientIdAsync(descriptor.ClientId);

            if (app == null)
            {// create
                app = await _manager.CreateAsync(descriptor);

                await _manager.PopulateAsync(descriptor, app);
            }
            else
            {// update
                //prevent changing client secret
                descriptor.ClientSecret = app.ClientSecret;

                await _manager.PopulateAsync(app, descriptor);

                await _manager.UpdateAsync(app);
            }

            descriptor.ClientSecret = app.ClientSecret;
            return(descriptor);
        }
Exemple #23
0
        public override async ValueTask HandleAsync(
            OpenIddictServerEvents.HandleTokenRequestContext notification)
        {
            var request = notification.Request;
            var context = notification;

            if (!request.IsClientCredentialsGrantType())
            {
                return;
            }

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

            if (application == null)
            {
                context.Reject(
                    error: OpenIddictConstants.Errors.InvalidClient,
                    description: "The client application was not found in the database.");
                return;
            }

            var user = await _userManager.FindByIdAsync(application.ApplicationUserId);

            context.Principal = await CreateClaimsPrincipalAsync(request, user);
        }
        public static async Task <ClaimsPrincipal> CreateClaimsPrincipalAsync(OpenIddictApplicationManager <BTCPayOpenIdClient> applicationManager,
                                                                              OpenIddictAuthorizationManager <BTCPayOpenIdAuthorization> authorizationManager,
                                                                              IdentityOptions identityOptions,
                                                                              SignInManager <ApplicationUser> signInManager,
                                                                              OpenIddictRequest request,
                                                                              ApplicationUser user)
        {
            var principal = await signInManager.CreateUserPrincipalAsync(user);

            if (!request.IsAuthorizationCodeGrantType() && !request.IsRefreshTokenGrantType())
            {
                principal.SetScopes(request.GetScopes().Restrict(principal));
            }
            else if (request.IsAuthorizationCodeGrantType() &&
                     string.IsNullOrEmpty(principal.GetInternalAuthorizationId()))
            {
                var app = await applicationManager.FindByClientIdAsync(request.ClientId);

                var authorizationId = await IsUserAuthorized(authorizationManager, request, user.Id, app.Id);

                if (!string.IsNullOrEmpty(authorizationId))
                {
                    principal.SetInternalAuthorizationId(authorizationId);
                }
            }

            principal.SetDestinations(identityOptions);
            return(principal);
        }
Exemple #25
0
        private static async Task AddClientApplications(ApplicationDbContext context, OpenIddictApplicationManager <OpenIddictApplication> manager)
        {
            const string clientId = "socialarts.club";

            var app = await manager.FindByClientIdAsync(clientId);

            if (app != null)
            {
                await manager.DeleteAsync(app);
            }

            var descriptor = new OpenIddictApplicationDescriptor
            {
                ClientId    = clientId,
                DisplayName = clientId,
                // TODO: Read this from configuration.
                RedirectUris =
                {
                    new Uri("https://localhost:5001/MyProgressJournal"),
                    new Uri("https://socialarts.club/MyProgressJournal")
                },
                Permissions =
                {
                    OpenIddictConstants.Permissions.Endpoints.Authorization,
                    OpenIddictConstants.Permissions.GrantTypes.Implicit,
                    OpenIddictConstants.Permissions.Scopes.OpenId,
                }
            };

            await manager.CreateAsync(descriptor);
        }
        public async Task <IActionResult> Exchange([ModelBinder(typeof(OpenIddictMvcBinder))] OpenIdConnectRequest request)
        {
            if (!request.IsClientCredentialsGrantType())
            {
                return(BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
                    ErrorDescription = "The specified grant type is not supported."
                }));
            }

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

            if (application == null)
            {
                return(BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidClient,
                    ErrorDescription = "The client application was not found in the database."
                }));
            }

            var ticket = CreateTicket(application);

            return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
        }
Exemple #27
0
        public async Task <IActionResult> Exchange()
        {
            var request = HttpContext.GetOpenIddictServerRequest();

            if (request.IsAuthorizationCodeGrantType())
            {
                // Note: the client credentials are automatically validated by OpenIddict:
                // if client_id or client_secret are invalid, this action won't be invoked.

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

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

                // Create a new ClaimsIdentity containing the claims that
                // will be used to create an id_token, a token or a code.
                var identity = new ClaimsIdentity(
                    TokenValidationParameters.DefaultAuthenticationType,
                    Claims.Name, Claims.Role);

                // Use the client_id as the subject identifier.
                identity.AddClaim(Claims.Subject, await _applicationManager.GetClientIdAsync(application),
                                  Destinations.AccessToken, Destinations.IdentityToken);

                identity.AddClaim(Claims.Name, await _applicationManager.GetDisplayNameAsync(application),
                                  Destinations.AccessToken, Destinations.IdentityToken);

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

            throw new NotImplementedException("The specified grant type is not implemented.");
        }
        public async Task <IActionResult> Authorize()
        {
            var request = HttpContext.GetOpenIdConnectRequest();

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

            if (application == null)
            {
                return(BadRequest(OpenIdConnectConstants.Errors.InvalidClient));
            }

            // Retrieve the profile of the logged in user.
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(BadRequest(OpenIdConnectConstants.Errors.ServerError));
            }

            if (!user.EmailConfirmed)
            {
                return(BadRequest("unconfirmed_email"));
            }


            var ticket = await CreateTicketAsync(request, user);

            // Returning a SignInResult will ask OpenIddict to issue the appropriate access/identity tokens.
            return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
        }
        private async Task AddOpenIdConnectApplication(IConfiguration configuration)
        {
            if (await _openIddictApplicationManager.FindByClientIdAsync("botw") == null)
            {
                var host = configuration["HostUrl"].ToString();

                var descriptor = new OpenIddictApplicationDescriptor
                {
                    ClientId               = "botw",
                    DisplayName            = "Best of the Worst",
                    PostLogoutRedirectUris = { new Uri($"{host}signout-oidc") },
                    RedirectUris           = { new Uri(host) },
                    Permissions            =
                    {
                        OpenIddictConstants.Permissions.Endpoints.Authorization,
                        OpenIddictConstants.Permissions.Endpoints.Token,
                        OpenIddictConstants.Permissions.GrantTypes.Implicit,
                        OpenIddictConstants.Permissions.GrantTypes.Password,
                        OpenIddictConstants.Permissions.GrantTypes.RefreshToken,
                        OpenIddictConstants.Permissions.Scopes.Email,
                        OpenIddictConstants.Permissions.Scopes.Profile,
                        OpenIddictConstants.Permissions.Scopes.Roles,
                    }
                };

                await _openIddictApplicationManager.CreateAsync(descriptor);
            }
        }
Exemple #30
0
        public override async Task <OpenIddictServerEventState> HandleAsync(
            OpenIddictServerEvents.HandleTokenRequest notification)
        {
            var request = notification.Context.Request;

            if (!request.IsClientCredentialsGrantType())
            {
                // Allow other handlers to process the event.
                return(OpenIddictServerEventState.Unhandled);
            }

            var application = await _applicationManager.FindByClientIdAsync(request.ClientId,
                                                                            notification.Context.HttpContext.RequestAborted);

            if (application == null)
            {
                notification.Context.Reject(
                    error: OpenIddictConstants.Errors.InvalidClient,
                    description: "The client application was not found in the database.");
                // Don't allow other handlers to process the event.
                return(OpenIddictServerEventState.Handled);
            }

            var user = await _userManager.FindByIdAsync(application.ApplicationUserId);

            notification.Context.Validate(await CreateTicketAsync(request, user));
            // Don't allow other handlers to process the event.
            return(OpenIddictServerEventState.Handled);
        }