Skip to content

Instantly share code, notes, and snippets.

@ajtatum
Created November 17, 2020 03:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajtatum/fc27d826df33f9ef261a1ce562a4356e to your computer and use it in GitHub Desktop.
Save ajtatum/fc27d826df33f9ef261a1ce562a4356e to your computer and use it in GitHub Desktop.
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