身份验证后,是否可以在ASP.NET Core中间件中添加声明? [英] Is there a way to add claims in an ASP.NET Core middleware after Authentication?

查看:91
本文介绍了身份验证后,是否可以在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();
}

我需要在用户通过身份验证后添加一些其他声明,但是中间件Invoke函数总是在Auth(HttpContext.User.Identity.IsAuthenticated为false)之前触发.但是当它碰到控制器时,用户便可以通过身份验证.

I need to add some additional claims AFTER the user is authenticated, but the middleware Invoke function always fires before Auth (HttpContext.User.Identity.IsAuthenticated is false). But when it hits the controller the user is authenticated fine.

有什么想法在这里做什么?我试过在调用 app.UseMiddleware 后放入"app.UseAuthentication()",但它没有任何作用.

Any idea what to do here? I've tried to put "app.UseAuthentication()" after calling app.UseMiddleware but it has no affect.

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

I'm currently using multiple Authentication schemes. I'm not sure if that has an affect.

推荐答案

是可以的,但是除了添加到现有声明列表中之外,您还必须添加类型为 ClaimsIdentity 的新标识./p>

Yes it's possible, but instead of adding to the list of existing claims you have to add a new identity of 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);
    }
}

这篇关于身份验证后,是否可以在ASP.NET Core中间件中添加声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