从IHttpHandler获取Owin IIdentity

时间:2015-09-01 15:30:57

标签: asp.net asp.net-web-api owin iidentity

接受的答案备注:

虽然我很感激帮助创建我自己的OwinMiddleware来进行一些检查后发送图像而不是IHttpModule,但这并没有完全解决问题。

问题是我已经为ajax请求添加了一个Authorization标头,并且在该标头内我发送了我的Bearer的令牌,以便我可以从Owin获取登录的用户信息。因此,我必须将此标头添加到图像请求中,以便能够从图像处理程序中间件获取记录的用户信息。

原始问题:

我正在关注this blog post为我的网站项目创建基于令牌的身份验证。因为我的Web API的某些资源将由本机移动客户端使用。我听说基于令牌的身份验证是实现这一目标的方法。在我自己的项目中,我有一个自定义图像请求处理程序。并且需要此处理程序中记录的用户信息。但是当我尝试从票证中提取用户信息时,我得到null。我不确定这一点,但我认为这里有2个不同的IIdentity对象,我需要存储在Owin Context中的对象。

这里让我给你看一些代码;

我的GrantResourceOwnerCredentials将声明存储到ClaimsIdentity,

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
....
// checking user credentials and get user information into 'usr' variable
....

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim(ClaimTypes.Sid, usr.UserId.ToString()));

            var props = new AuthenticationProperties(new Dictionary<string, string>
                {
                    {
                        "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                    },
                    {
                        "userId", usr.UserId.ToString()
                    }
                });

            var ticket = new AuthenticationTicket(identity, props);
            context.Validated(ticket);
}

帮助函数从给定的IIdentity对象中提取用户ID

public class utils {
    public Guid? GetUserIdFromTicket(IIdentity identity)
    {
        var cId = (ClaimsIdentity)identity;
        var uid = cId.FindFirst(ClaimTypes.Sid);

        if (uid != null && Comb.IsComb(uid.Value))
            return new Guid(uid.Value);
        else
            return null;
    }
....
}

现在我可以从我的控制器获取loggedUserId,例如

    var loggedUserId = utils.GetUserIdFromTicket(User.Identity);

但如果我从我的IHttpHandler中调用它,我会得到null,

    public class ImageHandler : IHttpHandler
    {
        public ImageHandler()
        {
        }

        public ImageHandler(RequestContext requestContext)
        {
            RequestContext = requestContext;
        }

        protected RequestContext RequestContext { get; set; }

        public utils utils = new utils(); // changed name for simplicity.

        public void ProcessRequest(HttpContext context)
        {
            var strUserId = RequestContext.RouteData.Values["userid"].ToString();
            var strContentId = RequestContext.RouteData.Values["contentid"].ToString();
            var fileName = RequestContext.RouteData.Values["filename"].ToString();
            var size = RequestContext.RouteData.Values["size"].ToString();

            var loggedUserId = utils.GetUserIdFromTicket(context.User.Identity);

....
image processing
....
            context.Response.End();
        }

}

希望我没有把这件事搞砸了......

解决方案:

在完成一些检查后,我已经实现了自己的中间件来向我的用户提供服务。这是我的Invoke任务实现。其他一切都像接受的答案中推荐的那样。但如上所述,为了实现这一点,我必须使用Authorization标头发送图像,否则loggedUserId将再次为null。

