Search code examples
c#asp.net-coreserenity-platform

How to keep track of consumed JWT by my API


my controller method consumes a JWT token which was enabled in ConfigureServices method in Startup.cs

.AddJwtBearer(options => { // some code }; });

The CreateUser() action in UserController consumes this token

[HttpPost, Authorize("JWT")]

public SaveResponse CreateUser(IUnitOfWork uow, UserRequest request) {

return new UserRepository().Create(uow, request);

}

The problem is as follows: A few methods deeper upon creating a new user, there's a method HasPermission() that checks logged in user's Administration permissions. However, in this particular case using JWT, there's no logged in user. The presence of valid JWT suffices. I am going to modify this HasPermission() in a way, that it also accepts JWT.

At CreateUser method level, the JWT is present inside HttpRequest's 'Authorization' header.

The question is - How can I deliver this JWT token to like a 8th method in a chain of methods executed by UserRepository().Create(uow, request) ? Is there a way to pull this off without modifying parameters of these methods?

thank you


Solution

  • If you use DI to instantiate service dependecies you can register IHttpContextAccessor via services.AddHttpContextAccessor() and use it to get information about request:

    public SomeService(IHttpContextAccessor contextAccessor)
    {
        _contextAccessor = contextAccessor;
    }
    
    public void SomeServiceMethod()
    {
        var auth = _contextAccessor.HttpContext.Request.Headers[HeaderNames.Authorization].ToString(); // possibly will need to remove scheme from the header
    }