我正在使用MVC 4 Web Api,并且希望用户在使用我的服务之前进行身份验证。如何在Web API中使用Api密钥进行使用表单身份验证的服务身份验证
我已经实现了一个授权消息处理程序,工作得很好。
public class AuthorizationHandler : DelegatingHandler
{
private readonly AuthenticationService _authenticationService = new AuthenticationService();
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
IEnumerable<string> apiKeyHeaderValues = null;
if (request.Headers.TryGetValues("X-ApiKey", out apiKeyHeaderValues))
{
var apiKeyHeaderValue = apiKeyHeaderValues.First();
// ... your authentication logic here ...
var user = _authenticationService.GetUserByKey(new Guid(apiKeyHeaderValue));
if (user != null)
{
var userId = user.Id;
var userIdClaim = new Claim(ClaimTypes.SerialNumber, userId.ToString());
var identity = new ClaimsIdentity(new[] { userIdClaim }, "ApiKey");
var principal = new ClaimsPrincipal(identity);
Thread.CurrentPrincipal = principal;
}
}
return base.SendAsync(request, cancellationToken);
}
}
问题是,我使用表单身份验证。
[HttpPost]
public ActionResult Login(UserModel model)
{
if (ModelState.IsValid)
{
var user = _authenticationService.Login(model);
if (user != null)
{
// Add the api key to the HttpResponse???
}
return View(model);
}
return View(model);
}
当我打电话给我的API:
[Authorize]
public class TestController : ApiController
{
public string GetLists()
{
return "Weee";
}
}
处理程序无法找到X-ApiKey头。
只要用户登录,是否有方法将用户的api密钥添加到http响应头并保留密钥? 是否有另一种实现此功能的方式?
谢谢!你是对的我的意思是表单身份验证。我编辑了我的问题。我没有使用成员资格提供程序,而是创建了自定义身份验证逻辑。 我不能使用HttpRequestMessage,因为我正在使用MVC控制器进行身份验证,并返回一个Action Result(或者我不知道如何使用它)。 – 2013-04-26 18:18:10