public async Task Invoke(HttpContext context) { logger.LogInformation($"{context.Request.Path}\tRECEIVED"); var sw = new Stopwatch(); sw.Start(); var crumb = new Breadcrumb("LoggerMiddleware"); crumb.Message = $"{context.Request.Method} {context.Request.Path}{context.Request.QueryString.ToUriComponent()}"; crumb.Data = new Dictionary <string, string>() { { "IsAuthenticated", context.User.Identity.IsAuthenticated.ToString() }, { "Authentication", context.User.Identity.IsAuthenticated ? context.User.Identity.Name : "Unknown" } }; raven.AddTrail(crumb); try { await _next.Invoke(context); } catch (Exception e) { //Log exception with RavenClient await raven.CaptureNetCoreEventAsync(e); } sw.Stop(); logger.LogInformation($"{context.Request.Path}\t{sw.Elapsed.TotalMilliseconds}(ms)"); }
public async Task Invoke(HttpContext context) { try { logger.LogInformation($"{context.Request.Path}\tRECEIVED"); var sw = new Stopwatch(); sw.Start(); //Log activty through Sentry Breadcrumb var crumb = new Breadcrumb("LoggerMiddleware"); crumb.Message = $"{context.Request.Method} {context.Request.Path}{context.Request.QueryString.ToUriComponent()}"; crumb.Data = new Dictionary <string, string>() { { "IsAuthenticated", context.User.Identity.IsAuthenticated.ToString() }, { "Authentication", context.User.Identity.IsAuthenticated ? context.User.Identity.Name : "Unknown" } }; raven.AddTrail(crumb); //Log activty through API var activity = new LoggingActivityModel() { IP = context.Connection.RemoteIpAddress == null ? "N/A" : context.Connection.RemoteIpAddress.ToString(), User = (context.User.Identity.IsAuthenticated == false) ? "Guest" : context.User.FindFirst(ClaimTypes.Name).Value, Request = context.Request.Path }; AppTask.Forget(() => appLogging.LogActivity(activity)); //Start processing the request try { await _next.Invoke(context); } catch (Exception e) { //Allow Postgres to receive querystring var feature = new LoggerFeature() { Path = context.Request.Path + context.Request.QueryString.ToString() }; context.Features.Set <LoggerFeature>(feature); //Try to send the request to Sentry await raven.CaptureNetCoreEventAsync(e); //rethrow so we can redirect to Error page throw e; } //Stop request timing and output time sw.Stop(); logger.LogInformation($"{context.Request.Path}\t{sw.Elapsed.TotalMilliseconds}(ms)"); } catch (Exception e) { //Try to send the request to Sentry await raven.CaptureNetCoreEventAsync(e); } }
public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next) { var bindingCrumb = new Breadcrumb("ModelBinderBreadcrumb"); bindingCrumb.Level = BreadcrumbLevel.Info; bindingCrumb.Data = new Dictionary <string, string>(); bindingCrumb.Data.Add("QueryString", context.HttpContext.Request.QueryString.ToUriComponent()); raven.AddTrail(bindingCrumb); await next(); var bindingAfterCrumb = new Breadcrumb("ModelBinderBreadcrumb"); bindingCrumb.Level = BreadcrumbLevel.Info; bindingCrumb.Data = new Dictionary <string, string>(); bindingCrumb.Data.Add("ModelState", context.ModelState.IsValid.ToString()); raven.AddTrail(bindingAfterCrumb); }
//Should not be used on the FE, this is for backend JWT generation public string GenerateToken(Claim[] claims) { //Add breadcrumb for Raven error monitoring var crumb = new Breadcrumb("AliseeksJwtAuthentication"); crumb.Message = "Creating jwt token"; raven.AddTrail(crumb); var securityKey = System.Text.Encoding.ASCII.GetBytes(jwtOptions.SecretKey); var handler = new JwtSecurityTokenHandler(); var now = DateTime.UtcNow; var tokenDescriptor = new SecurityTokenDescriptor() { Subject = new ClaimsIdentity(claims), Issuer = "AliseeksIssuer", Audience = "AliseeksUser", Expires = DateTime.Now.AddDays(14), NotBefore = now, IssuedAt = now, SigningCredentials = new SigningCredentials( new SymmetricSecurityKey(securityKey), SecurityAlgorithms.HmacSha256) }; try { var token = handler.CreateToken(tokenDescriptor); var tokenString = handler.WriteToken(token); return(tokenString); } catch (Exception e) { //Blocking I/O raven.CaptureNetCoreEvent(e).Wait(); //Throw for whatever service is calling it throw e; } }
public AuthenticationTicket Unprotect(string protectedText, string purpose) { var handler = new JwtSecurityTokenHandler(); ClaimsPrincipal principal = null; SecurityToken validToken = null; try { //Add breadcrumb for Sentry error monitoring var crumb = new Breadcrumb("AliseeksJwtCookieAuthentication"); crumb.Message = "Attempting to validate JWT token"; crumb.Data = new Dictionary <string, string>() { { "ValidationParameters", JsonConvert.SerializeObject(this.validationParameters) }, { "ProtectedText", protectedText } }; raven.AddTrail(crumb); principal = handler.ValidateToken(protectedText, this.validationParameters, out validToken); var validJwt = validToken as JwtSecurityToken; if (validJwt == null) { throw new ArgumentException("Invalid JWT"); } if (!validJwt.Header.Alg.Equals(algorithm, StringComparison.Ordinal)) { throw new ArgumentException($"Algorithm must be {algorithm}"); } //Append token value to identity var tokenClaim = new Claim[] { new Claim("Token", protectedText) }; principal.AddIdentity(new ClaimsIdentity(tokenClaim)); return(new AuthenticationTicket(principal, new Microsoft.AspNetCore.Http.Authentication.AuthenticationProperties() { }, "AliseeksCookie")); } catch (SecurityTokenValidationException e) { //Blocking I/O raven.CaptureNetCoreEvent(e).Wait(); return(null); } catch (ArgumentException e) { //Blocking I/O raven.CaptureNetCoreEvent(e).Wait(); return(null); } catch (Exception e) { //Blocking I/O raven.CaptureNetCoreEvent(e).Wait(); return(null); } }
//Function that actually goes out and gets Aliexpress search and converts it async Task <SearchResultOverview> searchItems(SearchServiceModel search) { var resultTasks = new List <Task <string> >(); SearchResultOverview results = null; foreach (var page in search.Pages) { search.Page = page; string endpoint = new AliexpressQueryString().Convert(search); #region Error Tracking //Add breadcrumb for error monitoring var crumb = new Breadcrumb("AliexpressService") { Message = $"GET {endpoint}", Data = new Dictionary <string, string>() { { "Aliexpress URL", endpoint } } }; raven.AddTrail(crumb); #endregion try { resultTasks.Add((await http.Get(endpoint)).Content.ReadAsStringAsync()); } catch (Exception e) { var sentry = new SentryEvent(e); await raven.CaptureNetCoreEventAsync(sentry); } } var responses = await Task.WhenAll(resultTasks); foreach (var response in responses) { try { var result = new AliexpressPageDecoder().ScrapeSearchResults(response); if (results == null) { results = result; this.ServiceModel.PopulateState(results); } else { results.Items.AddRange(result.Items); } } catch (Exception e) { var sentry = new SentryEvent(e); await raven.CaptureNetCoreEventAsync(sentry); } } if (results != null && results.Items.Count > 0) { StoreSearchItems(results.Items); } return((results != null) ? results : new SearchResultOverview()); }