ASP Core: How to set httpContext.User?

Alexey Maslovski picture Alexey Maslovski · Oct 7, 2016 · Viewed 8.5k times · Source

I writing middleware for authentication with tokens. (don't ask me: "why?").

...
private UserManager<ApplicationUser> userManager;
private RequestDelegate next;
private WareHouseDbContext context; 
...
public async Task Invoke(HttpContext httpContext)
{
    var header = httpContext.Request.Headers.Where(x => x.Key == "Authorization");
    if (header.Count() == 1)
    {
        var token = header.First().Value.First();
        if (token.Contains("Bearer"))
        {
            var name = TokenEncryptor.Decrypt(token.Replace("Bearer ", ""));
            var user = context.Users.FirstOrDefault(x => x.UserName == name);

            if (user != null)
            {
                httpContext.User = user; // ???? how do this  ???/
            }
        }
    }           
    await next.Invoke(httpContext);
}

Please answer me how to set httpContext.User?

Answer

user495093 picture user495093 · Jun 19, 2017

you must create IPrincipal object like this

var user = new GenericPrincipal(new ClaimsIdentity(userData.Username), userData.Roles);
httpContext.User = user;