.NET Web API 2 OWIN Bearer Token Authentication direct call

前端 未结 4 1879
天命终不由人
天命终不由人 2020-12-30 12:46

I have a problem with my Web Api Project. I have files stored in my Database and want to call them directly in a new window to view/save (URL like : /api/Files/5 - 5 beeing

4条回答
  •  别那么骄傲
    2020-12-30 13:46

    Although I'm not sure it's a very good idea, you could implementing a DelegatingHandler to achieve what you are looking for.

    public class QueryStringBearerToken : DelegatingHandler
    {
        protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var bearerToken = request.GetQueryNameValuePairs()
                                     .Where(kvp => kvp.Key == "bearerToken")
                                     .Select(kvp => kvp.Value)
                                     .FirstOrDefault();
    
            if(!String.IsNullOrEmpty(bearerToken))
            {
                request.Headers.Add("Authorization", "Bearer " + bearerToken);
            }
            return base.SendAsync(request, cancellationToken);
        }
    }
    

    This handler will look for the query string named "bearerToken" and, if it exists, will add it to the request header for the subsequent handlers / filter to process. You might want to check first if the header is already present and not override in this case. You can add this handler in your configuration phase in the usual fashion:

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

    A request for /YourRoute?bearerToken=theToken will pass in the DelegatingHandler, adding the token passed in the query string to the list of headers in the original request and the regular Bearer Token authentication will look for the header and find it.

提交回复
热议问题