【问题标题】:ASP.NET MVC API with WebForms带有 WebForms 的 ASP.NET MVC API
【发布时间】: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


    【解决方案1】:

    AuthorizeAttribute 派生并实现 OnAuthorization 方法。查看 more details

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-13
      • 2016-10-09
      • 2010-10-14
      • 2014-07-10
      • 2011-05-28
      • 2017-11-07
      相关资源
      最近更新 更多