How inject user object from startup class to controller constructor based on cookie value

Viewed 650

I'm using CookieAuthentication to achieve custom login,

app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
    AuthenticationScheme = "MyCookieMiddlewareInstance",
    LoginPath = new PathString("/Account/Unauthorized/"),
    AccessDeniedPath = new PathString("/Account/Forbidden/"),
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    CookieName="Id",
});

Each controller in my application is expecting an user object, which can be created using the secret id(CookieName="Id") present in the cookie. How can I create the user object by reading cookie and inject into the controller on each request.

I tried the following approach,

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    var sp = services.BuildServiceProvider();
    services.AddTransient<IUserContext, UserObject>(a => new UserObjectResolver(sp.GetService<IHttpContextAccessor>()).GetUserObject());
}

But here the IHttpContextAccessor seems to be always null on arrival of request.

1 Answers
Related