【发布时间】:2013-03-31 17:17:16
【问题描述】:
我开始研究 Web Api,只想创建一个简单的基本身份验证。我想知道该怎么做?
我尝试使用给定的 MSDN 链接,但 MSDN 上没有提供分步教程。 http://www.asp.net/web-api/overview/security/basic-authentication
【问题讨论】:
标签: authentication basic-authentication asp.net-web-api
我开始研究 Web Api,只想创建一个简单的基本身份验证。我想知道该怎么做?
我尝试使用给定的 MSDN 链接,但 MSDN 上没有提供分步教程。 http://www.asp.net/web-api/overview/security/basic-authentication
【问题讨论】:
标签: authentication basic-authentication asp.net-web-api
您提供的链接提供了您需要的大部分详细信息,我希望这能填补空白。
注意:如果使用 Web.API 2,Microsoft 建议使用 authentication filters 的不同方法。
如果您需要真正的安全性,这非常重要,否则窥探方可能会收集到密码。你如何做到这一点完全取决于你的设置,你没有详细说明,但如果你正在使用 Azure WebRole,那么来自 Microsoft 的 step-by-step guide to setting up SSL 非常好。
这不是后续步骤所必需的,但应该在发布代码之前完成。我首先提到它是因为这部分通常涉及让其他人参与(服务器配置的系统管理员,购买证书的财务等),并且给他们很多警告是很好的。
这是 C# 代码 in your link 的大块 - 它解析浏览器发送的值并将 HttpContext.Current.User 设置为经过身份验证的用户。只需将肉复制并粘贴到您自己的应用程序中的一个类中,我们稍后再讨论。您需要在代码中使用以下 using 语句。
using System; using System.Net.Http.Headers; using System.Security.Principal;
using System.Text; using System.Threading; using System.Web;
将新模块添加到您的 web.config 文件(注意 system.webServer 可能已经存在)
<system.webServer>
<modules>
<add name="BasicAuth" type="Full.ClassName.Path.BasicAuth, Assembly.Name"/>
</modules>
</system.webServer>
您可以通过在操作定义前添加 [Authorize] 属性来阻止特定操作。通过在您的控制器类之前添加它来阻止整个控制器。
[Authorize] // Restricts access to whole controller
public class StockController : ApiController {
[Authorize] // Restricts access to this action - not necessary if whole controller restricted.
public IEnumerable<StockLevel> Get() {
或者在您的 App_Start\WebApiConfig.cs 文件中添加config.Filters.Add(new AuthorizeAttribute());,它将锁定所有内容。
需要注意的一点 - 还有一个 System.Web.Mvc.AuthorizeAttribute,所以如果您包含该命名空间,您可能会得到令人困惑的结果。
此时你可以试一试——user: "user", pass: "password"。
回到我们从链接中窃取的课程,你会看到以下代码块:
// TODO: Here is where you would validate the username and password.
private static bool CheckPassword(string username, string password)
如果用户名和密码有效,则更改此项以返回 true。如果你自己动手,你可能想调查bcrypt(你相信你从网上下载的实现吗?),PBKDF2 或Crypto class(简单但不是非常安全)但可能有更好的东西Microsoft 因为正确存储密码存在很多问题。
【讨论】:
我必须在 MSDN 示例中添加几行代码才能使其正常工作。具体来说,在 OnApplicationAuthenticateRequest() 中,如果无法验证用户,我将响应状态代码设置为 401:
private static void OnApplicationAuthenticateRequest(object sender, EventArgs e)
{
var request = HttpContext.Current.Request;
var authHeader = request.Headers["Authorization"];
bool validated = false;
if (authHeader != null)
{
var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);
// RFC 2617 sec 1.2, "scheme" name is case-insensitive
if (authHeaderVal.Scheme.Equals("basic",
StringComparison.OrdinalIgnoreCase) &&
authHeaderVal.Parameter != null)
{
validated = AuthenticateUser(authHeaderVal.Parameter);
}
}
if (!validated)
{
HttpContext.Current.Response.StatusCode = 401;
}
}
一旦我这样做了,它就工作得很好。可能有更好的方法来构建逻辑,但这是与完成这项工作的示例相比的最小变化。
【讨论】:
if (!validated) {...} 块 - 我相信 OnApplicationEndRequest() 方法会“处理”这一点。
要在每个控制器或每个方法的基础上选择性地启用基本身份验证,您可以从AuthorizeAttribute 派生,如this question 中所述。
【讨论】: