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?
you must create IPrincipal
object like this
var user = new GenericPrincipal(new ClaimsIdentity(userData.Username), userData.Roles);
httpContext.User = user;