Created
November 17, 2020 03:41
-
-
Save ajtatum/fc27d826df33f9ef261a1ce562a4356e to your computer and use it in GitHub Desktop.
AuthKeyFilter logic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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