This commit is contained in:
2020-05-08 22:36:53 +00:00
parent e30db21b57
commit 94bb06e249
4 changed files with 39 additions and 9 deletions

View File

@@ -360,30 +360,56 @@ namespace AyaNova
app.UseAuthorization();
//Custom middleware to get user roles and put them into the request so
//Custom middleware to ensure token still valid and to
//get user roles and put them into the request so
//they can be authorized in routes.
app.Use(async (context, next) =>
{
if (!context.User.Identity.IsAuthenticated)
{
context.Request.HttpContext.Items["AY_ROLES"] = 0;
await next.Invoke();
}
else
{
//Get user ID from claims
long userId = Convert.ToInt64(context.User.FindFirst(c => c.Type == "id").Value);
//Get JWT
string JWT = string.Empty;
var AuthHeaders = context.Request.Headers[Microsoft.Net.Http.Headers.HeaderNames.Authorization];
foreach (String s in AuthHeaders)
{
if (s.ToLowerInvariant().Contains("bearer"))
{
JWT = s;
break;
}
}
//Get the database context
var ct = context.RequestServices.GetService<AyContext>();
var ct = context.RequestServices.GetService<AyContext>();
//get the user record
var u = await ct.User.AsNoTracking().Where(a => a.Id == userId).Select(m => new { roles = m.Roles, name = m.Name, id = m.Id, translationId = m.UserOptions.TranslationId }).FirstAsync();
var u = await ct.User.AsNoTracking().Where(a => a.Id == userId).Select(m => new { roles = m.Roles, name = m.Name, id = m.Id, translationId = m.UserOptions.TranslationId, currentAuthToken = m.CurrentAuthToken }).FirstAsync();
context.Request.HttpContext.Items["AY_ROLES"] = u.roles;
context.Request.HttpContext.Items["AY_USERNAME"] = u.name;
context.Request.HttpContext.Items["AY_USER_ID"] = u.id;
context.Request.HttpContext.Items["AY_TRANSLATION_ID"] = u.translationId;
//CHECK JWT
if (u.currentAuthToken != JWT)
{
context.Response.StatusCode = 401;
context.Response.Headers.Add("X-AyaNova-Authorization-Error", "Authorization token was replaced by more recent login");
await context.Response.WriteAsync("Authorization token was replaced by more recent login");
}
else
{
await next.Invoke();
}
}
await next.Invoke();
});
#endregion