【发布时间】:2014-07-31 22:44:36
【问题描述】:
我正在尝试创建一个 ASP.NET MVC API 授权过滤器,原因是我希望我的 API 同时使用会话登录和 API 密钥。
所以如果HttpContext.Current.User.Identity.IsAuthenticated 是真的,什么也不做。如果没有找到参数 API 密钥并验证它和仅针对此请求的用户。
我在下面尝试了以下操作,但是当我进入操作时,它被称为 HttpContext.Current.User.Identity.Name 只是空的,IsAuthenticated 是假的。
公共类 MyAccessFilter : ActionFilterAttribute, IAuthorizationFilter { 私有DatabaseEntities 数据库;
public MyAccessFilter()
{
database = new DatabaseEntities();
}
public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken,
Func<Task<HttpResponseMessage>> continuation)
{
// If the users is already authed is this a local call, user id should be set
if (HttpContext.Current.User.Identity.IsAuthenticated)
return continuation();
// Find the api key and log in with it
IEnumerable<string> apiKeyHeader;
if (!actionContext.Request.Headers.TryGetValues("apikey", out apiKeyHeader))
return failed();
if(apiKeyHeader.Count() != 1)
return failed();
string key = apiKeyHeader.First();
//var key = actionContext.ControllerContext.RouteData.Values["apikey"] as string;
if (String.IsNullOrWhiteSpace(key))
return failed();
var userid = (from f in database.Users where f.ApiKey == key select f.Id).FirstOrDefault();
if (userid == 0)
{
return failed();
}
var usernameClaim = new Claim(ClaimTypes.Name, userid.ToString());
var identity = new ClaimsIdentity(new[] { usernameClaim }, "ApiKey");
var principal = new ClaimsPrincipal(identity);
Thread.CurrentPrincipal = principal;
return continuation();
}
private Task<HttpResponseMessage> failed()
{
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
tcs.SetResult(new HttpResponseMessage(HttpStatusCode.Unauthorized));
return tcs.Task;
}
}
【问题讨论】:
标签: asp.net-mvc-4 asp.net-web-api