DelegatingHandler添加授权令牌以进行请求

时间:2015-09-16 10:47:14

标签: asp.net angularjs asp.net-web-api oauth bearer-token

为了下载文件,我需要使用GET:/ API / File / ID?bearerToken = XYZ ...方法。

我已经创建了一个DelegatingHandler来将我的令牌添加到AuthorizationHeader,但似乎可以在此之前完成令牌验证......

Angular添加的当前所有标记在请求之前将标记添加到HTTP标头。

public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();
        ConfigureOAuth(app);
        WebApiConfig.Register(config);
        GlobalFilters.Add(config);
        app.UseWebApi(config);

        config.MessageHandlers.Insert(0, new QueryStringBearerToken());
    }

...

public class QueryStringBearerToken : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            var bearerToken = request.GetQueryNameValuePairs().
                Where(kvp => kvp.Key == "bearertoken")
                .Select(kvp => kvp.Value)
                .FirstOrDefault();

            //QueryString exists and Header doesn't
            if (!string.IsNullOrWhiteSpace(bearerToken) && !request.Headers.Any(x=>x.Key == "Authorization")) 
            {
                request.Headers.Add("Authorization", "Bearer " + bearerToken);
            }

            return base.SendAsync(request, cancellationToken);
        }
    }

1 个答案:

答案 0 :(得分:2)

我认为您使用的是Katana的Bearer中间件? (通过致电ConfigureAuth判断?)

如果是这样,Katana中间件确实会在Web API处理程序之前运行,并在它甚至有机会被处理程序处理之前拒绝您的请求。

您应该将功能移至Katana中间件,而不是创建处理程序。

以下是一个例子:

public class QueryBearerMiddleware : OwinMiddleware
{
    public QueryBearerMiddleware(OwinMiddleware next)
        : base(next)
    {
    }

    public override async Task Invoke(IOwinContext context)
    {
        string bearerToken = null;
        if (context.Request.QueryString.HasValue)
        {
            var queryPairs = context.Request.QueryString.ToUriComponent()
                .Substring(1)
                .Split(new [] {'&'}, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Split('=')).ToDictionary(x => x[0], x => x[1]);
            if (queryPairs.ContainsKey("bearertoken"))
            {
                bearerToken = queryPairs["bearertoken"];
            }
        }

        //QueryString exists and Header doesn't
        if (!string.IsNullOrWhiteSpace(bearerToken) && context.Request.Headers.All(x => x.Key != "Authorization"))
        {
            context.Request.Headers.Add("Authorization", new [] { "Bearer " + bearerToken });
        }

        await Next.Invoke(context);
    }
}

您应该注册此中间件,以便在承载中间件之前运行

在您ConfigureAuth的某个地方,您应该致电app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());。我们刚创建的这个新中间件应该在之前注册,即:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.Use(typeof(QueryBearerMiddleware));
        var config = new HttpConfiguration();
        ConfigureOAuth(app);
        WebApiConfig.Register(config);
        GlobalFilters.Add(config);
        app.UseWebApi(config);
    }
}