加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-web-api – 带有json有效负载中令牌的WebApi授权过滤器

发布时间:2020-12-16 06:24:39 所属栏目:asp.Net 来源:网络整理
导读:我一直在研究使用AspNetWebApi进行授权,有关该主题的信息有点稀疏. 我有以下选择: 在查询字符串上传递API令牌 将API令牌作为标头传递 使用Basic Auth传递API令牌 将API令牌传递到json中的请求有效内容. 通常推荐哪种方法? 我也想知道第4点),我将如何检查Au
我一直在研究使用AspNetWebApi进行授权,有关该主题的信息有点稀疏.

我有以下选择:

>在查询字符串上传递API令牌
>将API令牌作为标头传递
>使用Basic Auth传递API令牌
>将API令牌传递到json中的请求有效内容.

通常推荐哪种方法?

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

解决方法

如果您想要一个真正安全的授权选项,那么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;
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读