我的创业公司有这个:
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/