繁体   English   中英

如何对ASP.NET MVC Web应用程序进行授权的HttpWebRequest

[英]How to make an Authorized HttpWebRequest to an ASP.NET MVC web app

我有一个ASP.NET MVC Web应用程序,需要允许公共API下载文件。 这是动作代码:

public ActionResult DownloadFile(int id)
{
        var item = _context.GetRepositoryFileByID(id);
        if (item == null)
        {
            return HttpNotFound();
        }
        var filePath = Path.Combine(AppConfig.FilesRepositoryStorageRoot, item.IntrenalFilePath);
        return File(filePath, "application/pdf");
}

此方法是设置了[Authorize(Roles = "Administrator,User")]属性的控制器,因此只有登录用户才能访问此操作

现在,此操作应允许用户使用以下代码发出请求:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(fileDownloadUrl));
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

我在这里缺少的是如何将授权的HttpWebRequest传递给DownloadFile操作。

我尝试的每件事都会返回登录页面,因为应用程序无法授权用户并允许他访问DownloadFile操作。

我试图使用以下代码将此Cookie值传递给请求该文件的网站

var authCookie = FormsAuthentication.GetAuthCookie(User.Identity.Name, true);
var authCoockieValue = authCookie.Value;

然后网站使用了这个值:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(fileDownloadUrl));
request.Headers[HttpRequestHeader.Authorization] = "Bearer " + authorization;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

但是这没有用。我也尝试用“Basic”而不是“Bearer”标签传递标题,但它也是字段。

我不明白我不太了解ASP.NET MVC应用程序如何使用FormsAuthentication[Authorize]属性,所以我谦虚地请求你的帮助......

我找到了解决方案。 您需要向HttpWebRequest添加身份验证Cookie,如下所示:

Uri fileDownloadURI = new Uri(fileDownloadUrl);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fileDownloadURI);
request.Headers[HttpRequestHeader.Authorization] = "Bearer " + authorization;
var authCookie = FormsAuthentication.GetAuthCookie(User.Identity.Name, true);
Cookie requestAuthCoockie = new Cookie()
{
    Expires = authCookie.Expires,
    Name = authCookie.Name,
    Path = authCookie.Path,
    Secure = authCookie.Secure,
    Value = authCookie.Value,
    Domain = fileDownloadURI.Host,
    HttpOnly = authCookie.HttpOnly,
};
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(requestAuthCoockie);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

取决于您使用的是哪种身份验证。 通常,只需模拟用户登录时浏览器正在执行的操作(您应该根据您的代码+ web.config知道,或者您可以使用Web调试工具来捕获Web请求)。 如果是登录表单和cookie,只需从HttpWebRequest调用登录操作,并使用CookieContainer,以便生成的cookie持久保存到下一个请求。 或者您可以创建新的身份验证API,甚至是使用不同身份验证的全新Web应用程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM