how to share the token between classes

78 views Asked by At

I have having a design issue with asp.net web-api and would like to know how to solve this problem

public abstract class BaseApiController<TEntity> : ApiController where TEntity : Entity
{

    protected string GetUsername()
    {
        return Utilities.GetUsername(Request.Headers.Authorization);
    }

     //some other code

 }

public class StakeholderApiController : BaseApiController<Stakeholders>
{
      ILogger _logger = new CustomApiLogger("StkhManager", GetUsername())

     //some other code

}

now the problem I have is:

I have the BaseApiController which I am using the share certain functionality between all ApiControllers.

And then I have some specified ApiController for certain not shared functionality.

Now while doing logging, I do want to log the logged in user's name, the problem is I have to pass it everytime I create a new instance, is there a way I can make the logged in user's name global for the current api request so that it can be accessed everywhere.

I cannot make it static, otherwise for others request it will give wrong username.

is there a way I can avoid passing it everytime. Given that webapi is stateless, so session cant be used, is there anyother way??

I am using angularjs front end, hence I am NOT using any authorization technique provided by MVC/.net

Note:

  1. I cannot move creation of Logger to base class for certain reasons

  2. This is just one example, I want to use the logged in user's name in many other place. Hence dont want to pass it around.

1

There are 1 answers

2
Badrinarayanan Lakshmiraghavan On BEST ANSWER

There is a standard pattern in setting and accessing principal with ASP.NET Web API. From an ApiController such as your BaseApiController, you can just use the User property to retrieve the same. To set it, typically, the HttpRequestContext is obtained from the request object and the principal is set like so.

Request.GetRequestContext().Principal = new ClaimsPrincipal(...);

BTW, you can access the current request object in the Web API pipeline pretty much from anywhere.