public static async Task ValidateApiKey(ApiKeyValidateIdentityContext context, String schema = null) { var dbContext = ServiceLocator.Current.GetService <IDbContext>(); var host = ServiceLocator.Current.GetService <IApplicationHost>(); schema = schema ?? "a2security"; var findUsersql = $"[{schema}].[FindApiUserByApiKey]"; var writeLogSql = $"[{schema}].[WriteLog]"; var prms = new ExpandoObject(); prms.Set("Host", context.Host); prms.Set("ApiKey", context.ApiKey); var user = await dbContext.LoadAsync <ApiAppUser>(host.CatalogDataSource, findUsersql, prms); if (user != null) { if (IdentityHelpers.IsValidIPAddress(user.AllowIP, context.Host)) { context.Claims = CreateClaims(user); context.IsValidated = true; } else { var fo = new ExpandoObject(); fo.Set("UserId", user.Id); fo.Set("SeverityChar", "W"); fo.Set("Code", 66 /*Api IP forbidden*/); fo.Set("Message", $"expected: '{user.AllowIP}', actual:'{context.Host}'"); await dbContext.ExecuteExpandoAsync(host.CatalogDataSource, writeLogSql, fo); } } }
public virtual async Task ValidateIdentity(ApiKeyValidateIdentityContext context) { if (OnValidateIdentity == null) { throw new ArgumentNullException(nameof(OnValidateIdentity)); } await OnValidateIdentity(context); }
protected override async Task <AuthenticationTicket> AuthenticateCoreAsync() { const String API_KEY = "ApiKey"; String apiKey = null; String header = Request.Headers.Get("Authorization"); if (!String.IsNullOrEmpty(header)) { if (header.StartsWith(API_KEY, StringComparison.OrdinalIgnoreCase)) { apiKey = header.Substring(API_KEY.Length).Trim(); } } else { header = Request.Headers.Get("X-API-Key"); if (!String.IsNullOrEmpty(header)) { apiKey = header; } } if (apiKey == null) { return(null); } var context = new ApiKeyValidateIdentityContext(Context, Options, apiKey, Request.RemoteIpAddress); await Options.Provider.ValidateIdentity(context); if (context.IsValidated) { Response.Headers.Append("WWW-Authenticate", API_KEY); var claims = new List <Claim> { new Claim(ClaimTypes.AuthenticationMethod, context.Options.AuthenticationType) }; foreach (var cl in context.Claims) { claims.Add(cl); } var identity = new ClaimsIdentity(context.Claims, this.Options.AuthenticationType); return(new AuthenticationTicket(identity, new AuthenticationProperties() { IssuedUtc = DateTime.UtcNow })); } return(Fail()); }