我有这个在我的启动:
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();
}
我需要添加一些额外的请求后,对用户进行身份验证,但中间件调用函数总是验证之前触发(HttpContext.User.Identity.IsAuthenticated是假的)。但是,当它击中控制器的用户进行身份验证的罚款。
任何想法在这里做什么?我试图把“app.UseAuthentication()”呼叫app.UseMiddleware
后,但它没有影响。
我目前使用多个身份验证方案。我不知道如果有一个影响。
是的,它是可能的,但不是增加现有的版权声明的列表中,您必须添加类型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);
}
}
}
用于.NET核心2.x的优选方法是使用IClaimsTransformation,这具有与音符一个方法TransformAsync(ClaimsPrincipal)
提供一个中心转变点改变指定的主体。注意:这个将在每个AuthenticateAsync调用运行,所以其安全返回一个新的ClaimsPrincipal如果转型不幂等。
根据富集的性质我索赔添加到现有的认证身份或创建新标识和标记,作为认证。随着第二个想法,你可以通过尝试富集前检查您的自定义的身份让你的方法幂等。
您可以将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>();
这取决于你想要做什么和方案使用。
例如,如果你使用JwtBearer
,那么你可以利用JwtBearerOptions.Events
处理由中间件提出了具体的事件。您需要设置在ConfigureServices
类的你Startup
方法。
这将使你的,你希望你的声明添加到,例如,OnTokenValidated
什么精确的情况下,更精细的控制。