需要在Asp.Net Core中处理Post Authenticate

时间:2017-07-11 19:30:04

标签: asp.net-core asp.net-core-identity

我已经准备好使用Asp.Net核心,但这就是我正在做的事情。在MVC 5中,我有一个处理PostAuthenticate事件的Http模块,以便创建声明,我正在做一些事情来确定用户的角色。我认为没有办法在Core中做同样的事情。请注意,这是使用Windows身份验证,因此没有要处理的登录方法。

从当前连接到PostAuthenticate的httpModule,因为我想为用户初始化一些东西。
context.PostAuthenticateRequest + = Context_PostAuthenticateRequest;

请注意,使用Core的httpModules不再存在,而且正在转移到中间件..我不知道如何从那里开始使用该事件。

2 个答案:

答案 0 :(得分:2)

我今天第一次这样做了。这里有两个基本步骤。

第一: 创建一个实现IClaimsTransformer接口的类。

public class MyTransformer : IClaimsTransformer
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext context )
    {
        //don't run if user isn't logged in 
        if(context.Principal.Identity.IsAuthenticated)
        {
           ((ClaimsIdentity)context.Principal.Identity)?.AddClaims(...);
        }
    }
    return Task.FromResult(context.Principal);
}

第二: 将此行添加到

中的Startup.cs
public void Configure(IApplicationBuilder app, ..., ...)
{
    //app.Use...Authentication stuff above, for example
    app.UseOpenIdConnectAuthentication( new OpenIdOptions
    {
        //or however you like to do this. 
    });

    app.UseClaimsTransformation(o => new MyTransformer().TransformAsync(o));
    //UseMvc below
    app.UseMvc(...);
}

请记住,TransformAsync将在每个请求上运行,因此如果您使用会话或缓存,可能需要查看使用会话或缓存。

答案 1 :(得分:0)

Windows身份验证由应用程序管道开头的主机(IIS或HttpSys / WebListener)执行。在这种情况下,管道中的第一个中间件相当于PostAuthenticateRequest。根据需要在HttpContext.User上操作。