[英]Using ASP.NET Core Identity with IdentityServer4 - Authentication
我正在尝试了解如何在微服务环境中实现安全性,目前正在考虑使用 .NET Core Identity 进行用户访问管理(用户名、密码、散列等)和 IdentityServer4 进行基于令牌的身份验证和管理。
这是因为我想要一个客户端进行身份验证:一个将使用用户名和密码的 Blazer 网站; 其他可能使用令牌的内部 API; 以及一个也将使用 OAUTH 令牌/刷新令牌逻辑的移动应用程序。
我试图在一个微服务中实现所有这些,所以只有一个地方所有客户端都可以进行身份验证 - 各种看门人。
我的问题是:这是一个好主意还是我应该拆分服务?
其次:Wnen 我正在测试来自邮递员的登录 API 调用,因为 API 试图将我重定向到登录页面,因此我收到了 404。 我希望在这里使用 401,因为我已将身份验证方案定义为Bearer 。
这是我的代码:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddNewtonsoftJson();
var connectionString = Configuration.GetConnectionString("DefaultConnection");
//add Users and Role system
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
//this configures the dependancy injection for the UserManager in the Identity controller constructor.
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
//add Client tokens system
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddIdentityServer()
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder =>
builder.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
})
.AddOperationalStore(options =>
{
options.ConfigureDbContext = b => b.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
})
.AddAspNetIdentity<IdentityUser>();//required for Identity and IdentityServer4 to play nice together.
//add authentication for this service
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5001";//this service
options.RequireHttpsMetadata = false;
options.ApiName = "Identity";
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// InitializeIdentityServerDatabase(app);
app.UseHttpsRedirection();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
AddIdentityServerAuthentication 只会在您从授权中间件收到质询时启动,即控制器/操作上有授权属性。
一般来说,我也总是建议您将 IdentityServer 与您的客户端和 API 分开,以获得更好的关注点分离。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.