/// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { if (httpContext == null) { throw new ArgumentNullException(nameof(httpContext)); } Uri spHostUrl = SharePointContext.GetUriFromQueryStringParameter(httpContext.Request, SharePointContext.SPHostUrlKey); if (spHostUrl == null) { return(null); } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return(spContext); }
public async Task Invoke(HttpContext context) { var sw = new Stopwatch(); sw.Start(); using (var memoryStream = new MemoryStream()) { var bodyStream = context.Response.Body; context.Response.Body = memoryStream; await _next(context); var isHtml = context.Response.ContentType?.ToLower().Contains("text/html"); if (context.Response.StatusCode == 200 && isHtml.GetValueOrDefault()) { memoryStream.Seek(0, SeekOrigin.Begin); using (var streamReader = new StreamReader(memoryStream)) { var responseBody = await streamReader.ReadToEndAsync(); //C# 6 DEMO var newFooter = string.Format($"<footer><div id='process'>Page processed in {sw.ElapsedMilliseconds} milliseconds.</div>"); responseBody = responseBody.Replace("<footer>", newFooter); context.Response.Headers.Add("X-ElapsedTime", new[] { sw.ElapsedMilliseconds.ToString() }); using (var amendedBody = new MemoryStream()) using (var streamWriter = new StreamWriter(amendedBody)) { streamWriter.Write(responseBody); amendedBody.Seek(0, SeekOrigin.Begin); await amendedBody.CopyToAsync(bodyStream); } } } } }
public async Task Invoke(HttpContext context, ISecretNumber secretNumber, IOptions<MessageConfiguration> configuration) { await context.Response.WriteAsync(secretNumber.ComputeNumber().ToString()); await context.Response.WriteAsync(configuration.Value.Messages.Salutation); }
private static HttpRequestMessage CreateHttpRequestMessage(HttpContext httpContext) { var httpRequest = httpContext.Request; var uriString = httpRequest.Scheme + "://" + httpRequest.Host + httpRequest.PathBase + httpRequest.Path + httpRequest.QueryString; var message = new HttpRequestMessage(new HttpMethod(httpRequest.Method), uriString); // This allows us to pass the message through APIs defined in legacy code and then // operate on the HttpContext inside. message.Properties[nameof(HttpContext)] = httpContext; message.Content = new StreamContent(httpRequest.Body); foreach (var header in httpRequest.Headers) { // Every header should be able to fit into one of the two header collections. // Try message.Headers first since that accepts more of them. if (!message.Headers.TryAddWithoutValidation(header.Key, header.Value)) { var added = message.Content.Headers.TryAddWithoutValidation(header.Key, header.Value); Debug.Assert(added); } } return message; }
public bool Authorize(HttpContext httpContext, BasicAuthIdentity identity, string roles) { if (identity == null) return false; return identity.Username == identity.Password; }
//private string requiredSiteFolder; //public SiteFolderRouteConstraint(string folderParam) //{ // requiredSiteFolder = folderParam; //} public bool Match( HttpContext httpContext, IRouter route, string parameterName, IDictionary<string,object> values, RouteDirection routeDirection) { string requestFolder = RequestSiteResolver.GetFirstFolderSegment(httpContext.Request.Path); //return string.Equals(requiredSiteFolder, requestFolder, StringComparison.CurrentCultureIgnoreCase); ISiteResolver siteResolver = httpContext.ApplicationServices.GetService<ISiteResolver>(); if(siteResolver != null) { try { // exceptions expected here until db install scripts have run or if db connection error ISiteSettings site = siteResolver.Resolve(); if ((site != null) && (site.SiteFolderName == requestFolder)) { return true; } } catch { // do we need to log this? } } return false; }
/// <summary> /// Initializes a new instance of the <see cref="UrlHelper"/> class using the specified action context and /// action selector. /// </summary> /// <param name="contextAccessor">The <see cref="IScopedInstance{TContext}"/> to access the action context /// of the current request.</param> /// <param name="actionSelector">The <see cref="IActionSelector"/> to be used for verifying the correctness of /// supplied parameters for a route. /// </param> public UrlHelper(IScopedInstance<ActionContext> contextAccessor, IActionSelector actionSelector) { _httpContext = contextAccessor.Value.HttpContext; _router = contextAccessor.Value.RouteData.Routers[0]; _ambientValues = contextAccessor.Value.RouteData.Values; _actionSelector = actionSelector; }
public async Task Invoke(HttpContext context) { using (var memoryStream = new MemoryStream()) { var bodyStream = context.Response.Body; context.Response.Body = memoryStream; await _next(context); var isHtml = context.Response.ContentType?.ToLower().Contains("text/html"); if (context.Response.StatusCode == 200 && isHtml.GetValueOrDefault()) { { memoryStream.Seek(0, SeekOrigin.Begin); using (var streamReader = new StreamReader(memoryStream)) { string body = await streamReader.ReadToEndAsync(); body = MinifyHtml(body); using (var minBodyStream = new MemoryStream()) using (var streamWriter = new StreamWriter(minBodyStream)) { streamWriter.Write(body); streamWriter.Flush(); minBodyStream.Seek(0, SeekOrigin.Begin); await minBodyStream.CopyToAsync(bodyStream); } } } } } }
public async Task Invoke(HttpContext context) { if (context.Request.Headers.ContainsKey("Authorization")) { var token = Convert.FromBase64String(context.Request.Headers["Authorization"]); if (token.Length > 3 && token.Length < 91) { // handshake state 2 - CHALLENGE context.Response.StatusCode = StatusCodes.Status401Unauthorized; context.Response.Headers.Add("WWW-Authenticate", "NTLM TlRMTVNTUAACAAAAHgAeADgAAAAFwoqi4OsyKS+KwHxArb4Q4wAAAJgAmABWAAAACgAAKAAAAA9EAEUAUwBLAFQATwBQAC0ANwBRAEsANABLAEMASgACAB4ARABFAFMASwBUAE8AUAAtADcAUQBLADQASwBDAEoAAQAeAEQARQBTAEsAVABPAFAALQA3AFEASwA0AEsAQwBKAAQAHgBEAEUAUwBLAFQATwBQAC0ANwBRAEsANABLAEMASgADAB4ARABFAFMASwBUAE8AUAAtADcAUQBLADQASwBDAEoABwAIAAWsUmSNW9EBAAAAAA=="); return; } else if (token.Length > 90) { // handshake state 3 - AUTHENTICATED } else { // handshake state 1 - NEGOTIATE context.Response.StatusCode = StatusCodes.Status401Unauthorized; context.Response.Headers.Add("WWW-Authenticate", "NTLM"); return; } } else { // handshake state 1 - NEGOTIATE context.Response.StatusCode = StatusCodes.Status401Unauthorized; context.Response.Headers.Add("WWW-Authenticate", "NTLM"); return; } await _next(context); }
public bool Match(HttpContext httpContext, IRouter route, string routeKey, IDictionary<string, object> values, RouteDirection routeDirection) { var context = httpContext.ApplicationServices.GetService<IPantherContext>(); var url = "/"; if (context == null) return false; //if (values.ContainsKey("culture") && !CheckCulture(values["culture"].ToString())) // return false; if(values.ContainsKey("url") && values["url"] != null) url = values["url"].ToString(); var canHandle = context.CanHandleUrl(context.Path); if (!canHandle) return false; if (!string.IsNullOrEmpty(context.Current.Controller)) values["controller"] = context.Current.Controller; if (!string.IsNullOrEmpty(context.Current.Action)) values["action"] = context.Current.Action; if (!string.IsNullOrEmpty(context.Current.Route)) context.Router.AddVirtualRouteValues(context.Current.Route, context.VirtualPath, values); values["context"] = context; return context.Current != null; }
/// <summary> /// Creates a new <see cref="VirtualPathContext"/>. /// </summary> /// <param name="httpContext">The <see cref="Http.HttpContext"/> associated with the current request.</param> /// <param name="ambientValues">The set of route values associated with the current request.</param> /// <param name="values">The set of new values provided for virtual path generation.</param> public VirtualPathContext( HttpContext httpContext, RouteValueDictionary ambientValues, RouteValueDictionary values) : this(httpContext, ambientValues, values, null) { }
public async Task Invoke(HttpContext context) { //Mocking the calcapi if (context.Request.Host.Value.Equals("www.calcapi.io")) { if (context.Request.Path.Value == "/count") { await context.Response.WriteAsync("1"); } } //Mocking the calendarapi else if (context.Request.Host.Value.Equals("www.calendarapi.io")) { if (context.Request.Path.Value == "/today") { await context.Response.WriteAsync("2015-04-15"); } else if (context.Request.Path.Value == "/yesterday") { await context.Response.WriteAsync("2015-04-14"); } else if (context.Request.Path.Value == "/tomorow") { await context.Response.WriteAsync("2015-04-16"); } } else { throw new Exception("undefined host : " + context.Request.Host.Value); } //await next(context); }
public CustomUrlHelper(IScopedInstance<ActionContext> contextAccessor, IActionSelector actionSelector, IOptions<AppOptions> appOptions) : base(contextAccessor, actionSelector) { _appOptions = appOptions; _httpContext = contextAccessor.Value.HttpContext; }
public static async Task ProcessRequestAsync(HttpContext Context, string Action) { var form = Context.Request.Form; Context.Response.ContentType = "text/javascript"; switch (Action) { case Forms.TakeThePledge.Action.Form: var businessName = form[Forms.TakeThePledge.Keys.BusinessName]; var address = form[Forms.TakeThePledge.Keys.Address]; var manager = form[Forms.TakeThePledge.Keys.OwnerManagerName]; var phoneNumber = form[Forms.TakeThePledge.Keys.PhoneNumber]; var email = form[Forms.TakeThePledge.Keys.Email]; var website = form[Forms.TakeThePledge.Keys.Website]; string message = $"Business Name: {businessName}\r\nAddress: {address}\r\nOwner/Manager: {manager}\r\nPhone Number: {phoneNumber}\r\nEmail: {email}\r\nWebsite: {website}"; try { var e = new Site.Email() { To = Application.TakeThePledge.Form.EmailTo, Subject = "New Business Took Bag Free Portsmouth Pledge", Body = message }; if (_queue == null) { _queue = CloudStorageAccount.Parse($"DefaultEndpointsProtocol=https;AccountName={Application.Queue.Name};AccountKey={Application.Queue.Key}").CreateCloudQueueClient().GetQueueReference(Application.Queue.Name); } await _queue.AddMessageAsync(new CloudQueueMessage(JsonConvert.SerializeObject(e))); await Context.Response.WriteAsync(Response.Substitute(Forms.TakeThePledge.HtmlID.FormContainer, "<div class=\"tac blue\">Thanks! Your information has been received and you'll be contacted shortly.</div>")); } catch { await Context.Response.WriteAsync(Response.Substitute(Forms.TakeThePledge.HtmlID.FormContainer, $"<div class=\"tac blue\">Sorry, there was an error processing the form.</div>")); } break; } }
async Task OnLogin(HttpContext ctx) { LoginWasCalled = true; await ReadSignInMessage(ctx); await IssueLoginCookie(ctx); await CreateSignInResponse(ctx); }
public async Task Invoke(HttpContext httpContext, RequestTelemetry telemetry) { telemetry.Timestamp = DateTimeOffset.UtcNow; var sw = new Stopwatch(); sw.Start(); bool requestFailed = false; try { await this.next.Invoke(httpContext); } catch (Exception) { requestFailed = true; throw; } finally { sw.Stop(); telemetry.Duration = sw.Elapsed; telemetry.ResponseCode = httpContext.Response.StatusCode.ToString(); telemetry.Success = (!requestFailed) && (httpContext.Response.StatusCode < 400); telemetry.HttpMethod = httpContext.Request.Method; telemetry.Url = httpContext.Request.GetUri(); telemetry.Context.GetInternalContext().SdkVersion = this.sdkVersion; this.telemetryClient.TrackRequest(telemetry); } }
/// <summary> /// Initializes a new <see cref="OAuthRequestTokenContext"/> /// </summary> /// <param name="context">HTTP environment</param> /// <param name="challenge">The www-authenticate header value.</param> public OAuthChallengeContext( HttpContext context, string challenge) : base(context) { Challenge = challenge; }
public async Task Invoke(HttpContext httpContext, UserManager<ApplicationUser> manager) { if (httpContext.Request.Path.StartsWithSegments(_options.Path)) { var headers = httpContext.Request.Headers; if (!(headers.ContainsKey("ApiUser") && headers.ContainsKey("ApiToken"))) { await httpContext.Authentication.ChallengeAsync(); return; } var apiUser = headers.FirstOrDefault(h => h.Key == "ApiUser").Value; var token = headers.FirstOrDefault(h => h.Key == "ApiToken").Value; var user = await manager.FindByNameAsync(apiUser).ConfigureAwait(false); var authorized = await manager.VerifyUserTokenAsync(user, "Default", "api-request-injest", token).ConfigureAwait(false); if (!authorized) { await httpContext.Authentication.ChallengeAsync(); return; } } await _next(httpContext); }
public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception ex) { _logger.LogError("An unhandled exception has occurred while executing the request", ex); if (context.Response.HasStarted) { _logger.LogWarning("The response has already started, the error page middleware will not be executed."); throw; } try { context.Response.Clear(); context.Response.StatusCode = 500; await DisplayException(context, ex); return; } catch (Exception ex2) { // If there's a Exception while generating the error page, re-throw the original exception. _logger.LogError("An exception was thrown attempting to display the error page.", ex2); } throw; } }
public async Task Invoke(HttpContext httpContext) { if (httpContext == null) { throw new ArgumentNullException(nameof(httpContext)); } var existingFeature = httpContext.Features.Get<IServiceProvidersFeature>(); // All done if request services is set if (existingFeature?.RequestServices != null) { await _next.Invoke(httpContext); return; } using (var feature = new RequestServicesFeature(_services)) { try { httpContext.Features.Set<IServiceProvidersFeature>(feature); await _next.Invoke(httpContext); } finally { httpContext.Features.Set(existingFeature); } } }
public async Task<AntiforgeryTokenSet> GetRequestTokensAsync(HttpContext httpContext) { if (httpContext == null) { throw new ArgumentNullException(nameof(httpContext)); } var requestCookie = httpContext.Request.Cookies[_options.CookieName]; if (string.IsNullOrEmpty(requestCookie)) { throw new InvalidOperationException( Resources.FormatAntiforgery_CookieToken_MustBeProvided(_options.CookieName)); } if (!httpContext.Request.HasFormContentType) { // Check the content-type before accessing the form collection to make sure // we throw gracefully. throw new InvalidOperationException( Resources.FormatAntiforgery_FormToken_MustBeProvided(_options.FormFieldName)); } var form = await httpContext.Request.ReadFormAsync(); var formField = form[_options.FormFieldName]; if (string.IsNullOrEmpty(formField)) { throw new InvalidOperationException( Resources.FormatAntiforgery_FormToken_MustBeProvided(_options.FormFieldName)); } return new AntiforgeryTokenSet(formField, requestCookie); }
public async Task Invoke(HttpContext httpContext) { // We check Ordinal explicitly first because it's faster than OrdinalIgnoreCase if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal) || httpContext.Request.Path.StartsWithSegments(_path, StringComparison.OrdinalIgnoreCase)) { var db = (ApplicationDbContext)httpContext.RequestServices.GetService(typeof(ApplicationDbContext)); db.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking; var id = _random.Next(1, 10001); var row = await db.World.SingleAsync(w => w.Id == id); var result = JsonConvert.SerializeObject(row); httpContext.Response.StatusCode = 200; httpContext.Response.ContentType = "application/json"; httpContext.Response.ContentLength = result.Length; await httpContext.Response.WriteAsync(result); return; } await _next(httpContext); }
private static Task Success(HttpContext context) { context.Response.StatusCode = 200; context.Items["test.PathBase"] = context.Request.PathBase.Value; context.Items["test.Path"] = context.Request.Path.Value; return Task.FromResult<object>(null); }
public async Task Invoke(HttpContext httpContext) { if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("Begin Routing Request"); } var shellSettings = httpContext.RequestServices.GetService<ShellSettings>(); var routerTable = httpContext.ApplicationServices.GetService<IRunningShellRouterTable>(); var router = routerTable.GetOrAdd( shellSettings.Name, name => httpContext.RequestServices.GetService<IRouteBuilder>().Build() ); var context = new RouteContext(httpContext); context.RouteData.Routers.Add(router); await router.RouteAsync(context); if (!context.IsHandled) { if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("Request did not match any routes."); } await _next.Invoke(httpContext); } if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("End Routing Request"); } }
public async Task Invoke(HttpContext httpContext) { // We check Ordinal explicitly first because it's faster than OrdinalIgnoreCase if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal) || httpContext.Request.Path.StartsWithSegments(_path, StringComparison.OrdinalIgnoreCase)) { httpContext.Response.ContentType = "text/html"; await httpContext.Response.WriteAsync("<h1>Application Information</h1>"); await httpContext.Response.WriteAsync("<ul>"); await httpContext.Response.WriteAsync($"<li>Environment: {_hostingEnv.EnvironmentName}</li>"); await httpContext.Response.WriteAsync($"<li>Framework: {_appEnv.RuntimeFramework.FullName}</li>"); await httpContext.Response.WriteAsync($"<li>Configuration: {_configurationName}</li>"); await httpContext.Response.WriteAsync($"<li>Server: {_hostingEnv.Configuration["server"]}</li>"); await httpContext.Response.WriteAsync($"<li>Server URLs: {_hostingEnv.Configuration["server.urls"]}</li>"); await httpContext.Response.WriteAsync($"<li>Supports Send File: {httpContext.Response.SupportsSendFile()}</li>"); await httpContext.Response.WriteAsync($"<li>Server features:<ul>"); foreach (var feature in httpContext.Features) { await httpContext.Response.WriteAsync($"<li>{feature.Key.Name}</li>"); } await httpContext.Response.WriteAsync($"</ul></li>"); await httpContext.Response.WriteAsync("</ul>"); return; } await _next(httpContext); }
public Task Invoke(HttpContext httpContext) { string cacheKey = "GreetingMiddleware-Invoke"; string greeting; // try to get the cached item; null if not found // greeting = _memoryCache.Get(cacheKey) as string; // alternately, TryGet returns true if the cache entry was found if(!_memoryCache.TryGetValue(cacheKey, out greeting)) { // fetch the value from the source greeting = _greetingService.Greet("world"); // store in the cache _memoryCache.Set(cacheKey, greeting, new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromMinutes(1))); _logger.LogInformation($"{cacheKey} updated from source."); } else { _logger.LogInformation($"{cacheKey} retrieved from cache."); } return httpContext.Response.WriteAsync(greeting); }
public async Task Respond(HttpContext context) { // Get path Match match = new Regex(_request_regex_pattern).Match(context.Request.Path); int length = match.Groups.Count; if (length < 2) length = 2; string[] matches = new string[length]; matches[1] = ""; for (int i = 0; i < match.Groups.Count; i++) { matches[i] = match.Groups[i].Value; } string file_path = String.Format(_file_directory, matches); // Check existance if (!File.Exists(file_path)) { IHttpHandler error_handler = new ErrorHandler(404); await error_handler.Respond(context); return; } // Change content type if needed string ext = Path.GetExtension(file_path); if (_content_types.ContainsKey(ext)) { context.Response.ContentType = _content_types[ext]; } await context.Response.SendFile(file_path); }
public async Task Invoke(HttpContext context, TenantService service) { if (!await service.SetTenant(context)) return; await _next(context); }
private string[] GetAndCacheAllMatchingValues(string routeKey, HttpContext httpContext) { var actionDescriptors = GetAndValidateActionDescriptorsCollection(httpContext); var version = actionDescriptors.Version; var valuesCollection = _cachedValuesCollection; if (valuesCollection == null || version != valuesCollection.Version) { var routeValueCollection = actionDescriptors .Items .Select(ad => ad.RouteConstraints .FirstOrDefault( c => c.RouteKey == routeKey && c.KeyHandling == RouteKeyHandling.RequireKey)) .Where(rc => rc != null) .Select(rc => rc.RouteValue) .Distinct() .ToArray(); valuesCollection = new RouteValuesCollection(version, routeValueCollection); _cachedValuesCollection = valuesCollection; } return _cachedValuesCollection.Items; }
/// <summary> /// Executes the middleware. /// </summary> /// <param name="context">The <see cref="HttpContext"/> for the current request.</param> /// <returns>A task that represents the execution of this middleware.</returns> public async Task Invoke(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } PathString path = context.Request.Path; PathString remainingPath; if (path.StartsWithSegments(_options.PathMatch, out remainingPath)) { // Update the path PathString pathBase = context.Request.PathBase; context.Request.PathBase = pathBase + _options.PathMatch; context.Request.Path = remainingPath; try { await _options.Branch(context); } finally { context.Request.PathBase = pathBase; context.Request.Path = path; } } else { await _next(context); } }
/// <summary> /// Initializes base class used for certain event contexts /// </summary> protected BaseValidatingClientContext( HttpContext context, OpenIdConnectServerOptions options, OpenIdConnectMessage request) : base(context, options) { Request = request; }
/// <summary> /// Getting the correct url with the correct url scheme since httpContext.Request.GetDisplayUrl() /// provides incorrect 'http' scheme even we are running on 'https'. It needs to be double checked until /// better solution has been found. /// </summary> /// <param name="httpContext"></param> /// <returns></returns> private static string GetCurrentUrl(HttpContext httpContext) { var url = httpContext.Request.GetDisplayUrl(); //compare request scheme var serverScheme = ((Microsoft.AspNet.Server.Kestrel.Http.ListenerContext) ((Microsoft.AspNet.Http.Internal.DefaultHttpContext)httpContext).Features).ServerAddress.Scheme; if (httpContext.Request.Scheme != serverScheme) { url = url.Replace(httpContext.Request.Scheme, serverScheme); } return(url); }
protected override SharePointContext LoadSharePointContext(HttpContext httpContext) { byte[] value; httpContext.Session.TryGetValue(SPContextKey, out value); if (value == null) { return(null); } char[] chars = new char[value.Length / sizeof(char)]; System.Buffer.BlockCopy(value, 0, chars, 0, value.Length); string acsSessionContext = new string(chars); var dto = JsonConvert.DeserializeObject <SharePointSessionData>(acsSessionContext); var contextTokenObj = TokenHandler.ReadAndValidateContextToken(dto.ContextToken, httpContext.Request.Host.Value); return(new SharePointAcsContext(dto.SpHostUrl, dto.SpAppWebUrl, dto.SpLanguage, dto.SpClientTag, dto.SpProductNumber, dto.ContextToken, contextTokenObj, Configuration)); }
protected override void SaveSharePointContext(SharePointContext spContext, HttpContext httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; //creates a cookie to store the SPCacheKey if (spAcsContext != null) { //The following code generates a cookie in the response with the SPCacheKey as a value var options = new CookieOptions() { HttpOnly = true, Secure = true }; httpContext.Response.Cookies.Append(SPCacheKeyKey, spAcsContext.CacheKey, options); } string output = JsonConvert.SerializeObject(spAcsContext); byte[] bytes = new byte[output.Length * sizeof(char)]; System.Buffer.BlockCopy(output.ToCharArray(), 0, bytes, 0, bytes.Length); httpContext.Session.Set(SPContextKey, bytes); }
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContext httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; //Checks for the SPCacheKey cookie and gets the value if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetUriFromQueryStringParameter (httpContext.Request, SharePointContext.SPHostUrlKey); string contextToken = TokenHandler.GetContextTokenFromRequest(httpContext.Request); //read the cookie value HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey, httpContext.Request.Cookies[SPCacheKeyKey]); string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return(spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken)); } return(false); }
/// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContext httpContext);
/// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContext httpContext);
/// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException(nameof(httpContext)); } redirectUrl = null; bool contextTokenExpired = false; try { if (Current.GetSharePointContext(httpContext) != null) { return(RedirectionStatus.Ok); } } catch (SecurityTokenExpiredException) { contextTokenExpired = true; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.Query[SPHasRedirectedToSharePointKey]) && !contextTokenExpired) { return(RedirectionStatus.CanNotRedirect); } Uri spHostUrl = SharePointContext.GetUriFromQueryStringParameter (httpContext.Request, SharePointContext.SPHostUrlKey); if (spHostUrl == null) { return(RedirectionStatus.CanNotRedirect); } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.Method, "POST")) { return(RedirectionStatus.CanNotRedirect); } var uri = GetCurrentUrl(httpContext); Uri requestUrl = new Uri(uri); var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHandler.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return(RedirectionStatus.ShouldRedirect); }
/// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContext httpContext);