protected override void OnPreRender(IDotvvmRequestContext context) { var authorized = false; #if OWIN var options = (StackExchange.Profiling.MiniProfiler.Current?.Options ?? StackExchange.Profiling.MiniProfiler.DefaultOptions) as MiniProfilerOptions; authorized = options?.ResultsAuthorize?.Invoke(HttpContext.Current.Request) ?? false; #else var options = (StackExchange.Profiling.MiniProfiler.Current?.Options ?? StackExchange.Profiling.MiniProfiler.DefaultOptions) as MiniProfilerOptions; if (options != null) { authorized = options.ResultsAuthorize?.Invoke(context.GetAspNetCoreContext().Request) ?? false; if (options.ResultsAuthorize == null && options.ResultsAuthorizeAsync is object) { // TODO: REVIEW whether this usage is correctly implemented authorized = Task.Run(async() => { return(await options.ResultsAuthorizeAsync(context.GetAspNetCoreContext().Request).ConfigureAwait(false)); }).GetAwaiter().GetResult(); } } #endif if (authorized) { var javascript = MiniProfilerJavascriptResourceManager.GetWigetInlineJavascriptContent(); context.ResourceManager.AddStartupScript("DotVVM-MiniProfiler-Integration", javascript, "dotvvm"); } base.OnPreRender(context); }
protected override void RenderControl(IHtmlWriter writer, IDotvvmRequestContext context) { writer.WriteUnencodedText(ClientTimingHelper.InitScript); if (StackExchange.Profiling.MiniProfiler.Current is object) { #if AspNetCore var html = StackExchange.Profiling.MiniProfiler.Current.RenderIncludes( context.GetAspNetCoreContext(), position: Position, showTrivial: ShowTrivial, showTimeWithChildren: ShowTimeWithChildren, maxTracesToShow: MaxTraces, showControls: ShowControls, startHidden: StartHidden); #else var html = StackExchange.Profiling.MiniProfiler.Current.RenderIncludes( position: Position, showTrivial: ShowTrivial, showTimeWithChildren: ShowTimeWithChildren, maxTracesToShow: MaxTraces, showControls: ShowControls, startHidden: StartHidden); #endif writer.WriteUnencodedText(html.ToString()); } base.RenderControl(writer, context); }
private async Task Authorize(IDotvvmRequestContext context, object appliedOn) { if (!CanBeAuthorized(appliedOn ?? context.ViewModel)) { return; } var policy = await GetAuthorizationPolicy(context); if (policy == null) { return; } var coreContext = context.GetAspNetCoreContext(); if (policy.AuthenticationSchemes != null && policy.AuthenticationSchemes.Count > 0) { ClaimsPrincipal principal = null; foreach (var scheme in policy.AuthenticationSchemes) { var result = await coreContext.AuthenticateAsync(scheme); if (result.Succeeded && result.Principal != null) { principal = MergeUserPrincipal(principal, result.Principal); } } if (principal == null) { principal = new ClaimsPrincipal(new ClaimsIdentity()); } coreContext.User = principal; } if (IsAnonymousAllowed(appliedOn)) { return; } var authService = coreContext.RequestServices.GetRequiredService <IAuthorizationService>(); if (!(await authService.AuthorizeAsync(coreContext.User, context, policy)).Succeeded) { if (coreContext.User.Identity.IsAuthenticated) { await HandleUnauthorizedRequest(coreContext, policy); } else { await HandleUnauthenticatedRequest(coreContext, policy); } } }
protected override void RenderControl(IHtmlWriter writer, IDotvvmRequestContext context) { var html = StackExchange.Profiling.MiniProfiler.Current.RenderIncludes( context.GetAspNetCoreContext(), position: Position, showTrivial: ShowTrivial, showTimeWithChildren: ShowTimeWithChildren, maxTracesToShow: MaxTraces, showControls: ShowControls, startHidden: StartHidden); writer.WriteUnencodedText(html.ToString()); base.RenderControl(writer, context); }
private IAuthorizationPolicyProvider GetPolicyProvider(IDotvvmRequestContext context) => context.GetAspNetCoreContext().RequestServices.GetRequiredService <IAuthorizationPolicyProvider>();
private byte[] GetOrCreateSessionId(IDotvvmRequestContext context, bool canGenerate = true) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var originalHttpContext = context.GetAspNetCoreContext(); var sessionIdCookieName = GetSessionIdCookieName(context); if (string.IsNullOrWhiteSpace(sessionIdCookieName)) { throw new FormatException("Configured SessionIdCookieName is missing or empty."); } // Construct protector with purposes var protector = this.protectionProvider.CreateProtector(PURPOSE_SID); // Get cookie value var sidCookieValue = cookieManager.GetRequestCookie(originalHttpContext, sessionIdCookieName); if (!string.IsNullOrWhiteSpace(sidCookieValue)) { // Try to read from cookie try { var protectedSid = Convert.FromBase64String(sidCookieValue); var sid = protector.Unprotect(protectedSid); return(sid); } catch (Exception ex) { // Incorrect Base64 formatting of crypto protection error // Generate new one or thow error if can't if (!canGenerate) { throw new SecurityException("Value of the SessionID cookie is corrupted or has been tampered with.", ex); } // else suppress error and generate new SID } } // No SID - generate and protect new one if (canGenerate) { var rng = System.Security.Cryptography.RandomNumberGenerator.Create(); var sid = new byte[SID_LENGTH]; rng.GetBytes(sid); var protectedSid = protector.Protect(sid); // Save to cookie sidCookieValue = Convert.ToBase64String(protectedSid); cookieManager.AppendResponseCookie( originalHttpContext, sessionIdCookieName, // Configured cookie name sidCookieValue, // Base64-encoded SID value new CookieOptions { HttpOnly = true, // Don't allow client script access Secure = context.HttpContext.Request.IsHttps, // If request goes trough HTTPS, mark as secure only SameSite = SameSiteMode.Lax }); // Return newly generated SID return(sid); } else { throw new SecurityException("SessionID cookie is missing, so can't verify CSRF token."); } }
/// <summary> /// Gets the Authentication functionality available on the current request. /// </summary> /// <param name="context">The request context.</param> public static AuthenticationManager GetAuthentication(this IDotvvmRequestContext context) => context.GetAspNetCoreContext().Authentication;
public CancellationToken GetCancellationToken(IDotvvmRequestContext context) { return(context.GetAspNetCoreContext().RequestAborted); }
protected override void OnPreRender(IDotvvmRequestContext context) { var authorized = (StackExchange.Profiling.MiniProfiler.Current.Options as MiniProfilerOptions)?.ResultsAuthorize?.Invoke(context.GetAspNetCoreContext().Request) ?? false; if (authorized) { context.ResourceManager.AddStartupScript("DotVVM-MiniProfiler-Integration", @" (function() { var miniProfilerUpdate = function(arg) { if(arg.xhr && arg.xhr.getResponseHeader) { var jsonIds = arg.xhr.getResponseHeader('X-MiniProfiler-Ids'); if (jsonIds) { var ids = JSON.parse(jsonIds); MiniProfiler.fetchResults(ids); } } }; dotvvm.events.afterPostback.subscribe(miniProfilerUpdate); dotvvm.events.spaNavigated.subscribe(miniProfilerUpdate); dotvvm.events.staticCommandMethodInvoked.subscribe(miniProfilerUpdate); if(!window.performance || !window.performance.timing) return; var dotvvmInitialized = false; dotvvm.events.init.subscribe(function () { mPt.end('DotVVM init'); dotvvmInitialized = true; }); window.dotvvm.domUtils.onDocumentReady(function () { mPt.start('DotVVM init'); }); window.document.getElementById('mini-profiler').addEventListener('load', function () { window.MiniProfiler.initCondition = function() {return dotvvmInitialized;}; }); })()", "dotvvm"); } base.OnPreRender(context); }