首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从IIdentity获得Owin IHttpHandler

从IIdentity获得Owin IHttpHandler
EN

Stack Overflow用户
提问于 2015-09-01 15:30:56
回答 1查看 967关注 0票数 1

接受答案注:

虽然我很感激创建自己的OwinMiddleware,在做了一些检查之后才发送图像,而不是IHttpModule,但这并不能完全解决问题。

问题是,我在ajax请求中添加了一个授权头,在这个标头中,我发送了Bearer的令牌,这样我就可以从Owin获得记录的用户信息。因此,我必须将这个标题添加到图像请求中,以便能够从图像处理中间件获得记录的用户信息。

原始问题:

我跟随这篇博客文章为我的web项目创建基于令牌的身份验证。因为我的Web的某些资源将被本地移动客户端使用。我听说,基于令牌的认证是实现这一目标的途径。在我自己的项目中,我有一个自定义的图像请求处理程序。并需要在此处理程序中记录的用户信息。但是,当我试图从票证中提取用户信息时,我会得到null。我对此并不确定,但我认为这里有两个不同的IIdentity对象,我需要一个存储在Owin上下文中的对象。

这里,让我给你们展示一些密码;

我的GrantResourceOwnerCredentials将声明存储到ClaimsIdentity中,

代码语言:javascript
复制
    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。

代码语言:javascript
复制
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,

代码语言:javascript
复制
    var loggedUserId = utils.GetUserIdFromTicket(User.Identity);

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

代码语言:javascript
复制
    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();
        }

}

希望我没把事情搞砸.

解决方案:

在做了一些检查之后,我实现了自己的中间件来向我的用户提供映像服务。下面是我的调用任务实现。其他的一切都和公认的答案中所建议的一样。但如前所述,要使此工作,我必须用授权头发送图像,否则loggedUserId将再次为null。

代码语言:javascript
复制
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);
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-01 20:02:56

我想您的ImageHandler是在owin管道中的其他所有内容之前处理的,这意味着它是在授权生效之前处理的。

由于您使用的是owin,所以我建议您放弃IHttpHandler并使用一些定制的owin中间件。遵循此路径将允许您将模块注入管道中的正确位置。

创建中间件非常容易:

代码语言:javascript
复制
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");
    }
}

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

代码语言:javascript
复制
public static class ImageProcessingExtensions
{
    public static IAppBuilder UseImageProcessing(this IAppBuilder app)
    {
        return app.Use<ImageProcessingMiddleware>();
    }
}

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

代码语言:javascript
复制
app.UseImageProcessing();

如果您已经遵循Taiseer示例,那么在配置了授权模块之后,您将这样做:

代码语言:javascript
复制
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

回到中间件,您可能已经注意到有一个名为Invoke的方法

代码语言:javascript
复制
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中间件有一个有趣的文章,值得一读。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32335531

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档