代码拉取完成,页面将自动刷新
同步操作将从 ZhangXinYa/Identity 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
// -----------------------------------------------------------------------
// <copyright file="Startup.cs" company="Kengic">
// Copyright (c) Kengic. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Reflection;
using HealthChecks.UI.Client;
using IdentityServer4.Services;
using Kengic.Identity.API.Data;
using Kengic.Identity.API.Infrastructure.Authorization.RolesToPermission;
using Kengic.Identity.API.Infrastructure.Exceptions;
using Kengic.Identity.API.Infrastructure.Filters;
using Kengic.Identity.API.Infrastructure.Services;
using Kengic.Identity.API.Models;
using Kengic.Identity.API.Repositories;
using Kengic.Identity.API.Services;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using StackExchange.Redis;
namespace Kengic.Identity.API
{
/// <summary> A startup. </summary>
public class Startup
{
/// <summary>
/// Initializes a new instance of the <see cref="Startup"/> class. Constructor. </summary>
/// <param name="configuration"> The configuration. </param>
/// <param name="environment"> The environment. </param>
public Startup(IConfiguration configuration, IHostEnvironment environment)
{
Configuration = configuration;
Environment = environment;
}
/// <summary> Gets the configuration. </summary>
/// <value> The configuration. </value>
public IConfiguration Configuration { get; }
/// <summary> Gets the environment. </summary>
/// <value> The environment. </value>
public IHostEnvironment Environment { get; }
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services"> The services. </param>
public void ConfigureServices(IServiceCollection services)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
var connectionString = Configuration["ConnectionString"];
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddCors(options => options.AddPolicy(
"CorsPolicy",
builder => builder
.WithOrigins(
Configuration.GetValue<string>("WebSpaClient"),
"http://localhost:4203",
"http://localhost:4204")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()));
// Add Identity services.
services.AddDbContext<ApplicationDbContext>(options =>
options.EnableSensitiveDataLogging(Environment.IsDevelopment())
.UseSqlServer(
connectionString,
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.MigrationsAssembly(migrationsAssembly);
// Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
}));
services.AddIdentity<ApplicationUser, RolePermissions>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Adds IdentityServer services.
var builder = services.AddIdentityServer(x =>
{
x.IssuerUri = "null";
x.Authentication.CookieLifetime = TimeSpan.FromHours(2);
})
.AddAspNetIdentity<ApplicationUser>() // adds the integration layer to allow IdentityServer to access the user data for the ASP.NET Identity user database.
.AddConfigurationStore(options => options.ConfigureDbContext = builder => builder
.EnableSensitiveDataLogging(Environment.IsDevelopment())
.UseSqlServer(
connectionString,
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.MigrationsAssembly(migrationsAssembly);
// Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
}))
.AddOperationalStore(options => options.ConfigureDbContext = builder => builder
.UseSqlServer(
connectionString,
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.MigrationsAssembly(migrationsAssembly);
// Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency
sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
}));
if (Environment.IsDevelopment())
{
builder.AddDeveloperSigningCredential();
}
else
{
throw new IdentityDomainException("need to configure key material");
}
if (Configuration.GetValue<string>("IsClusterEnv") == bool.TrueString)
{
services.AddDataProtection(opts => opts.ApplicationDiscriminator = "sds")
.PersistKeysToRedis(ConnectionMultiplexer.Connect(Configuration["RedisConnectionString"]), "DataProtection-Keys")
.SetApplicationName("SharedCookieApp");
}
services.AddHealthChecks()
.AddCheck("self", () => HealthCheckResult.Healthy())
.AddSqlServer(
Configuration["ConnectionString"],
name: "IdentityDB-check",
tags: new[] { "IdentityDB" });
services.AddSwaggerGen(options =>
{
var info = new OpenApiInfo
{
Title = "SDS - Identity HTTP API",
Version = "v1",
Description = "The Identity Microservice HTTP API.",
};
options.SwaggerDoc("v1", info);
// Locate the XML file being generated by ASP.NET...
var xmlFile = $"{typeof(Startup).Assembly.GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
// ... and tell Swagger to use those XML comments.
options.IncludeXmlComments(xmlPath, true);
var securityScheme = new OpenApiSecurityScheme
{
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
Implicit = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri($"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize"),
TokenUrl = new Uri($"{Configuration.GetValue<string>("IdentityUrlExternal")}/connect/token"),
Scopes = new Dictionary<string, string>
{
{ "Identity", "Identity API" },
},
},
},
};
options.AddSecurityDefinition("oauth2", securityScheme);
options.OperationFilter<AuthorizeCheckOperationFilter>();
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddTransient<IIdentityService, IdentityService>();
services.AddTransient<IPermissionsMenuService, PermissionsMenuService>();
services.AddTransient<IPermissionsMenuRepository, PermissionsMenuRepository>();
services.AddTransient<IRoleMenuRepository, RoleMenuRepository>();
services.AddTransient<IRoleMenuService, RoleMenuService>();
services.AddTransient<IUserService, UserService>();
services.AddTransient<IWorkingGroupService, WorkingGroupService>();
services.AddTransient<IWorkingGroupRepository, WorkingGroupRepository>();
services.AddTransient<IWorkingGroupUserService, WorkingGroupUserService>();
services.AddTransient<IWorkingGroupUserRepository, WorkingGroupUserRepository>();
services.AddTransient<IPermissionsMenuRepository, PermissionsMenuRepository>();
services.AddTransient<IRoleService, RoleService>();
services.AddTransient<IPermissionCodeRelationRepository, PermissionCodeRelationRepository>();
services.AddTransient<ILoginService<ApplicationUser>, EFLoginService>();
services.AddTransient<IRedirectService, RedirectService>();
services.AddScoped<UserManager<ApplicationUser>, AspNetUserManager<ApplicationUser>>();
services.AddScoped<RoleManager<RolePermissions>, AspNetRoleManager<RolePermissions>>();
services.AddTransient<IProfileService, ProfileService>(); // IdentityServer defines an extensibility point for allowing claims to be dynamically loaded as needed for a user.
// Register the Permission policy handlers
services.AddSingleton<IAuthorizationPolicyProvider, AuthorizationPolicyProvider>();
services.AddTransient<IAuthorizationHandler, PermissionHandler>();
services.Configure<AppSettings>(Configuration);
services.AddAntiforgery(options => { options.HeaderName = "X-XSRF-TOKEN"; });
services.AddControllersWithViews()
.AddNewtonsoftJson();
services.AddAuthentication();
services.AddAuthorization();
services.Configure<IdentityOptions>(options =>
{
// Password settings.
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequiredLength = 6;
options.Password.RequiredUniqueChars = 1;
// User settings.
options.User.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
options.User.RequireUniqueEmail = false;
});
}
/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request
/// pipeline.
/// </summary>
/// <param name="app"> The application. </param>
/// <param name="env"> The environment. </param>
/// <param name="loggerFactory"> The logger factory. </param>
/// <param name="antiforgery"> The antiforgery. </param>
public void Configure(IApplicationBuilder app, IHostEnvironment env, ILoggerFactory loggerFactory, IAntiforgery antiforgery)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
var pathBase = Configuration["PATH_BASE"];
if (!string.IsNullOrEmpty(pathBase))
{
loggerFactory.CreateLogger<Startup>().LogDebug("Using PATH BASE '{pathBase}'", pathBase);
app.UsePathBase(pathBase);
}
app.UseForwardedHeaders();
app.UseCors("CorsPolicy");
app.UseIdentityServer();
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.Use(next => context =>
{
if (context.Request.Path.Value.IndexOf("/api", StringComparison.OrdinalIgnoreCase) != -1)
{
var tokens = antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append(
"XSRF-TOKEN",
tokens.RequestToken,
new CookieOptions { HttpOnly = false });
}
return next(context);
});
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
endpoints.MapHealthChecks("/health/ready", new HealthCheckOptions { Predicate = _ => true, ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse });
endpoints.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = (_) => false });
});
app.UseSwagger()
.UseSwaggerUI(c =>
{
c.SwaggerEndpoint($"{(!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty)}/swagger/v1/swagger.json", "Kengic.Identity.API V1");
c.OAuthClientId("identity_swaggerui");
c.OAuthAppName("Identity Swagger UI");
c.DocumentTitle = "Identity Swagger UI";
});
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。