簡體   English   中英

有沒有辦法在身份驗證后在 ASP.NET Core 中間件中添加聲明?

[英]Is there a way to add claims in an ASP.NET Core middleware after Authentication?

我在我的啟動中有這個:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseSwaggerWithUi();

    app.UseAuthentication();
    app.UseMiddleware<SomeMiddleware>();

    app.UseMvc();
}

我需要在用戶通過身份驗證后添加一些額外的聲明,但中間件調用函數總是在 Auth 之前觸發(HttpContext.User.Identity.IsAuthenticated 為 false)。 但是當它擊中控制器時,用戶的身份驗證很好。

知道在這里做什么嗎? 我嘗試在調用app.UseMiddleware后放置“app.UseAuthentication()”,但沒有任何影響。

我目前正在使用多種身份驗證方案。 我不確定這是否有影響。

是的,這是可能的,但是您必須添加一個ClaimsIdentity類型的新身份,而不是添加到現有聲明列表中。

public class SomeMiddleware
{
    private readonly RequestDelegate _next;

    public SomeMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        if (httpContext.User != null && httpContext.User.Identity.IsAuthenticated)
        {
            var claims = new List<Claim>
            {
                new Claim("SomeClaim", "SomeValue")
            };

            var appIdentity = new ClaimsIdentity(claims);
            httpContext.User.AddIdentity(appIdentity);                
        }

        await _next(httpContext);
    }
}

您可以在UseAuthentication()之后立即添加另一個中間件以添加聲明:

app.UseAuthentication();
app.Use(async(context, next)=>{
    if(context.User !=null && context.User.Identity.IsAuthenticated){
        // add claims here 
        context.User.Claims.Append(new Claim("type-x","value-x"));
    }
    await next();
});

//  call other middlewares 
app.UseMiddleware<SomeMiddleware>();

您可以編寫自己的中間件來添加新聲明。

public class YourCustomMiddleware
{
    private readonly RequestDelegate _next;

    public YourCustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext httpContext)
    {
        if (httpContext.User != null && httpContext.User.Identity.IsAuthenticated)
        {

            httpContext.User.Identities.FirstOrDefault().AddClaim(new Claim("your claim", "your field"));
        }
        await _next(httpContext);
    }
}

並在您的應用程序啟動中

app.UseAuthentication();
app.UseMiddleware<YourCustomMiddleware>();

.NET Core 2.x 的首選方法是使用IClaimsTransformation ,它有一個帶有注釋的 TransformAsync(ClaimsPrincipal) 方法

提供一個中央轉換點來更改指定的主體。 注意:這將在每個 AuthenticateAsync 調用上運行,因此如果您的轉換不是冪等的,則返回新的 ClaimsPrincipal 會更安全。

根據擴充的性質,我將聲明添加到現有的已驗證身份或創建一個新身份並將其標記為已驗證。 使用第二個想法,您可以通過在嘗試豐富之前檢查您的自定義身份來使您的方法具有冪等性。

這取決於您想做什么以及您使用哪種方案。

例如,如果您使用JwtBearer那么您可以利用JwtBearerOptions.Events來處理中間件引發的特定事件。 您需要在Startup類的ConfigureServices方法中進行設置。

這將使您能夠更精細地控制您希望將 Claims 添加到哪個精確案例,例如OnTokenValidated

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM