Exemplo n.º 1
0
 public static T ConvertToModel <T>(Microsoft.AspNetCore.Http.HttpContext context) where T : new()
 {
     return(Bind <T>(str =>
     {
         return WebRequestHelper.RequestValue(str, context);// context.Request[str];
     }));
 }
Exemplo n.º 2
0
        public static bool IsMobilePhone(ref Microsoft.AspNetCore.Http.HttpContext context)
        {
            Debug.Assert(context != null);

            HttpRequest request = context.Request;

            if (request.Cookies["View"] != null &&
                request.Cookies["View"].FirstOrDefault().ToString() == "MOBILE")
            {
                return(true);
            }
            if (request.Cookies["View"] != null &&
                request.Cookies["View"].FirstOrDefault().ToString() == "DESKTOP")
            {
                return(false);
            }
            if (request != null && request.Headers["User-Agent"].ToString() != null)
            {
                var u = request.Headers["User-Agent"].ToString().ToString();
                if (u.Length < 4)
                {
                    context.Response.Cookies.Append("View", "DESKTOP");
                    return(false);
                }
                if (MobileCheck.IsMatch(u) || MobileVersionCheck.IsMatch(u.Substring(0, 4)))
                {
                    context.Response.Cookies.Append("View", "MOBILE");
                    return(true);
                }
            }
            context.Response.Cookies.Append("View", "DESKTOP");

            return(false);
        }
Exemplo n.º 3
0
        public void RequestEnd(ProtoContext httpContext, Exception exception, HostingApplication.Context context)
        {
            // Local cache items resolved multiple items, in order of use so they are primed in cpu pipeline when used
            var startTimestamp   = context.StartTimestamp;
            var currentTimestamp = 0L;

            // If startTimestamp was 0, then Information logging wasn't enabled at for this request (and calcuated time will be wildly wrong)
            // Is used as proxy to reduce calls to virtual: _logger.IsEnabled(LogLevel.Information)
            if (startTimestamp != 0)
            {
                currentTimestamp = Stopwatch.GetTimestamp();
                // Non-inline
                LogRequestFinished(httpContext, startTimestamp, currentTimestamp);
            }

            if (_diagnosticListener.IsEnabled())
            {
                if (currentTimestamp == 0)
                {
                    currentTimestamp = Stopwatch.GetTimestamp();
                }

                if (exception == null)
                {
                    // No exception was thrown, request was sucessful
                    if (_diagnosticListener.IsEnabled(DeprecatedDiagnosticsEndRequestKey))
                    {
                        // Diagnostics is enabled for EndRequest, but it may not be for BeginRequest
                        // so call GetTimestamp if currentTimestamp is zero (from above)
                        RecordEndRequestDiagnostics(httpContext, currentTimestamp);
                    }
                }
                else
                {
                    // Exception was thrown from request
                    if (_diagnosticListener.IsEnabled(DiagnosticsUnhandledExceptionKey))
                    {
                        // Diagnostics is enabled for UnhandledException, but it may not be for BeginRequest
                        // so call GetTimestamp if currentTimestamp is zero (from above)
                        RecordUnhandledExceptionDiagnostics(httpContext, currentTimestamp, exception);
                    }
                }

                var activity = context.Activity;
                // Always stop activity if it was started
                if (activity != null)
                {
                    StopActivity(httpContext, activity);
                }
            }

            if (context.EventLogEnabled && exception != null)
            {
                // Non-inline
                HostingEventSource.Log.UnhandledException();
            }

            // Logging Scope is finshed with
            context.Scope?.Dispose();
        }
Exemplo n.º 4
0
        public static async Task DoSomething(Microsoft.AspNetCore.Http.HttpContext c)
        {
            string message = @"<!DOCTYPE html>
<html>
<head>
  <meta http-equiv=""X-UA-Compatible"" content=""IE=edge"">
  <meta charset=""utf-8"" />
  <meta name=""viewport"" content=""width=device-width, initial-scale=1"" />
  <title>LoL</title>
</head>
<body>
    <h1>howdy</h1>
</body>
</html>
";

            // message = "howdy dude";
            // c.Response.StatusCode = 200;
            c.Response.ContentType = "text/plain";


            // var ba = System.Text.Encoding.UTF8.GetBytes(message);
            // c.Response.Body.Write(ba, 0, ba.Length);
            // return Task.CompletedTask;


            await c.Response.WriteAsync(message);

            await Sleeper(c);

            //
            await c.Response.WriteAsync(message);
        }
Exemplo n.º 5
0
        public override Task Invoke(HttpContext httpContext)
        {
            var context    = GetDashboardContext(httpContext);
            var findResult = _routes.FindDispatcher(httpContext.Request.Path.Value);

            if (findResult == null)
            {
                return(_next.Invoke(httpContext));
            }

            // ReSharper disable once LoopCanBeConvertedToQuery
            foreach (var filter in _authorization)
            {
                if (!filter.Authorize(context))
                {
#if NETSTANDARD
                    var isAuthenticated = httpContext.User?.Identity?.IsAuthenticated;
#else
                    var isAuthenticated = httpContext.Request?.User?.Identity?.IsAuthenticated;
#endif
                    httpContext.Response.StatusCode = isAuthenticated == true
                        ? (int)System.Net.HttpStatusCode.Forbidden
                        : (int)System.Net.HttpStatusCode.Unauthorized;

                    return(Task.CompletedTask);
                }
            }

            context.UriMatch = findResult.Item2;

            var r = findResult.Item1.DispatchAsync(context);
            return(context.NextInvoke ? _next.Invoke(httpContext) : r);
        }
        public async Task Invoke(Microsoft.AspNetCore.Http.HttpContext context)
        {
            HttpContext.Set(context);
            await _next(context);

            HttpContext.Flush();
        }
        private async Task ProcessMetaFromFile(Microsoft.AspNetCore.Http.HttpContext httpContext)
        {
            Meta.MetaFromFile meta = new Meta.MetaFromFile();
            if (!string.IsNullOrEmpty(_options.WsdlFileOptions.VirtualPath))
            {
                meta.CurrentWebServer = _options.WsdlFileOptions.VirtualPath + "/";
            }

            meta.CurrentWebService = httpContext.Request.Path.Value.Replace("/", string.Empty);

            WebServiceWSDLMapping mapping = _options.WsdlFileOptions.WebServiceWSDLMapping[meta.CurrentWebService];

            meta.XsdFolder  = mapping.SchemaFolder;
            meta.WSDLFolder = mapping.WSDLFolder;
            if (_options.WsdlFileOptions.UrlOverride != string.Empty)
            {
                meta.ServerUrl = _options.WsdlFileOptions.UrlOverride;
            }
            else
            {
                meta.ServerUrl = httpContext.Request.Scheme + "://" + httpContext.Request.Host + "/";
            }

            string wsdlfile = mapping.WsdlFile;

            string path         = _options.WsdlFileOptions.AppPath;
            string wsdl         = meta.ReadLocalFile(path + Path.AltDirectorySeparatorChar + meta.WSDLFolder + Path.AltDirectorySeparatorChar + wsdlfile);
            string modifiedWsdl = meta.ModifyWSDLAddRightSchemaPath(wsdl);

            //we should use text/xml in wsdl page for browser compability.
            httpContext.Response.ContentType = "text/xml;charset=UTF-8";
            byte[] data = System.Text.Encoding.UTF8.GetBytes(modifiedWsdl);
            await httpContext.Response.Body.WriteAsync(data, 0, data.Length);
        }
Exemplo n.º 8
0
        private void LogException(Exception error, Microsoft.AspNetCore.Http.HttpContext context)
        {
            try
            {
                //            var connectionStr = Configuration.GetConnectionString("DefaultConnection");
                //            using (var connection = new System.Data.SqlClient.SqlConnection(connectionStr))
                //            {
                //                var command = connection.CreateCommand();
                //                command.CommandText = @"INSERT INTO ErrorLog (ErrorId, Application, Host, Type, Source, Method, Message, StackTrace, [User],  TimeUtc)
                //VALUES (@ErrorId, @Application, @Host, @Type, @Source, @Method, @Message, @StackTrace, @User,  @TimeUtc)";
                //                connection.Open();

                //                if (error.InnerException != null)
                //                    error = error.InnerException;

                //                command.Parameters.AddWithValue("@ErrorId", Guid.Parse(context.TraceIdentifier));
                //                command.Parameters.AddWithValue("@Application", this.GetType().Namespace);
                //                command.Parameters.AddWithValue("@Host", Environment.MachineName);
                //                command.Parameters.AddWithValue("@Type", error.GetType().FullName);
                //                command.Parameters.AddWithValue("@Source", error.Source);
                //                command.Parameters.AddWithValue("@Method", context.Request.Method);
                //                command.Parameters.AddWithValue("@Message", error.Message);
                //                command.Parameters.AddWithValue("@StackTrace", error.StackTrace);
                //                var user = context.User.Identity?.Name;
                //                if (user == null)
                //                    command.Parameters.AddWithValue("@User", DBNull.Value);
                //                else
                //                    command.Parameters.AddWithValue("@User", user);
                //                command.Parameters.AddWithValue("@TimeUtc", DateTime.Now);

                //                command.ExecuteNonQuery();
                //            }
            }
            catch (Exception exp) { }
        }
        public JsonResult Create(string bookId)
        {
            JsonResult json = new JsonResult("Request Failed");

            if (string.IsNullOrEmpty(bookId))
            {
                json = new JsonResult("bad request");
            }
            else
            {
                Microsoft.AspNetCore.Http.HttpContext currentHttpContext = HttpContext;
                string userid = HttpContext.Session.GetString("UserID");

                int result = 0;
                if (!string.IsNullOrEmpty(userid))
                {
                    Random rnd         = new Random();
                    int    requestCode = rnd.Next(10000000, 99999999);

                    result = _context.Database.
                             ExecuteSqlCommand(
                        "[dbo].[RequestBook] @bookId = {0}, @userId = {1}, @RCode = {2}",
                        Convert.ToInt32(bookId),
                        Convert.ToInt32(userid),
                        requestCode.ToString());

                    if (result.Equals(2))
                    {
                        json = new JsonResult(requestCode);
                    }
                }
            }

            return(json);
        }
Exemplo n.º 10
0
        public static async Task OnEndRequest(Microsoft.AspNetCore.Http.HttpContext e)
        {
            //Get preflight token
            string           state   = e.Request.Query["state"];
            DbPreflightToken session = await Program.connection.GetPreflightTokenByTokenAsync(state);

            if (session == null)
            {
                await Program.QuickWriteToDoc(e, "Failed to sign in, you might have taken too long.", "text/plain", 400); //TODO: REDIRECT BACK TO LOGIN

                return;
            }

            //Do auth
            DbUser user = await SteamAuth.SteamOpenID.Finish(e);

            if (user == null)
            {
                await Program.QuickWriteToDoc(e, "Failed to sign in. Try again.", "text/plain", 400); //TODO: REDIRECT BACK TO LOGIN

                return;
            }

            //Update
            await session.SetUser(Program.connection, user);

            //Redirect to final endpoint
            string url = PREFLIGHT_OUT_URLS[session.redirect_type].Replace("{STATE}", state);

            e.Response.Headers.Add("Location", url);
            await Program.QuickWriteToDoc(e, "Redirecting...", "text/plain", 302);
        }
Exemplo n.º 11
0
        /// <summary>调用</summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext ctx)
        {
            // APM跟踪
            //var span = Tracer?.NewSpan(ctx.Request.Path);
            ISpan span = null;

            if (Tracer != null)
            {
                var action = GetAction(ctx);
                if (!action.IsNullOrEmpty())
                {
                    span     = Tracer.NewSpan(action);
                    span.Tag = ctx.Request.GetRawUrl() + "";
                    span.Detach(ctx.Request.Headers.ToDictionary(e => e.Key, e => (Object)e.Value));
                }
            }

            try
            {
                await _next.Invoke(ctx);
            }
            catch (Exception ex)
            {
                span?.SetError(ex, null);

                throw;
            }
            finally
            {
                span?.Dispose();
            }
        }
Exemplo n.º 12
0
        private void attachUserToContext(Microsoft.AspNetCore.Http.HttpContext context, IUserService userService, string token)
        {
            try
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var key          = Encoding.ASCII.GetBytes(_appSettings.Secret);
                tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false,
                    // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
                    ClockSkew = TimeSpan.Zero
                }, out SecurityToken validatedToken);

                var jwtToken  = (JwtSecurityToken)validatedToken;
                var userModel = new UserLoginModel();
                var claim     = jwtToken.Claims.First(x => x.Type == ClaimTypes.UserData);
                if (claim != null)
                {
                    userModel = JsonConvert.DeserializeObject <UserLoginModel>(claim.Value);
                }

                //var userInfo = int.Parse(jwtToken.Claims.First(x => x.Type == ClaimTypes.UserData).Value);

                // attach user to context on successful jwt validation
                context.Items["User"] = userModel;
            }
            catch
            {
                // do nothing if jwt validation fails
                // user is not attached to context so request won't have access to secure routes
            }
        }
Exemplo n.º 13
0
        protected TestInvolvingAspNetHttpContext()
        {
            HttpContext = SetupFakeHttpContext();
#if !ASP_NET_CORE
            HttpContext.Current = HttpContext;
#endif
        }
        //异常错误信息捕获,将错误信息用Json方式返回
        private static Task HandleExceptionAsync(Microsoft.AspNetCore.Http.HttpContext context, Exception ex, int statusCode)
        {
            StringBuilder builder = new StringBuilder(ex.Message);

            ErrorHandlingMiddleware.GetExceptionMessage(ex, builder);
            ApiResult apiResult = new ApiResult()
            {
                Success = false, Data = new ApiResultData()
                {
                    Message = builder.ToString(), RequestUrl = context.Request.Path, ExceptionCode = statusCode
                }
            };

            if (ex is BusinessException)
            {
                apiResult.Data.ExceptionCode = (ex as BusinessException).ExceptionCode;
            }

            var result = JsonConvert.SerializeObject(apiResult);

            context.Response.ContentType = "application/json;charset=utf-8";

            GlobalConstants.DefaultLogger.Error(result);
            GlobalConstants.DefaultLogger.Error(ex.StackTrace);

            return(context.Response.WriteAsync(result));
        }
Exemplo n.º 15
0
            public async System.Threading.Tasks.Task SlowTaskStatusCode(Microsoft.AspNetCore.Http.HttpContext httpContext)
            {
                var handler = new Samples.MyHandler();
                var result  = await handler.SlowTaskStatusCode();

                await result.ExecuteAsync(httpContext);
            }
        private static async Task WriteExceptionAsync(HttpContext context, Exception exception)
        {
            //记录日志
            var logger = LogManager.GetCurrentClassLogger();

            logger.Log(LogLevel.Error, exception.Message);
            //返回友好的提示
            var response = context.Response;

            //状态码
            if (exception is UnauthorizedAccessException)
            {
                response.StatusCode = (int)HttpStatusCode.Unauthorized;
            }
            else
            {
                response.StatusCode = (int)HttpStatusCode.BadRequest;
            }

            response.ContentType = context.Request.Headers["Accept"];
            var result = new Result(StateCode.Fail, exception.Message);

            if (response.ContentType.ToLower() == "application/xml")
            {
                await response.WriteAsync(Object2XmlString(result)).ConfigureAwait(false);
            }
            response.ContentType = "application/json";
            await response.WriteAsync(JsonConvert.SerializeObject(result)).ConfigureAwait(false);
        }
Exemplo n.º 17
0
            public System.Threading.Tasks.Task Authed(Microsoft.AspNetCore.Http.HttpContext httpContext)
            {
                var handler = new Samples.MyHandler();

                handler.Authed();
                return(System.Threading.Tasks.Task.CompletedTask);
            }
Exemplo n.º 18
0
            public System.Threading.Tasks.Task Blah(Microsoft.AspNetCore.Http.HttpContext httpContext)
            {
                var handler = new Samples.MyHandler();
                var result  = handler.Blah();

                return(httpContext.Response.WriteAsJsonAsync(result));
            }
Exemplo n.º 19
0
            public async System.Threading.Tasks.Task PostAForm(Microsoft.AspNetCore.Http.HttpContext httpContext)
            {
                var handler  = new Samples.MyHandler();
                var arg_form = await httpContext.Request.ReadFormAsync();

                handler.PostAForm(arg_form);
            }
Exemplo n.º 20
0
            public async System.Threading.Tasks.Task Hello(Microsoft.AspNetCore.Http.HttpContext httpContext)
            {
                var handler        = new Samples.MyHandler();
                var formCollection = await httpContext.Request.ReadFormAsync();

                var arg_s          = formCollection["foo"].ToString();
                var arg_id         = httpContext.Request.Headers["X-Id"].ToString();
                var arg_page_Value = httpContext.Request.Query["page"].ToString();

                System.Nullable <int> arg_page;
                if (arg_page_Value != null && int.TryParse(arg_page_Value, out var arg_page_Temp))
                {
                    arg_page = arg_page_Temp;
                }
                else
                {
                    arg_page = default;
                }
                var arg_pageSize_Value = httpContext.Request.Query["pageSize"].ToString();

                System.Nullable <int> arg_pageSize;
                if (arg_pageSize_Value != null && int.TryParse(arg_pageSize_Value, out var arg_pageSize_Temp))
                {
                    arg_pageSize = arg_pageSize_Temp;
                }
                else
                {
                    arg_pageSize = default;
                }
                var result = handler.Hello(arg_s, arg_id, arg_page, arg_pageSize);
                await httpContext.Response.WriteAsync(result);
            }
Exemplo n.º 21
0
        private async Task HandleErrorAsync(Microsoft.AspNetCore.Http.HttpContext context, Exception exception)
        {
            //await _exceptionLogService.AddExceptionAsync(new ExceptionLogModel()
            //{
            //    ClassName = nameof(exception),
            //    Message = exception.Message,
            //    Source = exception.Source,
            //    StackTrace = exception.StackTrace
            //        .Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList()
            //});
            //Console.WriteLine(exception.Message);
            //if (Debugger.IsAttached)
            //{
            //    Debugger.Break();
            //}
            Console.WriteLine($"ErrorHandler:{exception.Message}");
            ApiResult apiResult;

            if (exception is PermissionAuthorizeFailException)
            {
                apiResult = ApiResult.GetRequestError("权限验证失败");
            }
            else
            {
                apiResult = ApiResult.GetServerError(exception.Message);
            }
            var response = context.Response;

            response.ContentType = "application/json";
            await response.WriteAsync(JsonSerializerHelper.SerializeObject(apiResult));
        }
Exemplo n.º 22
0
        public static async Task OnTokenRequest(Microsoft.AspNetCore.Http.HttpContext e)
        {
            //Get preflight token
            string           state   = e.Request.Query["state"];
            DbPreflightToken session = await Program.connection.GetPreflightTokenByTokenAsync(state);

            if (session == null)
            {
                await Program.QuickWriteToDoc(e, "Failed to sign in, you might have taken too long.", "text/plain", 400); //TODO: REDIRECT BACK TO LOGIN

                return;
            }

            //Verify
            if (!session.auth)
            {
                await Program.QuickWriteToDoc(e, "Token is not yet valid.", "text/plain", 400);

                return;
            }

            //Create output data
            TokenResponseData d = new TokenResponseData
            {
                token = session.final_token,
                next  = session.next,
                nonce = session.nonce
            };

            await Program.QuickWriteJsonToDoc(e, d);
        }
Exemplo n.º 23
0
        public static HttpContext GetHttpContext()
        {
            object factory = CPAppContext.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));

            Microsoft.AspNetCore.Http.HttpContext context = ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext;
            return(context);
        }
        public static void SetResponseCookie(this Microsoft.AspNetCore.Http.HttpContext context,
                                             string key,
                                             string value,
                                             DateTime expires,
                                             string subdomain = null,
                                             string path      = "/",
                                             bool httpOnly    = false,
                                             bool secure      = false)
        {
            var cookieOptions = new CookieOptions {
                Expires  = expires,
                Domain   = subdomain,
                Path     = path,
                Secure   = secure,
                HttpOnly = httpOnly
            };

            if (string.IsNullOrWhiteSpace(value))
            {
                context.Response.Cookies.Delete(key);
            }
            else
            {
                context.Response.Cookies.Append(key, value, cookieOptions);
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Read UserID from HttpContext
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static int GetUserID(this Microsoft.AspNetCore.Http.HttpContext context)
        {
            var claimsIdentity = context.User;
            var claim          = claimsIdentity.Claims.FirstOrDefault(cl => cl.Type == ClaimTypes.PrimarySid);

            return(Convert.ToInt32(claim.Value));
        }
Exemplo n.º 26
0
        public async Task Invoke(Microsoft.AspNetCore.Http.HttpContext context)
        {
            var httpContextAccessor = context.RequestServices.GetService <IHttpContextAccessor>();

            HttpContext.Configure(httpContextAccessor);
            await _next.Invoke(context);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Invoke middleware actions
        /// </summary>
        /// <param name="context">HTTP context</param>
        /// <param name="webHelper">Web helper</param>
        /// <param name="workContext">Work context</param>
        /// <returns>Task</returns>
        public Task Invoke(Microsoft.AspNetCore.Http.HttpContext context)
        {
            CommonHelper.SetTelerikCulture();

            //call the next middleware in the request pipeline
            return(_next(context));
        }
Exemplo n.º 28
0
        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        /// <param name="strValue">过期时间(分钟)</param>
        public static void WriteCookie(Microsoft.AspNetCore.Http.HttpContext context, string strName, string strValue, int expires, string domain = "", string path = "/", bool httponly = true, bool secure = false)
        {
#if !NET45
            context.Response.Cookies.Append(strName, strValue, new CookieOptions()
            {
                Domain   = domain,
                Path     = path,
                HttpOnly = httponly,
                Secure   = secure,
                Expires  = new DateTimeOffset(DateTime.Now.AddMinutes(expires))
            });
#else
            HttpCookie cookie = context.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value   = strValue;
            cookie.Expires = DateTime.Now.AddMinutes(expires);

            cookie.HttpOnly = httponly;
            cookie.Secure   = secure;
            cookie.Path     = path;

            if (domain != null)
            {
                cookie.Domain = domain;
            }

            context.Response.AppendCookie(cookie);
#endif
        }
Exemplo n.º 29
0
        public static Microsoft.AspNetCore.Http.HttpContext Current()
        {
            object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));

            Microsoft.AspNetCore.Http.HttpContext context = ((IHttpContextAccessor)factory).HttpContext;
            return(context);
        }
 public async Task Invoke(Microsoft.AspNetCore.Http.HttpContext context)
 {
     try
     {
         await next(context);
     }
     catch (Exception ex)
     {
         var statusCode = context.Response.StatusCode;
         if (ex is ArgumentException)
         {
             statusCode = 200;
         }
         try
         {
             await HandleExceptionAsync(context, ex, statusCode);
         }
         catch
         {
         }
     }
     finally
     {
         var statusCode = context.Response.StatusCode;
         if (statusCode != 101)
         {
             await ProcessError(context, statusCode);
         }
     }
 }
Exemplo n.º 31
0
        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);
        }
Exemplo n.º 32
0
 /// <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);
Exemplo n.º 33
0
        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);
        }
Exemplo n.º 34
0
 /// <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);
Exemplo n.º 35
0
        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
                var cookieCollection = httpContext.Request.Cookies;

                if (!cookieCollection.ContainsKey(SPCacheKeyKey)) return false;

                var spCacheKeyCookieValue = httpContext.Request.Cookies[SPCacheKeyKey];
                string spCacheKey = spCacheKeyCookieValue != null ? spCacheKeyCookieValue : null;

                //return spHostUrl == spAcsContext.SPHostUrl && (taken out)
                return 
                       !string.IsNullOrEmpty(spAcsContext.CacheKey) &&
                       spCacheKey == spAcsContext.CacheKey &&
                       !string.IsNullOrEmpty(spAcsContext.ContextToken) &&
                       (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
            }

            return false;
        }
Exemplo n.º 36
0
 /// <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();
     return url;
 }
Exemplo n.º 37
0
 /// <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);
Exemplo n.º 38
0
        /// <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);

            var queryNameValueCollection = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri);

            // 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(uri);
            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;
        }
Exemplo n.º 39
0
        /// <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));
            }

            SharePointContext spContext = LoadSharePointContext(httpContext);

            if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
            {
                spContext = CreateSharePointContext(httpContext.Request);

                if (spContext != null)
                {
                    SaveSharePointContext(spContext, httpContext);
                }
            }

            return spContext;
        }