예제 #1
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);
            }
        }
예제 #2
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);
        }
예제 #3
0
        public async Task <Audience> SetupAudience(string appName, string displayName)
        {
            //todo: implement name check
            string   clientId      = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 15).ToUpper();
            var      AudiencesRepo = _dbContext.Audiences;
            string   secret        = Guid.NewGuid().ToString().ToUpper();
            string   base64Secret  = Convert.ToBase64String(Encoding.UTF8.GetBytes(secret));
            Audience Audience      = new Audience();

            Audience.AppName      = appName;
            Audience.ClientId     = clientId;
            Audience.ClientSecret = secret;
            Audience.CreatedOn    = DateTime.Now;
            await AudiencesRepo.AddAsync(Audience);

            var descriptor = new OpenIddictApplicationDescriptor
            {
                ClientId     = clientId,
                ClientSecret = base64Secret,
                DisplayName  = displayName,
                Permissions  =
                {
                    OpenIddictConstants.Permissions.Endpoints.Token,
                    OpenIddictConstants.Permissions.GrantTypes.ClientCredentials,
                    OpenIddictConstants.Permissions.GrantTypes.Password,
                    OpenIddictConstants.Permissions.GrantTypes.RefreshToken
                }
            };

            await _openIddictConnectStore.CreateAsync(descriptor);

            await _dbContext.SaveChangesAsync();

            return(Audience);
        }
예제 #4
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 <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);
    }
예제 #6
0
        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);
            }
        }
        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);
            }
        }
예제 #8
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);
        }
예제 #9
0
        public void Configure(IApplicationBuilder app, UserServiceContext userServiceContext, OpenIddictApplicationManager <OpenIddictApplication> applicationManager, UserManager <ApplicationUser> userManager)
        {
            app.UseUserService();
            app.UseMvc();

            // Create database
            userServiceContext.Database.EnsureCreated();

            // OpenId application
            applicationManager.CreateAsync(new OpenIddictApplication()
            {
                ClientId          = "example-client",
                DisplayName       = "Example Client",
                LogoutRedirectUri = "http://example.com/logout.html",
                RedirectUri       = "http://example.com/o2c.html",
                Type = OpenIddictConstants.ClientTypes.Public
            }, new CancellationToken()).GetAwaiter().GetResult();

            // User
            userManager.CreateAsync(new ApplicationUser()
            {
                UserName = "******",
                Email    = "*****@*****.**",
            }, "!Test1").GetAwaiter().GetResult();
        }
예제 #10
0
 private async Task CreateOpenIdClients()
 {
     await applicationManager.CreateAsync(new OpenIddictApplication()
     {
         ClientId          = "example-client",
         DisplayName       = "Example Client",
         RedirectUri       = "http://localhost:5002/o2c.html",
         LogoutRedirectUri = "http://localhost:5002/o2c-logout.html",
         Type = OpenIddictConstants.ClientTypes.Public
     }, new CancellationToken());
 }
예제 #11
0
 private async Task CreateApplication()
 {
     await _applicationManager.CreateAsync(new OpenIddictApplication
     {
         Id                = _configuration["Authentication:OpenIddict:ApplicationId"],
         DisplayName       = _configuration["Authentication:OpenIddict:DisplayName"],
         RedirectUri       = _configuration["Authentication:OpenIddict:RedirectUri"],
         LogoutRedirectUri = _configuration["Authentication:OpenIddict:LogoutRedirectUri"],
         ClientId          = _configuration["Authentication:OpenIddict:ClientId"],
         Type              = OpenIddictConstants.ClientTypes.Public
     }, CancellationToken.None);
 }
 public async Task <IActionResult> PostApplication([FromBody] OpenIddictApplicationDescriptor descriptor)
 {
     return(await(await _oidApplicationManager.FindByClientIdAsync(descriptor.ClientId) == null
             ? Success <Error, OpenIddictApplicationDescriptor>(descriptor)
             : Fail <Error, OpenIddictApplicationDescriptor>($"Application {descriptor.ClientId} does exist"))
            .MatchAsync(
                async req =>
     {
         return Success <Error, OpenIddictEntityFrameworkCoreApplication>(
             await _oidApplicationManager.CreateAsync(req));
     }, errors => Fail <Error, OpenIddictEntityFrameworkCoreApplication>(errors.Join()))
            .ToActionResultAsync());
 }
