0

i am using web api mvc 5 and i am doing api call logging. Following is a snippet

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var corrId = string.Format("{0}{1}", DateTime.Now.Ticks, Thread.CurrentThread.ManagedThreadId);
        var requestInfo = string.Format("{0};{1}", request.Method, request.RequestUri);

        var requestMessage = await request.Content.ReadAsByteArrayAsync();

        await IncommingMessageAsync(corrId, requestInfo, requestMessage);

        var response = await base.SendAsync(request, cancellationToken);

        byte[] responseMessage;

        if (response.IsSuccessStatusCode)
            responseMessage = await response.Content.ReadAsByteArrayAsync();
        else
            responseMessage = Encoding.UTF8.GetBytes(response.ReasonPhrase);

        await OutgoingMessageAsync(corrId, requestInfo, responseMessage);

        return response;
    }

what i would like to know is how could i get the bearer token if the request is from an authenticated used. I tried HttpContext.Current.User but it's always null.

Thanks in advance.

user1144596
  • 1,986
  • 7
  • 29
  • 52

1 Answers1

1

Assuming your token is coming in the header as Authorization key then you can pull the bearer token from the header of the request:

 if (Request.Headers.Contains("Authorization"))
       var bearerToken = Request.Headers.GetValues("Authorization").FirstOrDefault();
Ben Hall
  • 1,173
  • 8
  • 17