If a token obtained during authentication, We can store it in a service that’s injected into your classes. Following example illustrates how to access token in a service file.
public class UserService
{
private readonly IHttpContextAccessor _httpContextAccessor;
public UserService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public void SomeMethod()
{
var accessToken = _httpContextAccessor.HttpContext.Request.Headers["Authorization"]
}
}
Suppose If we receive token in the format of Bearer Your_Token and we want only token part then we can get it as follows
var parts = accessToken.ToString().Split(‘ ‘);
var token = parts[1]
If the Authorization header doesn’t start with Bearer, we should handle it appropriately based on our application’s requirements.