首页 > 解决方案 > 有没有办法在身份验证后在 ASP.NET Core 中间件中添加声明?

问题描述

我的启动中有这个:

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.UseAuthentication()”,app.UseMiddleware但没有任何影响。

我目前正在使用多个身份验证方案。我不确定这是否有影响。

标签: c#asp.net-core

解决方案


是的,这是可能的,但是您必须添加一个 type 的新身份,而不是添加到现有声明列表中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);
    }
}

推荐阅读