【问题标题】:.NET WebApi Authentication.NET WebApi 身份验证
【发布时间】:2012-09-12 22:27:58
【问题描述】:

目前,我有一个销售小部件的 MVC Web 应用程序。用户使用表单身份验证登录我们的系统,然后可以根据他们所属的组执行各种功能(即下订单、查看订单、取消订单等)。

我们的任务是编写一个 API,让第三方能够在我们的系统中创建和查看订单。每个第三方都有自己的用户名,并且会根据他们所属的组限制使用某些 api 方法。

我们正在研究使用 Web Api 作为提供 api 的机制。我们还希望能够从我们的 MVC Web 应用程序中使用这个 api。不幸的是,我们遇到了 Web Api 身份验证的问题。使用 DelegatingHandler,我们为 WebApi 实现了基于 SSL 的基本身份验证。这对我们的第三方非常有用。但是,当尝试从我们的 MVC 应用程序使用 Api 时,我们会收到 401 access denied 错误,因为用户在 MVC 应用程序中使用 Forms 身份验证进行了身份验证,但我们无法将这些凭据传递给 Web Api。有没有办法将表单身份验证凭据从我们的 MVC 应用程序传递到我们的 Web api 应用程序?

IIS 设置 具有两个 Web 应用程序的名为 WidgetStore 的网站

  • WidgetStore\UI - 使用表单身份验证
  • WidgetStore\Api - 使用基本身份验证

【问题讨论】:

标签: asp.net-mvc rest authentication asp.net-web-api


【解决方案1】:

有没有办法将 Forms Auth 凭据从我们的 MVC 应用程序传递到我们的 Web api 应用程序?

当然,我们以调用 Web API 的以下 MVC 控制器操作为例:

[Authorize]
public ActionResult CallWebApi()
{
    var baseAddress = new Uri("https://example.com");
    var cookieContainer = new CookieContainer();
    using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
    using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
    {
        var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName].Value;
        cookieContainer.Add(baseAddress, new Cookie(FormsAuthentication.FormsCookieName, authCookie));
        var result = client.GetAsync("/api/values").Result;
        result.EnsureSuccessStatusCode();

        // now you can read the result.Content ...
    }
}

这假设您还在 Web API 项目的 web.config 中启用了表单身份验证,并且 cookie 名称与 MVC 项目中使用的名称相同。

【讨论】:

  • 感谢您的回复。但是,如果我在我的 Web API 项目的 web.config 中启用 FormsAuthentication,第三方将无法进行身份验证。他们使用 BASIC 身份验证连接到 WebApi,它将不再工作。第三方将没有 FormsAuth cookie
  • 但是您的基本表单身份验证委托处理程序是什么样的?如果看起来像这样,启用表单身份验证不会有问题:stackoverflow.com/a/11536349/29407
猜你喜欢
  • 2015-10-01
  • 2014-09-04
  • 2018-01-07
  • 2013-07-12
  • 1970-01-01
  • 2020-06-05
  • 2018-08-03
  • 1970-01-01
  • 2014-04-05
相关资源
最近更新 更多