微服务中的ASP.NET Core身份验证和授权

问题描述 投票:0回答:1

我希望在单独的微服务中执行身份验证和授权。同时,我的授权微服务不是一个身份提供者,而是一个简单的API。

如何配置 ASP.NET Core 中的哪个端点用于身份验证以及在访问目标端点之前向其发送哪些数据?

我在文档中找到了以下方法:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        // base-address of your identityserver
        options.Authority = "https://demo.identityserver.io";

        // name of the API resource
        options.Audience = "api1";
    });

我是否正确理解这就是我所需要的,但它使用身份服务器?

如何在不使用的情况下完成此任务?

c# asp.net-core authentication authorization
1个回答
0
投票

在 ASP.NET 中为微服务架构实现身份验证和授权涉及多个步骤和注意事项,以确保安全高效的用户访问控制。以下是有关如何实现此目标的综合指南:

1. 身份验证

身份验证验证用户或服务的身份。在微服务架构中,通常使用基于令牌的身份验证机制,例如 JWT(JSON Web 令牌)。

实现身份验证的步骤:

1.1。集中认证服务:

  • 身份提供商 (IdP): 使用集中式身份提供商,例如 IdentityServer4、Azure Active Directory 或 Auth0。该服务将处理用户身份验证并颁发令牌。
  • OAuth2/OpenID Connect:这些协议广泛用于在微服务中实现身份验证。它们允许应用程序验证用户身份并获得对用户数据的有限访问权限。

1.2。代币发行:

  • 当用户登录时,IdP 会发出包含用户声明(身份信息和权限)的 JWT。

1.3。代币验证:

  • 每个微服务都需要验证传入的令牌。这可以使用 ASP.NET Core 中的中间件来完成。

示例代码:

API网关或微服务的Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication("Bearer")
        .AddJwtBearer("Bearer", options =>
        {
            options.Authority = "https://your-identity-provider";
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateAudience = false
            };
        });

    services.AddAuthorization(options =>
    {
        options.AddPolicy("ApiScope", policy =>
        {
            policy.RequireAuthenticatedUser();
            policy.RequireClaim("scope", "api1");
        });
    });

    services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers()
            .RequireAuthorization("ApiScope");
    });
}

2. 授权

授权决定了经过身份验证的用户可以执行哪些操作。在微服务设置中,授权可以是基于角色 (RBAC) 或基于声明的。

实施授权步骤:

2.1。基于角色的访问控制 (RBAC):

  • 为用户分配角色,并根据角色定义权限。
  • 使用 ASP.NET 中的属性来实施基于角色的授权。

示例代码:

[Authorize(Roles = "Admin")]
public class AdminController : ControllerBase
{
    // Actions that only Admin can access
}

2.2。基于策略的授权:

  • 根据用户声明定义策略。

示例代码:

services.AddAuthorization(options =>
{
    options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
    options.AddPolicy("RequireUserClaim", policy => policy.RequireClaim("UserType", "Premium"));
});

[Authorize(Policy = "RequireAdminRole")]
public class AdminController : ControllerBase
{
    // Actions that only users with Admin role can access
}

[Authorize(Policy = "RequireUserClaim")]
public class PremiumUserController : ControllerBase
{
    // Actions that only users with the claim UserType = Premium can access
}

3. 代币传播

在微服务中,一个请求可能会经过多个服务。跨服务传播用户的身份和声明至关重要。

3.1。代币转发:

  • 使用 HttpClient 将令牌从一项服务转发到另一项服务。

示例代码:

public class SomeService
{
    private readonly HttpClient _httpClient;

    public SomeService(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task CallAnotherService(string token)
    {
        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
        var response = await _httpClient.GetAsync("https://another-microservice/api/data");
        response.EnsureSuccessStatusCode();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.