c# - 有没有办法在身份验证后在 ASP.NET Core 中间件中添加声明?

标签 c# 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)。但是当它到达 Controller 时,用户就可以通过身份验证了。

知道要做什么吗?我尝试在调用 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);
    }
}

关于c# - 有没有办法在身份验证后在 ASP.NET Core 中间件中添加声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53292286/

相关文章:

c# - 在 .NET Core 中以字符串形式返回 View

c# - ASP.NET核心: UsePathBase extracts pathbase from path but MapControllers() does not consider path

c# - 缺少字段异常 : Field not found: 'Microsoft.Net.Http.Headers.HeaderNames.Authorization'

c# - ASP.NET MVC 论坛?

c# - .Net Socket Read 功能阻塞问题

c# - orm 和 ADO.net 有什么区别?

c# - Entity Framework DbContext : Value cannot be null, 参数名称来源

asp.net - 更新数据库失败 : "The index ' IX_Task_UserId' is dependent on column 'UserId' "

带有本地服务器的 Docker/Kubernetes

c# - 如何在 FluentValidation 的世界中使用带有 ValidateAsync 的规则集?