微服务的授权和认证
我有一个移动(本机)和Web应用程序(SPA),用于与后端微服务(在核心2.0中开发)进行身份验证/授权以及其他与域名相关的功能,该功能使用Opendidict进行配置。 这两款应用都获得访问令牌。 我所苦恼的是,所有的微服务都应该接受用户登录的访问令牌和认证/授权(一种中央认证服务),auth微服务(OpenIddict 2. *)中产生的访问令牌。 那么在微服务中,我在REST API标记为[Authorize]时缺少哪些更改?
来自Auth Microservice的代码:
public void ConfigureServices(IServiceCollection services)
{
var connection = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<IdentityDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
options.UseOpenIddict();
});
services.AddAuthentication().AddOAuthValidation();
services.AddOpenIddict(options =>
{
options.AddEntityFrameworkCoreStores<IdentityDbContext>();
options.AddMvcBinders();
options.EnableTokenEndpoint("/connect/token");
// Enable the password flow.
options.AllowPasswordFlow().AllowRefreshTokenFlow();
options.SetRefreshTokenLifetime(TimeSpan.FromHours(1));
options.DisableHttpsRequirement();
});
services.AddDbContext<AuthDbContext>(options => options.UseSqlServer(connection));
services.AddScoped<IUserRepository, UserRepository>();
services.AddAuthentication(options =>
{
options.DefaultScheme = OAuthValidationDefaults.AuthenticationScheme;
});
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator"));
});
}
通知微服务中的现有代码
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MastersDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddAuthentication().AddOAuthValidation();
services.AddAuthentication(options =>
{
options.DefaultScheme = OAuthValidationDefaults.AuthenticationScheme;
});
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator"));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(builder =>
builder.WithOrigins("*")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
);
//app.UseAntiforgeryToken();
app.UseMvc();
app.UseAuthentication();
}
通知控制器:
// POST api/values
[HttpPost]
[Authorize]
public IActionResult Post(Notification notification)
{
//logic
return Ok();
}
为了令牌能够被所有微服务正确解密,您需要确保包含主密钥(由ASP.NET核心数据保护派生以创建加密和验证密钥)的密钥环正确同步。 该过程如下所述:https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview。
以下是如何使用共享文件夹完成的一个示例:
public void ConfigureServices(IServiceCollection services)
{
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(@"serversharedirectory"))
}
您还需要配置两个应用程序以使用相同的“应用程序鉴别器”:
public void ConfigureServices(IServiceCollection services)
{
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(@"serversharedirectory"))
.SetApplicationName("Your application name");
}
链接地址: http://www.djcxy.com/p/22281.html