Adding a bearer token for a custom request in the Web Api

I am using telogis third party library names in my project. For one of its features called Clustering, it is not possible to send a request header. Only the query string can be passed for clustering and all the API calling logic is done in the JS library.

My project uses bearer token authentication and is built with Web API 2. To solve this problem, I passed the access token in the query string and want to validate the request. I created below CustomAuthorize attribute for this:

public class ClusterRequestAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            base.OnAuthorization(actionContext);
        }

        public override Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
        {
            string accessToken = actionContext.Request.GetQueryNameValuePairs().Where(w => w.Key == "access_token").Select(w => w.Value).DefaultIfEmpty().FirstOrDefault();
            actionContext.Request.Headers.Remove("Authorization");
            actionContext.Request.Headers.Add("Authorization", accessToken);

            actionContext.ControllerContext.Request.Headers.Remove("Authorization");
            actionContext.ControllerContext.Request.Headers.Add("Authorization", accessToken);

            HttpContext.Current.Request.Headers.Remove("Authorization");
            HttpContext.Current.Request.Headers.Add("Authorization", accessToken);

            return base.OnAuthorizationAsync(actionContext, cancellationToken);
        }

        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            return base.IsAuthorized(actionContext);
        }
    }

      

But it IsAuthorized

always returns false. I have covered the internal Authorize API function using Git Link

According to this, I need to install actionContext.ControllerContext.RequestContext.Header

which is inaccessible due to the protection level as it is marked as internal

.

Is there any other work for this problem, or could it be better done?

+3


source to share





All Articles