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

Mor*_*lus 4 c# asp.net-mvc forms-authentication httpwebrequest asp.net-mvc-4

我有一个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");
}
Run Code Online (Sandbox Code Playgroud)

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

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

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(fileDownloadUrl));
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Run Code Online (Sandbox Code Playgroud)

我在这里缺少的是如何将授权传递HttpWebRequestDownloadFile动作.

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

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

var authCookie = FormsAuthentication.GetAuthCookie(User.Identity.Name, true);
var authCoockieValue = authCookie.Value;
Run Code Online (Sandbox Code Playgroud)

然后网站使用了这个值:

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

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

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

Mor*_*lus 5

我找到了解决方案.您需要在此处添加身份验证Cookie HttpWebRequest:

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();
Run Code Online (Sandbox Code Playgroud)