public async override Task Invoke(IOwinContext context)
{
    // need to interrupt image requests having src format : http://www.mywebsite.com/myapp-img/{userid}/{contentId}/{fileName}/{size}/
    if (context.Request.Path.HasValue && context.Request.Path.Value.IndexOf("myapp-img") > -1)
    {
        // get values from url.
        var pathValues = context.Request.Path.Value.Split('/');
        var strUserId = pathValues[2].ToString();
        var strContentId = pathValues[3].ToString();
        var fileName = pathValues[4].ToString();
        var size = pathValues[5].ToString();

        // check if code returned a notfound or unauthorized image as response.
        var hasError = false;

        // get userId from static utils class providing current owin identity object
        var loggedUserId = ChildOnBlogUtils.GetUserIdFromTicket(context.Request.User.Identity);

        // save root path of application to provide error images.
        var rootPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

        // assign content type of response to requested file type
        context.Response.ContentType = ChildOnBlogUtils.GetContentType(context.Request.Path.Value.ToString());

        // if user requested thumbnail send it without doing checks
        if (size == "thumb")
        {
            imgPath = "images/" + strUserId.ToLower() + "/thumbnail/" + fileName;
        }
        else
        {
            var canSee = false;

            // check if user can see the content and put the result into canSee variable
            // I am using loggedUserId inside these checks
            ...
            ...
            // end checks

            if (canSee)
            {
                // removed some more checks here for simplicity
                imgPath = "images/" + strUserId.ToLower() + "/" + fileName;
            }
            else
            {
                context.Response.ContentType = "Image/png";
                var imgData = File.ReadAllBytes(rootPath + "/images/unauthorized.png");
                await context.Response.Body.WriteAsync(imgData, 0, imgData.Length);
                hasError = true;
            }
        }

        if (!hasError) // if no errors have been risen until this point. try to provide the requested image to user.
        {
            try
            {
                var imgData = UserMediaContainer.GetFileContent(imgPath); // get file from storage account (azure)

                if (imgData.Length == 0)
                {
                    context.Response.ContentType = "Image/png";
                    imgData = File.ReadAllBytes(rootPath + "/images/notfound.png");
                    await context.Response.Body.WriteAsync(imgData, 0, imgData.Length);
                }
                else
                {
                    await context.Response.Body.WriteAsync(imgData, 0, imgData.Length);
                }
            }
            catch (Exception ex)
            {
                context.Response.ContentType = "Image/png";
                var imgData = File.ReadAllBytes(rootPath + "/images/notfound.png");
                await context.Response.Body.WriteAsync(imgData, 0, imgData.Length);
            }
        }
    }
    else if (context.Request.Path.HasValue && context.Request.Path.Value.IndexOf("profile-img") > -1)
    {
        // profile image provider. Same code as providing thumbnails.
    }
    else
    {
        // if it is not an image request to be handled. move to the next middleware.
        await Next.Invoke(context);
    }
}

1 个答案:

答案 0 :(得分:1)

我猜你的IHttpHandler是在owin管道中的其他所有内容之前处理的,这意味着它会在授权到位之前得到处理。

由于您正在使用owin,我建议您删除public class ImageProcessingMiddleware : OwinMiddleware { public ImageProcessingMiddleware(OwinMiddleware next): base(next) { } public async override Task Invoke(IOwinContext context) { string username = context.Request.User.Identity.Name; Console.WriteLine("Begin Request"); await Next.Invoke(context); Console.WriteLine("End Request"); } } 并使用一些自定义owin中间件。 遵循此路径将允许您将模块注入管道中的正确位置。

创建中间件非常简单:

public static class ImageProcessingExtensions
{
    public static IAppBuilder UseImageProcessing(this IAppBuilder app)
    {
        return app.Use<ImageProcessingMiddleware>();
    }
}

一旦定义了中间件,就可以为实例化创建扩展方法:

app.UseImageProcessing();

现在您可以在管道中插入中间件:

// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

如果您已经按照Taiseer示例进行操作,那么在配置授权模块后,您将这样做:

Invoke

回到中间件,你可能已经注意到了一个名为public async override Task Invoke(IOwinContext context) { string username = context.Request.User.Identity.Name; Console.WriteLine("Begin Request"); await Next.Invoke(context); Console.WriteLine("End Request"); } 的方法:

{{1}}

这是每个中间件的切入点。正如您所看到的那样,在授权令牌经过验证和授权后,我正在阅读授权用户的姓名。

有一个关于owin中间件的有趣article值得一读。