예제 #13
0
        public async Task ExecuteAsync(RecipeExecutionContext context)
        {
            if (!string.Equals(context.Name, "OpenIdApplication", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var model       = context.Step.ToObject <OpenIdApplicationStepModel>();
            var application = new OpenIdApplication();

            if (model.Id != 0)
            {
                application = await _applicationManager.FindByIdAsync(model.Id.ToString(), CancellationToken.None);
            }
            application.ClientId    = model.ClientId;
            application.DisplayName = model.DisplayName;
            application.AllowAuthorizationCodeFlow = model.AllowAuthorizationCodeFlow;
            application.AllowClientCredentialsFlow = model.AllowClientCredentialsFlow;
            application.AllowHybridFlow            = model.AllowHybridFlow;
            application.AllowImplicitFlow          = model.AllowImplicitFlow;
            application.AllowPasswordFlow          = model.AllowPasswordFlow;
            application.AllowRefreshTokenFlow      = model.AllowRefreshTokenFlow;
            application.LogoutRedirectUri          = model.LogoutRedirectUri;
            application.RedirectUri = model.RedirectUri;
            application.SkipConsent = model.SkipConsent;
            application.RoleNames   = model.RoleNames;
            application.Type        = model.Type;

            if (model.Type == ClientType.Confidential)
            {
                await _applicationManager.CreateAsync(application, model.ClientSecret, CancellationToken.None);
            }

            else
            {
                await _applicationManager.CreateAsync(application, CancellationToken.None);
            }
        }
예제 #14
0
        public async Task CreateAsync(ApplicationClient applicationClient, CancellationToken cancellationToken)
        {
            if (applicationClient == null)
            {
                throw new ArgumentNullException(nameof(applicationClient));
            }

            var entity = await _applicationManager.FindByIdAsync(applicationClient.Id.ToString(), cancellationToken);

            if (entity == null)
            {
                await _applicationManager.CreateAsync(applicationClient, applicationClient.ClientSecret,
                                                      cancellationToken);
            }
        }
예제 #15
0
        private async Task CreateApplication()
        {
            await OpenIddictManager.CreateAsync(new OpenIddictApplication
            {
                Id                = Configuration["Authentication:OpenIddict:ApplicationId"],
                DisplayName       = Configuration["Authentication:OpenIddict:DisplayName"],
                RedirectUri       = Configuration["Authentication:OpenIddict:Authority"] + Configuration["Authentication:OpenIddict:TokenEndPoint"],
                LogoutRedirectUri = Configuration["Authentication:OpenIddict:Authority"],
                ClientId          = Configuration["Authentication:OpenIddict:ClientId"],
                // ClientSecret = Crypto.HashPassword(Configuration["Authentication:OpenIddict:ClientSecret"]),
                Type = OpenIddictConstants.ClientTypes.Public
            }, new CancellationToken());

            //This is the new way of adding a client secret, although it won't work if the application is marked as public.
            //}, Configuration["Authentication:OpenIddict:ClientSecret"], new CancellationToken());
        }
예제 #16
0
        public async Task <IActionResult> Register([FromBody] UserRegistration user)
        {
            //Check OTP
            await _manager.CreateAsync(new OpenIddictApplicationDescriptor
            {
                ClientId     = user.ClientId,
                ClientSecret = user.Secret,
                DisplayName  = user.Name,
                Permissions  =
                {
                    OpenIddictConstants.Permissions.Endpoints.Token,
                    OpenIddictConstants.Permissions.GrantTypes.ClientCredentials
                }
            });

            return(Created(Request.Host.Value, user.ClientId));
        }
예제 #17
0
        public async Task <ActionResult <string> > Add()
        {
            var model = new ApplicationModel();

            do
            {
                model.ClientId = Guid.NewGuid().ToString("N").Substring(0, 10);
            } while (await _applicationManager.FindByClientIdAsync(model.ClientId) != null);

            var descriptor = new OpenIddictApplicationDescriptor
            {
                ClientId     = model.ClientId,
                ClientSecret = model.ClientSecret,
                DisplayName  = $"app-{model.ClientId}",
                Permissions  =
                {
                    OpenIddictConstants.Permissions.Endpoints.Authorization,
                    OpenIddictConstants.Permissions.Endpoints.Token,
                    OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode,
                    OpenIddictConstants.Permissions.GrantTypes.RefreshToken,

                    OpenIddictConstants.Scopes.OfflineAccess,
                    OpenIddictConstants.Scopes.Profile,
                    OpenIddictConstants.Scopes.Roles
                }
            };

            var app = await _applicationManager.CreateAsync(descriptor);

            var user = new ApplicationUser
            {
                UserName       = model.UserName,
                Email          = $"{model.ClientId}@demo-apps.local",
                EmailConfirmed = true,
                Applications   = new List <ObjectId> {
                    app.Id
                }
            };
            await _userManager.CreateAsync(user, model.UserPasssword);

            return(View("index", model));
        }
예제 #18
0
        private async Task SeedIdsClientsAsync()
        {
            if (await _manager.FindByClientIdAsync("test_client") == null)
            {
                var descriptor = new OpenIddictApplicationDescriptor
                {
                    ClientId     = "test_client",
                    ClientSecret = "901564A5-E7FE-42CB-B10D-61EF6A8F3654",
                    DisplayName  = "Test client",
                    Permissions  =
                    {
                        OpenIddictConstants.Permissions.Endpoints.Token,
                        OpenIddictConstants.Permissions.GrantTypes.RefreshToken,
                        OpenIddictConstants.Permissions.GrantTypes.Password,
                        OpenIddictConstants.Permissions.Scopes.Email,
                        OpenIddictConstants.Permissions.Scopes.Profile,
                        OpenIddictConstants.Permissions.Scopes.Roles
                    }
                };

                await _manager.CreateAsync(descriptor);
            }
        }
예제 #19
0
        public async Task <IActionResult> Create(CreateOpenIdApplicationViewModel model, string returnUrl = null)
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageOpenIdApplications))
            {
                return(Unauthorized());
            }

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

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

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

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

            var roleNames = new List <string>();

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

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

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

            if (string.IsNullOrEmpty(returnUrl))
            {
                return(RedirectToAction("Index"));
            }
            return(LocalRedirect(returnUrl));
        }
        public async Task InitializeAsync()
        {
            //if (await manager.FindByClientIdAsync("react") == null)
            //{
            //    var descriptor = new OpenIddictApplicationDescriptor
            //    {
            //        ClientId = "react",
            //        ClientSecret = "react_secret",
            //        DisplayName = "SPA client application",
            //        PostLogoutRedirectUris = { new Uri("http://localhost:3000/signout-callback-oidc") },
            //        RedirectUris = { new Uri("http://localhost:3000/signin-oidc") },
            //        Permissions =
            //        {
            //            OpenIddictConstants.Permissions.Endpoints.Authorization,
            //            OpenIddictConstants.Permissions.Endpoints.Logout,
            //            OpenIddictConstants.Permissions.GrantTypes.Implicit
            //        }
            //    };

            //    await manager.CreateAsync(descriptor);
            //}

            var resourceServer = await manager.FindByClientIdAsync("resource_server");

            if (resourceServer == null)
            {
                var descriptor = new OpenIddictApplicationDescriptor
                {
                    ClientId     = "resource_server",
                    ClientSecret = "resource_server_secret",
                    Permissions  =
                    {
                        OpenIddictConstants.Permissions.Endpoints.Token,
                        OpenIddictConstants.Permissions.GrantTypes.ClientCredentials
                    }
                };

                await manager.CreateAsync(descriptor);
            }

            var mvcClient = await manager.FindByClientIdAsync("mvc_client");

            if (mvcClient == null)
            {
                var descriptor = new OpenIddictApplicationDescriptor
                {
                    ClientId               = "mvc_client",
                    ClientSecret           = "mvc_client_secret",
                    DisplayName            = "MVC Client application",
                    PostLogoutRedirectUris = { new Uri($"{configuration["Client:BaseUrl"]}external/logout") },
                    RedirectUris           = { new Uri($"{configuration["Client:BaseUrl"]}external/login") },
                    Permissions            =
                    {
                        OpenIddictConstants.Permissions.Endpoints.Authorization,
                        OpenIddictConstants.Permissions.Endpoints.Logout,
                        OpenIddictConstants.Permissions.Endpoints.Token,
                        OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode,
                        OpenIddictConstants.Permissions.GrantTypes.RefreshToken
                    }
                };

                foreach (var scope in scopes.GetScopes())
                {
                    descriptor.Permissions.Add($"scp:{scope}");
                }

                await manager.CreateAsync(descriptor);
            }
            else
            {
                var permissions = new JArray(
                    OpenIddictConstants.Permissions.Endpoints.Authorization,
                    OpenIddictConstants.Permissions.Endpoints.Logout,
                    OpenIddictConstants.Permissions.Endpoints.Token,
                    OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode,
                    OpenIddictConstants.Permissions.GrantTypes.RefreshToken);

                foreach (var scope in scopes.GetScopes())
                {
                    permissions.Add($"scp:{scope}");
                }

                mvcClient.Permissions = JsonConvert.SerializeObject(permissions);
                await manager.UpdateAsync(mvcClient);
            }

            var swagger = await manager.FindByClientIdAsync("swagger");

            if (swagger == null)
            {
                var descriptor = new OpenIddictApplicationDescriptor
                {
                    ClientId     = "swagger",
                    DisplayName  = "Swagger",
                    RedirectUris = { new Uri(Combine(addressResolver.Resolve(), "/swagger/oauth2-redirect.html")) },
                    Permissions  =
                    {
                        OpenIddictConstants.Permissions.Endpoints.Authorization,
                        OpenIddictConstants.Permissions.GrantTypes.Implicit
                    }
                };

                foreach (var scope in scopes.GetScopes())
                {
                    descriptor.Permissions.Add($"scp:{scope}");
                }

                await manager.CreateAsync(descriptor);
            }
            else
            {
                var permissions = new JArray(OpenIddictConstants.Permissions.Endpoints.Authorization, OpenIddictConstants.Permissions.GrantTypes.Implicit);
                foreach (var scope in scopes.GetScopes())
                {
                    permissions.Add($"scp:{scope}");
                }

                swagger.Permissions = JsonConvert.SerializeObject(permissions);
                await manager.UpdateAsync(swagger);
            }
        }