Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AuthKeyFilter logic
public class AuthKeyFilter : ActionFilterAttribute
{
private readonly IdentityDbContext _context;
private readonly ILogger<AuthKeyFilter> _logger;
public AuthKeyFilter(IdentityDbContext context, ILogger<AuthKeyFilter> logger)
{
_context = context;
_logger = logger;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
var remoteIp = string.Empty;
try
{
remoteIp = context.HttpContext.Connection.RemoteIpAddress.ToString();
}
catch (SocketException socketException)
{
_logger.LogError("AuthKeyFilter: Error retrieving IP Address. Error: {@Exception}", socketException);
}
var authKeyQueryString = context.HttpContext.Request.Query["AuthKey"];
var authKeyHeader = context.HttpContext.Request.Headers["AuthKey"];
var authKey = (!authKeyHeader.IsEmpty() ? authKeyHeader.ToString() : authKeyQueryString.ToString()) ?? string.Empty;
if (authKey.IsNullOrWhiteSpace())
{
context.Result = new UnauthorizedResult();
return;
}
var authKeyUser = _context.Users.FirstOrDefault(x => x.ApiAuthKey == authKey);
if (authKeyUser == null)
{
_logger.LogWarning("AuthKeyFilter: Attempt to access {Path} denied by {IPAddress}. Tried using AuthKey: {AuthKey}",
context.HttpContext.Request.Path, remoteIp, authKey);
context.Result = new UnauthorizedResult();
return;
}
_logger.LogInformation("AuthKeyFilter: {Path} is being accessed by {AuthKeyUser} via {IpAddress}. Using AuthKey: {AuthKey}",
context.HttpContext.Request.Path, authKeyUser.UserName, remoteIp, authKey.Substring(0, 10));
base.OnActionExecuting(context);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment