Hello i have the next design problem:
Before accessing to my Controller i have a filter to check the authentication and the authorization so in order to do so i have to know the user. Until there everything is perfect, but the problem starts when i want to know the user who is log so i can do more things. Any ideas?
[AdministratorAuth("DogController")]
public class DogController : ControllerBase
{
[HttpGet]
public IAction GetDogsOfUser()
{
return Ok(dogLogic.GetDogsOfUser());
}
}
public class LoginAuth : Attribute, IActionFilter
{
public static Guid Token { get; private set; }
public void OnActionExecuted(ActionExecutedContext context)
{
}
public void OnActionExecuting(ActionExecutingContext context)
{
string headerToken = context.HttpContext.Request.Headers["Authorization"];
if (headerToken is null)
{
context.Result = new ContentResult()
{
Content = "Token is required",
};
} else
{
try
{
Guid token = Guid.Parse(headerToken);
VerifyToken(token, context);
Token = token;
} catch (FormatException)
{
context.Result = new ContentResult()
{
Content = "Invalid Token format",
};
}
}
}
private void VerifyToken(Guid token, ActionExecutingContext context)
{
using (var sessions = GetSessionLogic(context))
{
if (!sessions.IsValidToken(token))
{
context.Result = new ContentResult()
{
Content = "Invalid Token",
};
}
}
}
private ISessionLogic GetSessionLogic(ActionExecutingContext context)
{
var typeOfSessionsLogic = typeof(ISessionLogic);
return context.HttpContext.RequestServices.GetService(typeOfSessionsLogic) as ISessionLogic;
}
}
public class AdministratorAuth : LoginAuth
{
private readonly string permission;
public AdministratorAuth(string permission)
{
this.permission = permission;
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
public void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
string headerToken = context.HttpContext.Request.Headers["Authorization"];
Guid token = Guid.Parse(headerToken);
using (var sessions = GetSessionLogic(context))
{
if (!sessions.HasLevel(token, permission))
{
context.Result = new ContentResult()
{
Content = "The user hasn't the permission to access " + permission,
};
}
}
}
private ISessionLogic GetSessionLogic(ActionExecutingContext context)
{
var typeOfSessionsLogic = typeof(ISessionLogic);
return context.HttpContext.RequestServices.GetService(typeOfSessionsLogic) as ISessionLogic;
}
}
So let's imagine that i have this, if i want to know the dogs of the user who is log, how can i do?
You can simply use Nlog or log4net function,
or
create a model which contains
Logged = DateTime.Now,
LoginHost = Request.Host.ToString(),
LoginIP = Request.HttpContext.Connection.LocalIpAddress.ToString(),
SessionId = Request.HttpContext.Session.Id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.