具有json有效负载中的令牌的Web Api授权过滤器

时间:2012-05-03 15:19:47

标签: asp.net-web-api

我一直在研究使用AspNetWebApi进行授权,而且有关该主题的信息有点稀疏。

我有以下选择:

  1. 在查询字符串上传递API令牌
  2. 将API令牌作为标题
  3. 传递
  4. 使用基本身份验证传递API令牌
  5. 将API令牌传递到json中的请求有效内容。
  6. 这通常是推荐的方法吗?

    我也想知道第4点),我将如何检查AuthorizationFilterAttribute上的OnAuthorization方法中的json有效负载,以检查API令牌是否正确?

1 个答案:

答案 0 :(得分:5)

如果您想要一个真正安全的授权选项,那么OAuth就是您的最佳选择。这个blog post使用现在过时的WCF Web API提供了一个非常全面的示例,但很多代码都是可以挽救的。或者至少,使用HTTP基本身份验证,如此blog post所示。正如Aliostad所说,如果您使用基本身份验证路由,请确保使用HTTPS,以便令牌保持安全。

如果您决定要自己推送(几乎总是比上面的任何一个选项都安全得多),那么下面是一个代码示例,说明如果您使用HTTP标头路由,您需要的AuthorizationHanlder。请注意,Web API类中处理UserPrinicipal的方式很可能会发生变化,因此此代码仅适用于第一个预览版本。你需要像这样输入AuthorizationHandler:

    GlobalConfiguration.Configuration.MessageHandlers.Add(new AuthenticationHandler());

标头令牌代码:

public class AuthenticationHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        var requestAuthTokenList = GetRequestAuthTokens(request);
        if (ValidAuthorization(requestAuthTokenList))
        {
            //TODO: implement a Prinicipal generator that works for you
            var principalHelper = GlobalConfiguration.Configuration
                .ServiceResolver
                    .GetService(typeof(IPrincipalHelper)) as IPrincipalHelper;

            request.Properties[HttpPropertyKeys.UserPrincipalKey] = 
                principalHelper.GetPrinicipal(request);

            return base.SendAsync(request, cancellationToken);
        }
        /*
        ** This will make the whole API protected by the API token.
        ** To only protect parts of the API then mark controllers/methods
        ** with the Authorize attribute and always return this:
        **
        ** return base.SendAsync(request, cancellationToken);
        */
        return Task<HttpResponseMessage>.Factory.StartNew(
            () => new HttpResponseMessage(HttpStatusCode.Unauthorized)
                {
                    Content = new StringContent("Authorization failed")
                });
    }

    private static bool ValidAuthorization(IEnumerable<string> requestAuthTokens)
    {
        //TODO: get your API from config or however makes sense for you
        var apiAuthorizationToken = "good token";
        var authorized = requestAuthTokens.Contains(apiAuthorizationToken);

        return authorized;
    }

    private static IEnumerable<string> GetRequestAuthTokens(HttpRequestMessage request)
    {
        IEnumerable<string> requestAuthTokens;
        if (!request.Headers.TryGetValues("SomeHeaderApiKey", out requestAuthTokens))
        {
            //Initialize list to contain a single not found token:
            requestAuthTokens = new[] {"No API token found"};
        }
        return requestAuthTokens;
    }
}
相关问题