C# 为 WebAPI 禁用 Windows 身份验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14588397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Disable Windows Authentication for WebAPI
提问by ncbl
I am playing with an MVC4 application and using WebAPI for fetching/sending all my data. In a controller I am using an HttpClient request to get the data and all is working fine. The issue I am facing is that when Windows authentication is enabled in the project, the web API calls are returning a 401 Unauthorized error.
我正在使用 MVC4 应用程序并使用 WebAPI 来获取/发送我的所有数据。在控制器中,我使用 HttpClient 请求来获取数据并且一切正常。我面临的问题是,当项目中启用 Windows 身份验证时,Web API 调用返回 401 未经授权的错误。
the code in my controller that does the calling is:
我的控制器中执行调用的代码是:
using (var client = new HttpClient())
{
var invoiceDetailUrl = BASE_URL + Url.HttpRouteUrl(
"DefaultApi",
new { controller = "InvoiceDetails", id = id }
);
var result = client.GetAsync(invoiceDetailUrl).Result;
}
Windows authentication has to be on for the site, but not necessarily the Web API controllers. I have tried excluding the API controllers in the web.config like below:
该站点必须启用 Windows 身份验证,但不一定要启用 Web API 控制器。我尝试在 web.config 中排除 API 控制器,如下所示:
<location path="api">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
but the additions to the web.config did nothing.
但添加到 web.config 没有任何作用。
Any suggestions?
有什么建议?
采纳答案by Cybermaxs
Authentication
验证
Web API assumes that authentication happens in the host. IIS uses HTTP modules for authentication. asp.net now allow you to configure via web.config any of the authentication modules built in to IIS or ASP.NET, or write your own HTTP module to perform custom authentication.
Web API 假定身份验证发生在主机中。IIS 使用 HTTP 模块进行身份验证。asp.net 现在允许您通过 web.config 配置任何内置于 IIS 或 ASP.NET 的身份验证模块,或编写您自己的 HTTP 模块来执行自定义身份验证。
You can use multiple authentications at the same time, it's not a problem. In you case, you need both Windows authentication & Anonymous authentication. Windows authentication will secureyour WebSite, and Anonymous authentication will openyour Web Api.
您可以同时使用多个身份验证,这不是问题。在您的情况下,您需要Windows 身份验证和匿名身份验证。Windows 身份验证将保护您的网站,而匿名身份验证将打开您的 Web Api。
Configure Authentication in IIS
在 IIS 中配置身份验证
Hosting on IIS ExpressOpen the Properties pane (via F4 and not the properties of the project), and apply desired authentication Set "Anonymous Authentication" to "Disabled". Set "Windows Authentication" to "Enabled".
在 IIS Express 上托管打开“属性”窗格(通过 F4 而不是项目的属性),并应用所需的身份验证 将“匿名身份验证”设置为“已禁用”。将“Windows 身份验证”设置为“已启用”。
Hosting on IIS 7 or laterIn IIS Manager, open the Authentication feature in the features View. Enable/Disable desired authentication. If an authentication system is not an option (such as Windows), you'll need to install it via the Server Manager (Add Role Services).
在 IIS 7 或更高版本上托管在 IIS 管理器中,打开功能视图中的身份验证功能。启用/禁用所需的身份验证。如果身份验证系统不是一个选项(例如 Windows),您需要通过服务器管理器(添加角色服务)安装它。
Authorization
授权
asp.net Authorization
asp.net授权
In ASP.NET, there are two ways to authorize access to a given resource: File and Url authorization. I won't explain it here but you can read this article.
在 ASP.NET 中,有两种方法可以授权访问给定资源:文件授权和 Url 授权。我不会在这里解释,但你可以阅读这篇文章。
The important thing is that you can allow/deny users and/or groups in web.config.
重要的是您可以在 web.config 中允许/拒绝用户和/或组。
The default config in Windows authentication is to allow only authentication users *****, like this :
Windows 身份验证中的默认配置是仅允许身份验证用户 *****,如下所示:
<authorization>
<deny users="?" ></deny>
</authorization>
If you want to allow anonymous users ?under the url location "api", add this :
如果要允许匿名用户?在 url 位置“api”下,添加以下内容:
<location path="api">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
Web Api Authorization
Web API 授权
asp.net Web Api Authorization happens later in the pipeline, closer to the controller. That lets you make more granular choices when you grant access to resources.
asp.net Web Api 授权发生在管道的后面,更靠近控制器。这使您可以在授予对资源的访问权限时做出更精细的选择。
Web API provides a built-in authorization filter, AuthorizeAttribute. There is also an AllowAnonymousAttribute. You can use it Globally, on a Controller or on an action. By default, all actions are authorized.
Web API 提供了一个内置的授权过滤器AuthorizeAttribute。还有一个AllowAnonymousAttribute。您可以在全局、控制器或操作上使用它。默认情况下,所有操作都已授权。
Testing Api
测试API
Via Browser
通过浏览器
Integrated Windows authentication works with any browser that supports the Negotiate authentication scheme. It's the cas for Internet Explorer and now Chrome : they will automatically provide Windows Credentials when browsing a Web Site with Windows authentication. Firefox does not support this scheme, so I often test authentication with this browser.
集成 Windows 身份验证适用于支持协商身份验证方案的任何浏览器。它是 Internet Explorer 和现在 Chrome 的 cas:当浏览具有 Windows 身份验证的网站时,它们将自动提供 Windows 凭据。Firefox 不支持这个方案,所以我经常用这个浏览器测试认证。
Via HttpClientYour HttpClient needs to provide Credentials when invoking the Web Api (like browsers). This is done by configuring an HttpClientHandler whith appropriate credentials.
通过 HttpClient调用 Web Api(如浏览器)时,您的 HttpClient 需要提供凭据。这是通过配置具有适当凭据的 HttpClientHandler 来完成的。
//use default credentials aka Windows Credentials
HttpClientHandler handler = new HttpClientHandler()
{
UseDefaultCredentials = true
};
//use username/password credentials
HttpClient client = new HttpClient(handler);
var handler = new HttpClientHandler {
Credentials = new NetworkCredential(username, password)
};
var httpClient = new HttpClient(handler);
Hope this will help you.
希望这会帮助你。
One last important thing in you case, is that your Web Api does not allow anonymous users at all! Because you are using Default Credentialsin your HttpClientHandler, this means that your service requires Windows authentication. You don't have to configure any credentials in an open & public service.
在您的情况下,最后一件重要的事情是您的 Web Api根本不允许匿名用户!因为您在 HttpClientHandler中使用默认凭据,这意味着您的服务需要 Windows 身份验证。您不必在开放和公共服务中配置任何凭据。
回答by Notorious2tall
I came across this question while trying to do something very similar and wanted to add to the answer given above. I haven't found a lot of detailed information out there on how to do this. Just bits and piece all over the web. So hopefully this will add to what's out there.
我在尝试做一些非常相似的事情时遇到了这个问题,并想添加到上面给出的答案中。我还没有找到很多关于如何做到这一点的详细信息。只是网络上的点点滴滴。所以希望这会增加现有的内容。
I have an MVC4 application that has a WebAPI part to it. The MVC app needs to use Windows Auth, but the WebAPI portion needed to be anonymous and have Windows Auth turned off. While the above solution worked for ncbl, it didn't work for me because in my scenario I was not using code to handle credentials. In my scenario, I wanted a web.config or IIS based solution. I started with Cybermaxs' web.config solution and added to it. Here's what I ended up with.
我有一个 MVC4 应用程序,它有一个 WebAPI 部分。MVC 应用程序需要使用 Windows 身份验证,但 WebAPI 部分需要匿名并关闭 Windows 身份验证。虽然上述解决方案适用于 ncbl,但它对我不起作用,因为在我的场景中,我没有使用代码来处理凭据。在我的场景中,我想要一个基于 web.config 或 IIS 的解决方案。我从 Cybermaxs 的 web.config 解决方案开始并添加到其中。这就是我的结果。
<!-- Configure the virtual path api -->
<!-- This section is like a mini-web.config for the virtual path -->
<location path="api">
<system.web>
<authorization>
<!-- All anonymous users access to the virtual path api -->
<allow users="?" />
</authorization>
</system.web>
<!-- Need to include the security overrides else it will inherit from the root of the application -->
<system.webServer>
<security>
<authentication>
<!-- Need to enable anonymous access and turn off Windows authentication for the virtual path -->
<anonymousAuthentication enabled="true"/>
<windowsAuthentication enabled="false"/>
</authentication>
</security>
</system.webServer>
</location>
The key for me was to add the <system.webServer>
section to the web.config so that I could override the authentication for this virtual path. I tried to do this in IIS, but since it was a virtual path, i.e. /api doesn't exist on the web server, this was not possible for me.
对我来说,关键是将该<system.webServer>
部分添加到 web.config,以便我可以覆盖此虚拟路径的身份验证。我试图在 IIS 中执行此操作,但由于它是一个虚拟路径,即 Web 服务器上不存在 /api,这对我来说是不可能的。
Note: Be aware, IIS might have a config file at a higher configuration level that is locking the <authentication>
section, such as in the application.config or machine.config. An element might have the the attribute allowOverride set to false. I was getting a HTTP Error 500.19 (HRESULT: 0x80070021) at first and had to go into the application.config file to change this attribute. I found more details on this error here.
注意:请注意,IIS 可能有一个处于更高配置级别的配置文件来锁定该<authentication>
部分,例如在 application.config 或 machine.config 中。元素可能将属性 allowOverride 设置为 false。起初我收到一个 HTTP 错误 500.19 (HRESULT: 0x80070021),不得不进入 application.config 文件来更改这个属性。我在这里找到了有关此错误的更多详细信息。
Once I had this additional section in the <location>
section of my web.config I made sure to decorate my api controller with [AllowAnonymous]
. Then bam...it all started to work.
一旦我在<location>
web.config的部分有了这个额外的部分,我就确保用[AllowAnonymous]
. 然后砰……一切都开始起作用了。
This is how I have authentication and authorization setup for the root of my application.
这就是我为应用程序的根设置身份验证和授权的方式。
<system.web>
<authentication mode="Windows" />
<authorization>
<!-- Deny all anonymous users at the root of the application -->
<deny users="?" />
</authorization>
</system.web>
回答by jhilden
This is what I needed to do:
这是我需要做的:
<location path="api">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>