在ASP.Net Identity项目架构中集成IdentityServer4,可以按照以下步骤进行操作:
创建ASP.Net Core Web应用程序项目:
添加IdentityServer4 NuGet包:
Install-Package IdentityServer4
创建IdentityServer配置文件:
public static class Config
{
public static IEnumerable IdentityResources =>
new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
public static IEnumerable ApiScopes =>
new ApiScope[]
{
new ApiScope("api1", "My API"),
};
public static IEnumerable Clients =>
new Client[]
{
new Client
{
ClientId = "client",
ClientSecrets = { new Secret("secret".Sha256()) },
AllowedGrantTypes = GrantTypes.ClientCredentials,
AllowedScopes = { "api1" }
}
};
}
配置IdentityServer服务:
ConfigureServices
方法中注册IdentityServer服务和ASP.Net Identity:services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryIdentityResources(Config.IdentityResources)
.AddInMemoryApiScopes(Config.ApiScopes)
.AddInMemoryClients(Config.Clients)
.AddAspNetIdentity();
Configure
方法中启用IdentityServer中间件:app.UseIdentityServer();
配置ASP.Net Identity:
ConfigureServices
方法中配置ASP.Net Identity服务:services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity()
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
Configure
方法中启用ASP.Net Identity中间件:app.UseAuthentication();
创建用户和角色:
Configure
方法中添加以下代码,用于创建用户和角色:using (var scope = app.ApplicationServices.GetRequiredService().CreateScope())
{
var userManager = scope.ServiceProvider.GetRequiredService>();
var roleManager = scope.ServiceProvider.GetRequiredService>();
if (!await roleManager.RoleExistsAsync("Admin"))
{
await roleManager.CreateAsync(new IdentityRole("Admin"));
}
var adminUser = new ApplicationUser
{
UserName = "admin@example.com",
Email = "admin@example.com"
};
var result = await userManager.CreateAsync(adminUser, "Admin123!");
if (result.Succeeded)
{
await userManager.AddToRoleAsync(adminUser, "Admin");
}
}
启动应用程序:
这就是将IdentityServer4集成到ASP.Net Identity项目架构中的基本步骤。你可以根据需要进行进一步的配置和定制。