Get Access token from HttpContext in .NET Core

Get access token from HttpContext in NET Core

Today in this article, we will learn how to get access token from httpContext in .NET application. I wanted to read the token value from HttpContext.This access token from HTTP requests i wanted to use for authorized communication between clients and servers, enabling the API access control and allowing for stateless and scalable authentication mechanisms.

Below is a simple technique that I have used to get the access token from HttpContext.

Here I did use the same JWT Authentication in .NET Core technique to secure the method and then followed by another API to fetch the access token programmatically to pass it to other components as required.

As explained, the below piece of code is from the same sample which we learned in the JWT Authentication article,

Sample code how JWT authentication was configured in my code,

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddJwtBearer(options =>
                    {
                        options.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateIssuer = true,
                            ValidateAudience = true,
                            ValidateLifetime = true,
                            ValidateIssuerSigningKey = true,
                            ValidIssuer = Configuration["JwtToken:Issuer"],
                            ValidAudience = Configuration["JwtToken:Issuer"],
                            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtToken:SecuredKey"]))
                        };
                    });
        }

I was able to read JWT tokens using HttContext using a few of the below approaches.

Get Access token using HttpContext – Identity tokens Access

Access tokens enable clients to securely call protected web APIs and help perform authentication and authorization while providing access to the requested resources.

In the below example, we have used “access_token” to access the JWT Bearer token.

Here in the Controller method to fetch the token,

        [HttpGet]
        [Authorize]
        [Route("token")]
        public async Task<string> GetToken()
        {
           var accessToken = await 
           HttpContext.GetTokenAsync("access_token");
           return accessToken.ToString();
        }

Here is JWT Bearer token passed through the HTTP request used,

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJleHAiOjE1Njk4MTU5OTgsImlzcyI6Imh0dHBzOi8vbG9jYWxob3N0OjQ0Mzc4IiwiYXVkIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NDQzNzgifQ.
GTRD1V1q-XZNNC1aw596JnmhyAqaMoNumRX3ZXHs6gk

Here is how we can read the above token as below in the method,

read token from HttpContext in NET Core

Using HTTPContextAccessor to extract the Authorization header

If you need to access authentication headers or any HttpContext metadata in custom components or services or modules then please use HTTPContextAccessor as below,

 class EmployeeRepository : IEmployeeRepository
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public EmployeeRepository( IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
       
        public void GetEmployeeByID(int employeeID)
        {
            string header = _httpContextAccessor.HttpContext.Request.Headers["your auth header key"];
            PerformBusinessLogic(header);
        }
..
..
..
   }

To use the above option please register IHttpContextAccessor in ConfigServices() using code,

services.AddHttpContextAccessor();

Using Middleware to extract Authorization header

One can use Custom or Inline middleware also to read the HTTPContext details.

If you want to access HttpContext with the intention of doing more meaningful stuff then the Adding Custom Middleware ASP.NET Core approach is preferable.

Example: Custom Middleware

read auth headers in ASPNET Core

That’s all, Finally, we found it is very simple to read access tokens from HttpContext in .NET Core.

Summary

In this article, we learned various techniques for accessing token HTTP requests. Accessing access tokens from HTTP requests in .NET ensures secure and authorized communication between clients and servers, enables API access control, and allows for stateless and scalable authentication mechanisms

References

Happy Coding!!

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



4 thoughts on “How to Get Access Token from HttpContext in .NET Core

  1. Thanks you ! But i need to access token in the my business layer not in the controller. Could you please tell me how to achieve that?
    Thanks in Advance.

    1. Hello Thang -Thanks for your query. Please use IHTTPContextAccessor interface for accessing the same. Above article has now those details. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *