private static Task OnRedirectToIdentityProvider(RedirectContext n, IAdminConfiguration adminConfiguration)
        {
            n.ProtocolMessage.RedirectUri = adminConfiguration.IdentityAdminRedirectUri;

            return(Task.FromResult(0));
        }
示例#2
0
        /// <summary>
        /// Generate default clients, identity and api resources
        /// </summary>
        private static async Task EnsureSeedIdentityServerData <TIdentityServerDbContext>(TIdentityServerDbContext context, IAdminConfiguration adminConfiguration)
            where TIdentityServerDbContext : DbContext, IAdminConfigurationDbContext
        {
            if (!context.Clients.Any())
            {
                foreach (var client in Clients.GetAdminClient(adminConfiguration).ToList())
                {
                    await context.Clients.AddAsync(client.ToEntity());
                }

                await context.SaveChangesAsync();
            }

            if (!context.IdentityResources.Any())
            {
                var identityResources = ClientResources.GetIdentityResources().ToList();

                foreach (var resource in identityResources)
                {
                    await context.IdentityResources.AddAsync(resource.ToEntity());
                }

                await context.SaveChangesAsync();
            }

            if (!context.ApiResources.Any())
            {
                foreach (var resource in ClientResources.GetApiResources().ToList())
                {
                    await context.ApiResources.AddAsync(resource.ToEntity());
                }

                await context.SaveChangesAsync();
            }
        }
        public static void AddAuthenticationServices <TContext, TUserIdentity, TUserIdentityRole>(this IServiceCollection services, IHostingEnvironment hostingEnvironment, IAdminConfiguration adminConfiguration)
            where TContext : DbContext where TUserIdentity : class where TUserIdentityRole : class
        {
            services.AddIdentity <TUserIdentity, TUserIdentityRole>()
            .AddEntityFrameworkStores <TContext>()
            .AddDefaultTokenProviders();

            //For integration tests use only cookie middleware
            if (hostingEnvironment.IsStaging())
            {
                services.AddAuthentication(options =>
                {
                    options.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;

                    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultForbidScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultSignOutScheme      = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
                           options => { options.Cookie.Name = AuthenticationConsts.IdentityAdminCookieName; });
            }
            else
            {
                services.AddAuthentication(options =>
                {
                    options.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = AuthenticationConsts.OidcAuthenticationScheme;

                    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultForbidScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultSignOutScheme      = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
                           options => { options.Cookie.Name = AuthenticationConsts.IdentityAdminCookieName; })
                .AddOpenIdConnect(AuthenticationConsts.OidcAuthenticationScheme, options =>
                {
                    options.Authority            = adminConfiguration.IdentityServerBaseUrl;
                    options.RequireHttpsMetadata = false;

                    options.ClientId = AuthenticationConsts.OidcClientId;

                    options.Scope.Clear();
                    options.Scope.Add(AuthenticationConsts.ScopeOpenId);
                    options.Scope.Add(AuthenticationConsts.ScopeProfile);
                    options.Scope.Add(AuthenticationConsts.ScopeEmail);
                    options.Scope.Add(AuthenticationConsts.ScopeRoles);

                    options.SaveTokens = true;

                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        NameClaimType = JwtClaimTypes.Name,
                        RoleClaimType = JwtClaimTypes.Role,
                    };

                    options.Events = new OpenIdConnectEvents
                    {
                        OnMessageReceived            = OnMessageReceived,
                        OnRedirectToIdentityProvider = n => OnRedirectToIdentityProvider(n, adminConfiguration)
                    };
                });
            }
        }
 public RootConfiguration(IOptions <AdminConfiguration> adminConfiguration)
 {
     AdminConfiguration = adminConfiguration.Value;
 }
示例#5
0
        public static IServiceCollection AddCustomHealthCheck(this IServiceCollection services, IConfiguration configuration, IAdminConfiguration adminConfiguration)
        {
            services.AddHealthChecks()
            .AddCheck("self", () => HealthCheckResult.Healthy())
            .AddUrlGroup(new Uri(adminConfiguration.IdentityServerBaseUrl + configuration["IdentityUrlHC"]),
                         name: "identityapi-check", tags: new string[] { "identityapi" });

            return(services);
        }
示例#6
0
        /// <summary>
        /// Register services for authentication, including Identity.
        /// For production mode is used OpenId Connect middleware which is connected to IdentityServer4 instance.
        /// For testing purpose is used cookie middleware with fake login url.
        /// </summary>
        /// <typeparam name="TContext"></typeparam>
        /// <typeparam name="TUserIdentity"></typeparam>
        /// <typeparam name="TUserIdentityRole"></typeparam>
        /// <param name="services"></param>
        /// <param name="hostingEnvironment"></param>
        /// <param name="adminConfiguration"></param>
        public static void AddAuthenticationServices <TContext, TUserIdentity, TUserIdentityRole>(this IServiceCollection services, IHostingEnvironment hostingEnvironment, IAdminConfiguration adminConfiguration, Microsoft.Extensions.Logging.ILogger logger)
            where TContext : DbContext where TUserIdentity : class where TUserIdentityRole : class
        {
            services.AddIdentity <TUserIdentity, TUserIdentityRole>(options =>
            {
                options.User.RequireUniqueEmail = true;
            })
            .AddEntityFrameworkStores <TContext>()
            .AddDefaultTokenProviders();

            //For integration tests use only cookie middleware
            if (hostingEnvironment.IsStaging())
            {
                services.AddAuthentication(options =>
                {
                    options.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;

                    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultForbidScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultSignOutScheme      = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
                           options => { options.Cookie.Name = AuthenticationConsts.IdentityAdminCookieName; });
            }
            else
            {
                services.AddAuthentication(options =>
                {
                    options.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = AuthenticationConsts.OidcAuthenticationScheme;

                    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultForbidScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultSignOutScheme      = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
                           options =>
                {
                    options.Cookie.Name = AuthenticationConsts.IdentityAdminCookieName;

                    // Issue: https://github.com/aspnet/Announcements/issues/318
                    options.Cookie.SameSite = SameSiteMode.None;
                })
                .AddOpenIdConnect(AuthenticationConsts.OidcAuthenticationScheme, options =>
                {
                    options.Authority = adminConfiguration.IdentityServerBaseUrl;
                    // NOTE: This is only for development set for false
                    // For production use - set RequireHttpsMetadata to true!
                    options.RequireHttpsMetadata = false;
                    options.ClientId             = adminConfiguration.ClientId;
                    options.ClientSecret         = adminConfiguration.ClientSecret;
                    options.ResponseType         = adminConfiguration.OidcResponseType;

                    options.Scope.Clear();
                    foreach (var scope in adminConfiguration.Scopes)
                    {
                        options.Scope.Add(scope);
                    }

                    options.ClaimActions.MapJsonKey(AuthenticationConsts.RoleClaim, AuthenticationConsts.RoleClaim, AuthenticationConsts.RoleClaim);

                    options.SaveTokens = true;

                    options.GetClaimsFromUserInfoEndpoint = true;

                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        NameClaimType = JwtClaimTypes.Name,
                        RoleClaimType = JwtClaimTypes.Role,
                    };

                    options.Events = new OpenIdConnectEvents
                    {
                        OnMessageReceived            = OnMessageReceived,
                        OnRedirectToIdentityProvider = n => OnRedirectToIdentityProvider(n, adminConfiguration)
                    };
                });
            }
        }
示例#7
0
        public static IEnumerable <Client> GetAdminClient(IAdminConfiguration adminConfiguration)
        {
            return(new List <Client>
            {
                new Client
                {
                    ClientId = adminConfiguration.ClientId,
                    ClientName = adminConfiguration.ClientId,
                    ClientUri = adminConfiguration.IdentityAdminBaseUrl,

                    AllowedGrantTypes = GrantTypes.Hybrid,

                    ClientSecrets = new List <Secret>
                    {
                        new Secret(adminConfiguration.ClientSecret.ToSha256())
                    },

                    RedirectUris = { $"{adminConfiguration.IdentityAdminBaseUrl}/signin-oidc" },
                    FrontChannelLogoutUri = $"{adminConfiguration.IdentityAdminBaseUrl}/signout-oidc",
                    PostLogoutRedirectUris = { $"{adminConfiguration.IdentityAdminBaseUrl}/signout-callback-oidc" },
                    AllowedCorsOrigins = { adminConfiguration.IdentityAdminBaseUrl },

                    AllowedScopes =
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        IdentityServerConstants.StandardScopes.Email,
                        "roles"
                    }
                },

                new Client
                {
                    ClientId = adminConfiguration.IdentityAdminApiSwaggerUIClientId,
                    ClientName = adminConfiguration.IdentityAdminApiSwaggerUIClientId,

                    AllowedGrantTypes = GrantTypes.Implicit,

                    RedirectUris = new List <string>
                    {
                        adminConfiguration.IdentityAdminApiSwaggerUIRedirectUrl
                    },
                    AllowedScopes =
                    {
                        adminConfiguration.IdentityAdminApiScope
                    },
                    AllowAccessTokensViaBrowser = true
                },
                new Client
                {
                    ClientId = "mcb_api_swagger",
                    ClientName = "Swagger UI for MCB",
                    AllowedGrantTypes = GrantTypes.Implicit,
                    AllowAccessTokensViaBrowser = true,
                    AccessTokenLifetime = 180,
                    RedirectUris =
                    {
                        "https://localhost:9001/api/oauth2-redirect.html"
                    },
                    AllowedScopes = new []
                    {
                        "tripwithmeapi"
                    }
                },
                new Client
                {
                    ClientName = "Trip With Me WebClient",
                    ClientId = "tripwithmeclient",
                    AllowedGrantTypes = GrantTypes.Implicit,
                    RequireConsent = false,
                    AllowAccessTokensViaBrowser = true,
                    AccessTokenLifetime = 180,
                    RedirectUris = { "https://localhost:4200/assets/oidc-login-redirect.html" },
                    PostLogoutRedirectUris = { "https://localhost:4200/?postLogout=true" },
                    AllowedCorsOrigins = { "https://localhost:4200/" },
                    AllowedScopes = new []
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        "roles",
                        "tripwithmeapi"
                    }
                }
                ,
                new Client
                {
                    ClientName = "Trip With Me Mobile",
                    ClientId = "tripwithmemobile",
                    Description = "Used for All Xamarin Mobile Apps",
                    AllowedGrantTypes = GrantTypes.Hybrid,
                    RequireConsent = false,
                    RequirePkce = true,
                    RedirectUris = { "https://com.mst.uwp" },
                    AllowedCorsOrigins = { "https://com.mst.uwp" },
                    AllowedScopes = new List <string>
                    {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        IdentityServerConstants.StandardScopes.OfflineAccess
                    },
                    AllowOfflineAccess = true,
                    AllowAccessTokensViaBrowser = true
                }
            });
        }
 public AuthorizeCheckOperationFilter(IRootConfiguration rootConfiguration)
 {
     _adminConfiguration = rootConfiguration.AdminConfiguration;
 }