【问题标题】:How to add Authentication to ASP .NET Web API with exising users?如何使用现有用户向 ASP .NET Web API 添加身份验证?
【发布时间】:2014-09-15 09:43:12
【问题描述】:
  • 我将用户存储在我们自己的自定义数据库中。
  • 我开发了一个 ASP .NET Web 2 API
  • 我没有现有的网站,并且客户端没有使用浏览器(因此无法使用表单身份验证)
  • 我需要使用现有用户,所以不能使用使用它自己的表的 ASP .NET 的身份?

如何最好地将身份验证添加到我的 API?我想利用现有的基础设施,例如 Authorize 属性。

(这个问题:User Authentication in ASP.NET Web API 没有回答我的问题,因为它提出的唯一两种身份验证方式是表单身份验证和 Windows 集成身份验证——我都不能使用)。

【问题讨论】:

  • 您可以根据任何条件在 web-api 上设置 Authorize,但是如果您没有浏览器,您打算如何保留身份验证,需要发送 cookie 或 ouath 令牌以便 api 知道请求是否合法且已授权?
  • 我没有浏览器,但它是 HTTP,因此我可以在标头中包含令牌,即使我没有使用 HTTP,我也可以将它包含在我的请求中。
  • 更容易将它发送的 cookie 包含在标头中,除非您知道如何配置 Ouath ?但是没有浏览器嗯 ouath 可能是你唯一的选择
  • 使用 // 做一些条件检查然后设置 FormsAuthentication.SetAuthCookie(userAccount, true); // 如果您不想创建持久 cookie,则设置为 false,如果您在标头中包含 cookie,它应该可以工作

标签: c# authentication asp.net-web-api .net-4.5


【解决方案1】:

我喜欢在消息处理程序中使用自定义身份验证机制。由于我不知道有关安全级别的要求,因此无法说出您应该使用哪种机制。如果您使用 SSL,那么 basic authentication 就足够了。

使用自定义用户存储进行基本身份验证的简单处理程序如下所示:

public class BasicAuthMessageHandler : DelegatingHandler
{
    private const string ResponseHeader = "WWW-Authenticate";
    private const string ResponseHeaderValue = "Basic";

    protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        AuthenticationHeaderValue authValue = request.Headers.Authorization;
        if (authValue != null && !String.IsNullOrWhiteSpace(authValue.Parameter))
        {
            Credentials parsedCredentials = ParseAuthorizationHeader(authValue.Parameter);
            if (parsedCredentials != null)
            {
                //Here check the provided credentials against your custom user store
                if(parsedCredentials.Username == "Username" && parsedCredentials.Password == "Pass") 
                {
                    Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(parsedCredentials.Username), null);
                }
            }
        }
        return base.SendAsync(request, cancellationToken)
           .ContinueWith(task =>
           {
               var response = task.Result;
               if (response.StatusCode == HttpStatusCode.Unauthorized
                   && !response.Headers.Contains(ResponseHeader))
               {
                   response.Headers.Add(ResponseHeader, ResponseHeaderValue);
               }
               return response;
           });
    }

    private Credentials ParseAuthorizationHeader(string authHeader)
    {
        string[] credentials = Encoding.ASCII.GetString(Convert
                                                        .FromBase64String(authHeader))
                                                        .Split(
                                                        new[] { ':' });
        return new Credentials()
                   {
                       Username = credentials[0],
                       Password = credentials[1],
                   };
    }
}

public class Credentials
{
    public string Username {get;set;}
    public string Password {get;set;}
}

然后在全局应用配置中应用消息处理程序

protected void Application_Start()
    {
        GlobalConfiguration.Configuration.MessageHandlers
          .Add(new BasicAuthMessageHandler());
    }

请注意,提供的示例只是一个示例。

【讨论】:

    猜你喜欢
    • 2018-06-30
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    相关资源
    最近更新 更多