authentication - Web api 中的基本身份验证

标签 authentication basic-authentication asp.net-web-api

我开始研究 Web Api,只想创建一个简单的基本身份验证。我想知道该怎么做?

我尝试使用给定的 MSDN 链接,但 MSDN 上没有给出分步教程。 http://www.asp.net/web-api/overview/security/basic-authentication

最佳答案

您提供的链接提供了您需要的大部分详细信息,我希望这可以填补空白。

注意:如果使用 Web.API 2,Microsoft 建议使用 authentication filters 采取不同的方法。 .

在您的服务器上设置 https

如果您需要真正的安全性,这一点非常重要,否则密码可能会被窥探方收集。如何执行此操作完全取决于您的设置,您不会详细说明,但如果您正在使用 Azure WebRole,那么有一个非常好的 step-by-step guide to setting up SSL来自微软。

这不是后续步骤所必需的,但应在发布代码之前完成。我首先提到它是因为这部分通常涉及让其他人参与(用于服务器配置的系统管理员、购买证书的财务等),并且最好给他们很多警告。

编写(或窃取)自定义 IHttpModule 来进行身份验证

这是一大块 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] 属性来阻止特定操作。通过在 Controller 类之前添加它来阻止整个 Controller 。

[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因此,如果您包含该 namespace ,您可能会得到令人困惑的结果。

此时你可以尝试一下 - 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 (您信任从网上下载的实现吗?),PBKDF2Crypto class (简单但不是非常安全)但微软可能有更好的东西,因为人们对正确存储密码存在很多担忧。

关于authentication - Web api 中的基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15899182/

相关文章:

git - 权限被拒绝(公钥)。致命的 : Could not read from remote repository

spring-security - Spring security,http basic 或 form 登录认证

c# - WebAPI 2 最佳实践 - 产品和类别

c# - 使用 OWIN 自托管 WebApi 声明身份验证

asp.net-web-api - 如何从 WEB API 响应中删除命名空间

iphone - 可以使用 native facebook 应用程序登录移动 html5 应用程序吗?在 iPhone 上

javascript - 如何正确地将管理员用户添加到数据库?

tomcat - 配置 ldap 身份验证后无法登录到 Tomcat 7 管理器应用程序

java - Axis2 (1.6.1) 客户端 Web 服务基本身份验证

ajax - 如何使用Ext.Ajax登录Spring Security?