如何才能最好地为我的API添加身份验证?我想利用现有的基础设施,例如Authorize
属性。
(这个问题:User Authentication in ASP.NET Web API没有回答我的问题,因为它提出的身份验证只有两种方式:表单身份验证和Windows集成身份验证 - 我都不能使用它。“
答案 0 :(得分: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());
}
请注意,提供的示例只是一个示例。