问题描述
我正在设法了解如何在微服务环境中实现安全性,并且目前正在尝试使用.NET Core Identity进行用户访问管理(用户名,密码,哈希等)和IdentityServer4作为令牌的想法基于身份验证和管理。
这是因为我希望有很多客户端进行身份验证:一个使用用户名和密码的Blazer网站;其他可能使用令牌的内部API;以及还将使用OAUTH令牌/刷新令牌逻辑的移动应用。
我正在尝试在一个微服务中实现所有这些功能,因此所有客户端只能在一个地方进行身份验证-各种各样的关守。
我的问题是:这是个好主意还是应该拆分服务?
第二:Wnen我正在测试来自邮递员的Login 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(); }); }
@H_502_19@解决方法
只有当您从授权中间件处收到质询时,即会出现AddIdentityServerAuthentication,即控制器/动作上有一个授权属性。
总的来说,我也始终建议您将IdentityServer与客户端和API分开,以更好地分离问题。