public string GetRouteDescriptorKey(HttpContextBase httpContext, RouteBase routeBase) { var route = routeBase as Route; var dataTokens = new RouteValueDictionary(); if (route != null) { dataTokens = route.DataTokens; } else { var routeData = routeBase.GetRouteData(httpContext); if (routeData != null) { dataTokens = routeData.DataTokens; } } var keyBuilder = new StringBuilder(); if (route != null) { keyBuilder.AppendFormat("url={0};", route.Url); } // the data tokens are used in case the same url is used by several features, like *{path} (Rewrite Rules and Home Page Provider) if (dataTokens != null) { foreach (var key in dataTokens.Keys) { keyBuilder.AppendFormat("{0}={1};", key, dataTokens[key]); } } return keyBuilder.ToString().ToLowerInvariant(); }
protected override void Context() { AccountService = MockRepository.GenerateStub<IAccountService>(); Identity = new FakeIdentity(Username); _user = new FakePrincipal(Identity, null); HttpRequest = MockRepository.GenerateStub<HttpRequestBase>(); HttpContext = MockRepository.GenerateStub<HttpContextBase>(); HttpContext.Stub(x => x.Request).Return(HttpRequest); HttpContext.User = _user; _httpResponse = MockRepository.GenerateStub<HttpResponseBase>(); _httpResponse.Stub(x => x.Cookies).Return(new HttpCookieCollection()); HttpContext.Stub(x => x.Response).Return(_httpResponse); Logger = MockRepository.GenerateStub<ILogger>(); WebAuthenticationService = MockRepository.GenerateStub<IWebAuthenticationService>(); MappingEngine = MockRepository.GenerateStub<IMappingEngine>(); AccountCreator = MockRepository.GenerateStub<IAccountCreator>(); AccountController = new AccountController(AccountService, Logger, WebAuthenticationService, MappingEngine, null, AccountCreator); AccountController.ControllerContext = new ControllerContext(HttpContext, new RouteData(), AccountController); }
protected virtual object HandleDataRequest(System.Web.HttpContextBase context) { var action = context.Request.PathInfo.Substring(PathInfo.Length).Trim('/'); if (string.IsNullOrEmpty(action)) { action = "Index"; } if (context.Request.HttpMethod != "GET") { action = context.Request.HttpMethod[0] + context.Request.HttpMethod.Substring(1).ToLower() + action; } var method = GetType().GetMethods().FirstOrDefault(m => m.Name.Equals(action, StringComparison.InvariantCultureIgnoreCase)); if (method == null) { throw new HttpException(404, action + " not found"); } var methodParameters = method.GetParameters() .Select(pi => GetParameterValue(context, pi)) .ToArray(); return(method.Invoke(this, methodParameters)); }
protected static void RedirectWithLanguage( System.Web.HttpContextBase context, string urlNonlocalized, string langtag, IUrlLocalizer m_urlLocalizer) { // Construct localized URL. string urlNew = m_urlLocalizer.SetLangTagInUrlPath(context, urlNonlocalized, UriKind.Relative, langtag); // Redirect user agent to new local URL. if (LocalizedApplication.Current.PermanentRedirects) { context.Response.StatusCode = 301; context.Response.Status = "301 Moved Permanently"; } else { context.Response.StatusCode = 302; context.Response.Status = "302 Moved Temporarily"; } context.Response.RedirectLocation = urlNew; // End the request early: no further processing along the pipeline. // NB: we did originally use context.Response.End(); here but that causes an // unnecessary exception to be thrown (https://support.microsoft.com/en-us/kb/312629) (#195) // NB: the line AFTER this line will execute, so best to return immediately here // and from caller etc.. context.ApplicationInstance.CompleteRequest(); }
public override System.Threading.Tasks.Task OnDisconnected(bool stopCalled) { System.Web.HttpContextBase httpContext = Context.Request.GetHttpContext(); string clientId = Context.ConnectionId; ChatUser user = ChatBLL.Instance.GetChatUser(clientId).Object; ChatBLL.Instance.DeleteChatUser(clientId); if (!(user != null && user.UserId.HasValue)) { return(base.OnDisconnected(stopCalled)); } SingletonGlobal.Instance.ConnectedClients.Remove(Context.ConnectionId); SingletonGlobal.Instance.ConnectedUsers.Remove(user.UserId.Value); string[] Exceptional = new string[1]; Exceptional[0] = clientId; // User is offline // Update ActiveUsers in SingletonUserChatGroups var users = ChatBLL.Instance.GetOnlineUsers(user.UserId.Value).Results; var oldOnlineUers = SingletonUserChatGroups.Instance.ActiveUsers; SingletonUserChatGroups.Instance.ActiveUsers = users; if (oldOnlineUers != null && SingletonUserChatGroups.Instance.ActiveUsers != null && SingletonUserChatGroups.Instance.ActiveUsers.Count() > 0) { foreach (var item in oldOnlineUers) { if (SingletonUserChatGroups.Instance.ActiveUsers.Where(m => m.UserId == item.UserId) .FirstOrDefault() != null) { SingletonUserChatGroups.Instance.ActiveUsers.Where(m => m.UserId == item.UserId) .FirstOrDefault().Status = item.Status; SingletonUserChatGroups.Instance.ActiveUsers.Where(m => m.UserId == item.UserId) .FirstOrDefault().OnlineAt = item.OnlineAt; } if (SingletonUserChatGroups.Instance.ActiveUsers.Where(m => m.UserId == user.UserId).Any()) { SingletonUserChatGroups.Instance.ActiveUsers.Where(m => m.UserId == user.UserId) .FirstOrDefault().OnlineAt = null; SingletonUserChatGroups.Instance.ActiveUsers.Where(m => m.UserId == user.UserId) .FirstOrDefault().Status = (int)ChatUserStatus.Offline; } } } //ChatMessageActiveUser obj = new ChatMessageActiveUser(); //obj.ActiveUsers = SingletonUserChatGroups.Instance.ActiveUsers.OrderBy(m => m.Status).ToList(); Clients.AllExcept(Exceptional).onDisconnectedCallback(new ActionOutput <int> { Status = ActionStatus.Successfull //, //Object = ChatBLL.Instance.GetActiveUsersByLoggedInUser(SingletonGlobal.Instance.ConnectedUsers.ToList(), user.UserId.Value) // .Where(m => m != user.UserId.Value) // .Count() }); return(base.OnDisconnected(stopCalled)); }
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { //if (!string.IsNullOrEmpty(Roles)) //{ // var roles = Roles.Split(','); // foreach (var r in roles) // { // var _r = r.Trim(); // var type = _r.ToEnum<AccountTypeEnum>(); // if (AuthenticationManager.Is(type)) // return true; // } //} if (AuthenticationManager.IsMod) { return(true); } if (Types != null) { foreach (var type in Types) { if (AuthenticationManager.Is(type)) { return(true); } } return(false); } return(AuthenticationManager.IsBasicAuthorized);// IsAuthenticated; }
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { System.Web.HttpContextBase context = filterContext.HttpContext; if (HttpContext.Current.Session["Login"] == null || Convert.ToBoolean(HttpContext.Current.Session["Login"]) == false) { //FormsAuthentication.RedirectToLoginPage(); filterContext.HttpContext.Response.Redirect("~/Login", true); } else if (context.Session != null) { if (context.Session.IsNewSession) { string sessionCookie = context.Request.Headers["Cookie"]; if ((sessionCookie != null) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)) { FormsAuthentication.SignOut(); string redirectTo = "~/Login"; if (!string.IsNullOrEmpty(context.Request.RawUrl)) { redirectTo = string.Format("~/Login/index?ReturnUrl={0}", HttpUtility.UrlEncode(context.Request.RawUrl)); } filterContext.HttpContext.Response.Redirect(redirectTo, true); } } } base.OnActionExecuting(filterContext); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { User user = (User)httpContext.Session[WebConstants.UserSessionKey]; if (user == null) { httpContext.Response.Redirect("~/Account/login"); return false; } else { if (user.Code == "su") { return true; } if (string.IsNullOrWhiteSpace(Permissions)) { return true; } else { string[] permissionArray = Permissions.Split(AuthorizeAttributeSplitSymbol); foreach (string permission in permissionArray) { if (user.UrlPermissions.Contains(permission)) { return true; } } return false; } } }
public override void ProcessSignInRequest(Scope scope, HttpContextBase httpContext) { httpContext.ApplicationInstance.CompleteRequest(); HttpContext.Current.Response.Redirect(this.GetAuthorizationLink()); HttpContext.Current.ApplicationInstance.CompleteRequest(); }
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { ClaimsPrincipal claimsPrincipal = (ClaimsPrincipal)HttpContext.Current.User; String[] userPermissions = null; foreach (Claim claim in claimsPrincipal.Claims) { if (claim.Type == userPermissionClaimName) { userPermissions = claim.Value.Split(new String[] { "," }, StringSplitOptions.RemoveEmptyEntries); } } if (userPermissions != null) { foreach (String p in permissions) { if (userPermissions.Contains(p)) { return(true); } } } return(false); }
public virtual void Handle(HttpContextBase context) { string action = context.Request["action"]; try { if (!Handlers.ContainsKey(action)) throw new InvalidOperationException("Couln't find any handler for the action: " + action); IAjaxService service = Handlers[action]; if (service.RequiresEditAccess && !security.IsEditor(context.User)) throw new PermissionDeniedException(null, context.User); if (!service.IsValidHttpMethod(context.Request.HttpMethod)) throw new HttpException((int)HttpStatusCode.MethodNotAllowed, "This service requires HTTP POST method"); service.Handle(context); } catch (Exception ex) { Logger.ErrorFormat("AJAX {0}: {1}", action, ex.Message); context.Response.Status = ((int)HttpStatusCode.InternalServerError).ToString() + " Internal Server Error"; context.Response.Write(WriteException(ex, context.User)); } }
public static ShopifyAuthorizationState GetAuthorizationState(System.Web.HttpContextBase httpContext) { string shopname = httpContext.Request.QueryString.Get("shop"); if (shopname == null) { return(httpContext.Session[AuthSessionKey] as ShopifyAuthorizationState); } shopname = shopname.Replace(".myshopify.com", String.Empty); try { Logger.Log("Grabbing auth state from database"); return(Graph.Instance.Cypher .Match("(auth:ShopifyAuth)") .Where((ShopifyAuthorizationState auth) => auth.ShopName == shopname) .Return(auth => auth.As <ShopifyAuthorizationState>()) .Results.Single()); } catch { return(httpContext.Session[AuthSessionKey] as ShopifyAuthorizationState); } }
protected override bool AuthorizeCore(HttpContextBase httpContext) { bool authorized = false; if (httpContext.Session["username"] != null) { if (Roles.ToString() != "") { if (httpContext.Session["Role"].ToString().Equals("Super Admin") || httpContext.Session["Role"].ToString().Equals("Manager")) authorized = true; else { authorized = false; } } else { authorized = true; } } if (!authorized) { // The user is not authorized => no need to go any further return false; } return true; }
internal static IDictionary<UnityPerWebRequestLifetimeManager, object> GetInstances(HttpContextBase httpContext) { IDictionary<UnityPerWebRequestLifetimeManager, object> instances; if (httpContext.Items.Contains(Key)) { instances = (IDictionary<UnityPerWebRequestLifetimeManager, object>)httpContext.Items[Key]; } else { lock (httpContext.Items) { if (httpContext.Items.Contains(Key)) { instances = (IDictionary<UnityPerWebRequestLifetimeManager, object>)httpContext.Items[Key]; } else { instances = new Dictionary<UnityPerWebRequestLifetimeManager, object>(); httpContext.Items.Add(Key, instances); } } } return instances; }
/// <summary> /// Gets current page. /// </summary> /// <returns>Current page object.</returns> public IPage GetCurrentPage(HttpContextBase httpContext) { // TODO: remove it or optimize it. var http = new HttpContextTool(httpContext); var virtualPath = HttpUtility.UrlDecode(http.GetAbsolutePath()); return GetPageByVirtualPath(virtualPath) ?? new Page(); // TODO: do not return empty page, should implemented another logic. }
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { Debug.WriteLine(httpContext.Request.HttpMethod == "GET"); return httpContext.Request.UserAgent != null && httpContext.Request.UserAgent.Contains(requiredUserAgent); }
public ActionResult Process(HttpContextBase context, AuthenticateCallbackData model) { if (model.Exception != null) throw model.Exception; var client = model.AuthenticatedClient; var username = client.UserInformation.UserName; FormsAuthentication.SetAuthCookie(username, false); context.Response.AppendCookie(new HttpCookie("AccessToken", client.AccessToken.SecretToken) { Secure = !context.IsDebuggingEnabled, HttpOnly = true }); var urlHelper = new UrlHelper(((MvcHandler)context.Handler).RequestContext); var redirectUrl = string.Format("/{0}/", username); var cookie = context.Request.Cookies["returnUrl"]; if (cookie != null && urlHelper.IsLocalUrl(cookie.Value)) { redirectUrl = cookie.Value; cookie.Expires = DateTime.Now.AddDays(-1); context.Response.Cookies.Add(cookie); } return new RedirectResult(redirectUrl); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { try { string url = httpContext.Request.Path; url = url.Substring(0, url.IndexOf("?") > 1 ? url.IndexOf("?") : url.Length); HttpCookie authcookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authcookie == null) { string token = httpContext.Request.Form["token"].ToString(); XXF.BasicService.CertCenter.CertCenterProvider ccp = new XXF.BasicService.CertCenter.CertCenterProvider(XXF.BasicService.CertCenter.ServiceCertType.manage); if (ccp.Auth(token)) { return true; } return false; } try { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authcookie.Value); string userid = ticket.Name.Split(' ').FirstOrDefault(); return true; } catch { return false; } } catch { return false; } }
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { var Authorized = base.AuthorizeCore(httpContext); AccessDenied = false; if (Authorized) { HttpContext.Current.Session[session.MenuId] = MenuId; ContextContainer Context = new ContextContainer(); MenuService menuService = new MenuService(Context); Authorized = menuService.IsUserInMenu(MenuId); //foreach (var menuId in MenuId) //{ // Authorized = menuService.IsMenuInRole(Context.CompanyId ?? 0, menuId); // if (Authorized) // break; //} AccessDenied = !Authorized; } return(Authorized); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { if (!httpContext.User.Identity.IsAuthenticated) return false; return httpContext.User.IsInRole(Roles); }
public void SetChatMessageRead(string ChatGroupId, int UserChatGroupId = 0) { System.Web.HttpContextBase httpContext = Context.Request.GetHttpContext(); int UserId = 0; HttpCookie auth_cookie = httpContext.Request.Cookies[Cookies.UserId]; if (auth_cookie != null) { UserId = Convert.ToInt32(auth_cookie.Value); } bool IsRead = ChatBLL.Instance.SetChatMessageRead(ChatGroupId, UserId, UserChatGroupId).Object; List <int> userIds = new List <int>(); if (SingletonUserChatGroups.Instance.ChatGroups.Where(m => m.ChatGroupId == ChatGroupId).Any()) { userIds = SingletonUserChatGroups.Instance.ChatGroups .Where(m => m.ChatGroupId == ChatGroupId) .FirstOrDefault() .ChatUsers //.Where(m => m.UserId.Value != UserId) .Select(m => m.UserId.Value) .ToList(); } Clients.Group(ChatGroupId).SetChatMessageReadCallback(new ActionOutput <string> { Status = ActionStatus.Successfull, Object = ChatGroupId + "`" + (IsRead ? "1" : "0"), Message = string.Join(",", userIds) }); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { bool isAdmin = false; var isAuthorized = base.AuthorizeCore(httpContext); if (!isAuthorized) { // the user is either not authenticated or // not in roles => no need to continue any further return false; } // get the currently logged on user var username = httpContext.User.Identity.Name; // get the id of the article that he is trying to manipulate // from the route data (this assumes that the id is passed as a route // data parameter: /foo/edit/123). If this is not the case and you // are using query string parameters you could fetch the id using the Request //var id = httpContext.Request.RequestContext.RouteData.Values["id"] as string; // Now that we have the current user and the id of the article he // is trying to manipualte all that's left is go ahead and look in // our database to see if this user is the owner of the article HLGranite.Mvc.Models.hlgraniteEntities db = new HLGranite.Mvc.Models.hlgraniteEntities(); HLGranite.Mvc.Models.User user = db.Users.Where(u => u.UserName.Equals(username)).FirstOrDefault(); if (user != null) isAdmin = user.IsAdmin; return isAdmin; }
public void CloseChat(string chatGroupId) { System.Web.HttpContextBase httpContext = Context.Request.GetHttpContext(); int UserId = 0; HttpCookie auth_cookie = httpContext.Request.Cookies[Cookies.UserId]; if (auth_cookie != null) { UserId = Convert.ToInt32(auth_cookie.Value); } // Finding correct chat group in which message suppose to be posted. ChatGroup chatGroup = SingletonUserChatGroups.Instance.ChatGroups.Where(m => m.ChatGroupId == chatGroupId).FirstOrDefault(); if (chatGroup != null) { chatGroup.ChatUsers.Where(m => m.UserId == UserId).FirstOrDefault().ChatClosed = true; if (chatGroup.ChatUsers.Where(m => m.ChatClosed).Count() == chatGroup.ChatUsers.Count()) { // Remove group from list because all users has closed the chat. SingletonUserChatGroups.Instance.ChatGroups.Remove(chatGroup); Clients.Group(chatGroupId).closeChatCallback(new ActionOutput <bool> { Status = ActionStatus.Successfull, Object = true }); } Clients.Group(chatGroupId).closeChatCallback(new ActionOutput <bool> { Status = ActionStatus.Successfull, Object = false, Message = chatGroupId }); } }
public void RequestAuthentication(System.Web.HttpContextBase context, Uri returnUrl) { string url = baseUrl + appId + "&redirect_uri=" + HttpUtility.UrlEncode(returnUrl.ToString()) + "&scope=" + scope; context.Response.Redirect(url); }
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { if (routeDirection == RouteDirection.UrlGeneration) { return true; } object versionValue; if (!values.TryGetValue(parameterName, out versionValue)) { return true; } if (versionValue == null || versionValue == UrlParameter.Optional) { return true; } string versionText = versionValue.ToString(); if (versionText.Length == 0) { return true; } SemanticVersion ignored; return SemanticVersion.TryParse(versionText, out ignored); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } else { if (httpContext.User.Identity.IsAuthenticated) { string strOwnerPermission; if (httpContext.Session["Permissons"] == null) { FormsIdentity formId = (FormsIdentity)httpContext.User.Identity; FormsAuthenticationTicket Ticket = formId.Ticket; var userdata = Encoding.Default.GetString(Convert.FromBase64String(Ticket.UserData)); strOwnerPermission = userdata; httpContext.Session["Permissons"] = Ticket.UserData; } else { strOwnerPermission = httpContext.Session["Permissons"].ToString(); } //if (strOwnerPermission == Permissons) return true; } httpContext.Response.StatusCode = 403; return false; } }
public bool IsSessionEnabled(HttpContext context) { // try to get the session store service from DI var sessionStore = context.RequestServices.GetService(typeof(ISessionStore)); return(sessionStore != null); }
/// <summary> /// Ensures that the user must be logged in or that the application is not configured just yet. /// </summary> /// <param name="httpContext"></param> /// <returns></returns> protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } try { //if its not configured then we can continue if (!_applicationContext.IsConfigured) { return true; } //otherwise we need to ensure that a user is logged in var isLoggedIn = BasePage.ValidateUserContextID(BasePage.umbracoUserContextID); if (isLoggedIn) { return true; } return false; } catch (Exception) { return false; } }
public bool AddToBasket(HttpContextBase httpContext, int productId, int quantity) { bool success = true; Basket basket = GetBasket(httpContext); BasketItem item = basket.BasketItems.FirstOrDefault(i => i.ProductId == productId); if (item == null) { item = new BasketItem() { BasketId = basket.BasketId, ProductId = productId, Quantity = quantity }; basket.AddBasketItem(item); } else { item.Quantity = item.Quantity + quantity; } baskets.Commit(); return success; }
public void InsertViewLocation(HttpContextBase httpContext, string key, string virtualPath) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } httpContext.Cache.Insert(AlterKey(key), virtualPath, new CacheDependency(HostingEnvironment.MapPath("~/Themes"))); }
protected override void SetCachePolicy(System.Web.HttpContextBase context, DateTime fileChangedDate) { if (!IsRequestComingFromCdn(context)) { base.SetCachePolicy(context, fileChangedDate); return; } var helper = ServiceLocator.Current.GetInstance <ContentRouteHelper>(); if (helper.Content != null) { var cdnString = (string)context.Items[CdnModule.CdnRequest]; var expectedString = CdnModule.Unique(helper.Content); if (!String.Equals(cdnString, expectedString, StringComparison.OrdinalIgnoreCase)) { context.Response.RedirectPermanent("/" + expectedString + context.Request.Url.PathAndQuery); } } context.Response.Cache.SetCacheability(HttpCacheability.Public); context.Response.Cache.SetLastModified(fileChangedDate); context.Response.Cache.SetExpires(DateTime.UtcNow + _cdnExpiration.Value); context.Response.Cache.SetValidUntilExpires(true); context.Response.Cache.VaryByParams.IgnoreParams = true; context.Response.Cache.SetOmitVaryStar(true); context.Response.Cache.SetNoServerCaching(); }
public override ClaimsIdentity ProcessSignInResponse(string realm, string originalUrl, HttpContextBase httpContext) { var client = new FacebookClient(this.applicationId, this.secret); AuthenticationResult result; try { result = client.VerifyAuthentication(httpContext, this.MultiProtocolIssuer.ReplyUrl); } catch (WebException wex) { throw new InvalidOperationException(new StreamReader(wex.Response.GetResponseStream()).ReadToEnd(), wex); } var claims = new List<Claim> { new Claim(System.IdentityModel.Claims.ClaimTypes.NameIdentifier, result.ExtraData["id"]) }; foreach (var claim in result.ExtraData) { claims.Add(new Claim("http://schemas.facebook.com/me/" + claim.Key, claim.Value)); } return new ClaimsIdentity(claims, "Facebook"); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { if (!base.AuthorizeCore(httpContext)) return false; return Permission.IsEmptyOrNull() || Authorization.HasPermission(Permission); }
public override RouteData GetRouteData(System.Web.HttpContextBase httpContext) { var virtualPath = httpContext.Request.AppRelativeCurrentExecutionFilePath + httpContext.Request.PathInfo;//获取相对路径 // ~/mingrenmingyan/page-3 virtualPath = virtualPath.Substring(2).Trim('/');//此时URL //判断是否是我们需要处理的URL,不是则返回null,匹配将会继续进行。 if (!Validate.IsNavUrl(virtualPath)) { return(null); } var PageIndex = virtualPath.Split('/').Last().Split('-').Last(); var Navigationname = virtualPath.Split('/').First(); //尝试根据分类名称获取相应分类,忽略大小写 var Navigation = navigationApp.GetEntityByEnCode(Navigationname, a => a.F_EnabledMark == true); if (Navigation == null)//如果分类是null,可能不是我们要处理的URL,返回null,让匹配继续进行 { return(null); } //至此可以肯定是我们要处理的URL了 var data = new RouteData(this, new MvcRouteHandler());//声明一个RouteData,添加相应的路由值 data.Values.Add("controller", "Navigation"); data.Values.Add("action", "index"); data.Values.Add("id", Navigation.F_EnCode); data.Values.Add("pageIndex", PageIndex); return(data);//返回这个路由值将调用NavigationController.Index(Navigation.CategoeyID)方法。匹配终止 }
internal UrlBuilder(HttpContextBase httpContext, VirtualPathUtilityBase virtualPathUtility, string path, object parameters) { _virtualPathUtility = virtualPathUtility; Uri uri; if (Uri.TryCreate(path, UriKind.Absolute, out uri)) { _path = uri.GetLeftPart(UriPartial.Path); _params.Append(uri.Query); } else { // If the url is being built as part of a WebPages request, use the template stack to identify the current template's virtual path. _path = GetPageRelativePath(httpContext, path); int queryStringIndex = (_path ?? String.Empty).IndexOf('?'); if (queryStringIndex != -1) { _params.Append(_path.Substring(queryStringIndex)); _path = _path.Substring(0, queryStringIndex); } } if (parameters != null) { AddParam(parameters); } }
public async Task<bool> CreateAndSignInExternalUser( HttpContextBase context, string logOnProvider, IUser user, string role, bool persist) { if (user == null) { throw new ArgumentNullException("user"); } var identity = await GetExternalIdentity(context); if (!VerifyExternalIdentity(identity, logOnProvider)) { return false; } var providerKey = identity.FindFirstValue( "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"); if (!(await storeManager.CreateExternalUser( user, logOnProvider, providerKey, role))) { return false; } await SignIn(context, user.Id, identity.Claims, persist); return true; }
public override RouteData GetRouteData(System.Web.HttpContextBase httpContext) { //如果HttpHandler为NULL,则不处理 if (httpContext.Handler != null) { return(null); } //请求Url的绝对路径 string filePath = httpContext.Request.Url.AbsolutePath; if (filePath.IsEmpty()) { return(null); } filePath = filePath.ToLower(); var endPage = filePath.RightOfRightmostOf('/'); if (endPage.IsNotEmpty() && endPage.Contains("?")) { endPage = endPage.Split('?')[0]; } var routeWebHander = GlobalApplicationObject.Current.ApplicationContext.RoutingManager.RouteWebHandlerInfoList.FirstOrDefault(p => p.routeUrl == filePath); if (routeWebHander.IsNotNull()) { var routeHandler = new RouteHandler() { RouteWebHandlerInfo = routeWebHander }; var data = new RouteData(this, routeHandler); return(data); } return(null); }
public override RouteData GetRouteData(HttpContextBase httpContext) { // locate appropriate shell settings for request var settings = _runningShellTable.Match(httpContext); // only proceed if there was a match, and it was for this client if (settings == null || settings.Name != _shellSettings.Name) return null; var effectiveHttpContext = httpContext; if (_urlPrefix != null) effectiveHttpContext = new UrlPrefixAdjustedHttpContext(httpContext, _urlPrefix); var routeData = _route.GetRouteData(effectiveHttpContext); if (routeData == null) return null; // otherwise wrap handler and return it routeData.RouteHandler = new RouteHandler(_workContextAccessor, routeData.RouteHandler, SessionState); routeData.DataTokens["IWorkContextAccessor"] = _workContextAccessor; if (IsHttpRoute) { routeData.Values["IWorkContextAccessor"] = _workContextAccessor; // for WebApi } return routeData; }
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { bool authorize = false; if (System.Web.HttpContext.Current.Request.Cookies.AllKeys.Contains("UserCookie")) { HttpCookie cookie = HttpContext.Current.Request.Cookies["UserCookie"]; int UserId = Convert.ToInt32(cookie.Values["Id"]); if (UserId != 0) { if (allowedroles.Length > 0) { foreach (var role in allowedroles) { //var user = db.Kullanicilar.Where(m => m.kullaniciID == kullaniciBilgileri.kullaniciID && m.rol.rolAdi == role); var user = db.Users.Where(m => m.Id == UserId); if (user.Count() > 0) { authorize = true; /* return true if Entity has current user(active) with specific role */ } } } else { authorize = true; } } } return(authorize); //} //return base.AuthorizeCore(httpContext); }
private static string GenerateClientUrlInternal(HttpContextBase httpContext, string contentPath) { if (String.IsNullOrEmpty(contentPath)) { return contentPath; } // can't call VirtualPathUtility.IsAppRelative since it throws on some inputs bool isAppRelative = contentPath[0] == '~'; if (isAppRelative) { string absoluteContentPath = VirtualPathUtility.ToAbsolute(contentPath, httpContext.Request.ApplicationPath); string modifiedAbsoluteContentPath = httpContext.Response.ApplyAppPathModifier(absoluteContentPath); return GenerateClientUrlInternal(httpContext, modifiedAbsoluteContentPath); } // we only want to manipulate the path if URL rewriting is active for this request, else we risk breaking the generated URL bool wasRequestRewritten = _urlRewriterHelper.WasRequestRewritten(httpContext); if (!wasRequestRewritten) { return contentPath; } // Since the rawUrl represents what the user sees in his browser, it is what we want to use as the base // of our absolute paths. For example, consider mysite.example.com/foo, which is internally // rewritten to content.example.com/mysite/foo. When we want to generate a link to ~/bar, we want to // base it from / instead of /foo, otherwise the user ends up seeing mysite.example.com/foo/bar, // which is incorrect. string relativeUrlToDestination = MakeRelative(httpContext.Request.Path, contentPath); string absoluteUrlToDestination = MakeAbsolute(httpContext.Request.RawUrl, relativeUrlToDestination); return absoluteUrlToDestination; }
public WebWorkContext(HttpContextBase httpContext, ICustomerService customerService, IVendorService vendorService, IStoreContext storeContext, IAuthenticationService authenticationService, ILanguageService languageService, ICurrencyService currencyService, IGenericAttributeService genericAttributeService, TaxSettings taxSettings, CurrencySettings currencySettings, LocalizationSettings localizationSettings, IUserAgentHelper userAgentHelper, IStoreMappingService storeMappingService) { this._httpContext = httpContext; this._customerService = customerService; this._vendorService = vendorService; this._storeContext = storeContext; this._authenticationService = authenticationService; this._languageService = languageService; this._currencyService = currencyService; this._genericAttributeService = genericAttributeService; this._taxSettings = taxSettings; this._currencySettings = currencySettings; this._localizationSettings = localizationSettings; this._userAgentHelper = userAgentHelper; this._storeMappingService = storeMappingService; }
public CultureSelectorResult GetCulture(HttpContextBase context) { if (context == null || ContextHelpers.IsRequestAdmin(context)) return null; // Attempt to determine culture by previous route if by POST string path; if (context.Request.HttpMethod.Equals(HttpVerbs.Post.ToString(), StringComparison.OrdinalIgnoreCase)) { if (context.Request.UrlReferrer != null) path = context.Request.UrlReferrer.AbsolutePath; else return null; } else { path = context.Request.Path; } var appPath = context.Request.ApplicationPath ?? "/"; var requestUrl = (path.StartsWith(appPath) ? path.Substring(appPath.Length) : path).TrimStart('/'); var content = GetByPath(requestUrl); if (content != null) { return new CultureSelectorResult { Priority = -2, CultureName = _localizationService.Value.GetContentCulture(content) }; } return null; }
public AuthenticationResult VerifyAuthentication(System.Web.HttpContextBase context) { string code = context.Request.QueryString["code"]; string rawUrl = context.Request.Url.OriginalString; //From this we need to remove code portion rawUrl = Regex.Replace(rawUrl, "&code=[^&]*", ""); IDictionary <string, string> userData = GetUserData(code, rawUrl); if (userData == null) { return(new AuthenticationResult(false, ProviderName, null, null, null)); } string id = userData["id"]; string username = userData["username"]; userData.Remove("id"); userData.Remove("username"); AuthenticationResult result = new AuthenticationResult(true, ProviderName, id, username, userData); return(result); }
protected override bool AuthorizeCore(HttpContextBase httpContext) { if (!CheckAuthToken(httpContext.Request.Headers)) return false; return base.AuthorizeCore(httpContext); }
public Subject GetCurrentSubject(PageItem pageItem, HttpContextBase httpContext) { var subjectId = httpContext.Request.RawUrl; if (httpContext.Items["Comments.SubjectId"] != null) { subjectId = httpContext.Items["Comments.SubjectId"].ToString(); } var subject = new Subject { Id = subjectId }; var page = httpContext.CurrentHandler as Page; if (page != null) { subject.Title = page.Title; } if (httpContext.Items["Comments.SubjectTitle"] != null) { subject.Title = httpContext.Items["Comments.SubjectTitle"].ToString(); } if (httpContext.Items["Comments.SubjectType"] != null) { subject.Type = httpContext.Items["Comments.SubjectType"].ToString(); } return subject; }
protected override string RenderJsDependencies(IEnumerable<IClientDependencyFile> jsDependencies, HttpContextBase http, IDictionary<string, string> htmlAttributes) { if (!jsDependencies.Any()) return string.Empty; var sb = new StringBuilder(); if (http.IsDebuggingEnabled || !EnableCompositeFiles) { foreach (var dependency in jsDependencies) { sb.Append(RenderSingleJsFile(dependency.FilePath, htmlAttributes)); } } else { var comp = ClientDependencySettings.Instance.DefaultCompositeFileProcessingProvider.ProcessCompositeList(jsDependencies, ClientDependencyType.Javascript, http); foreach (var s in comp) { sb.Append(RenderSingleJsFile(s, htmlAttributes)); } } return sb.ToString(); }
public string GetViewLocation(HttpContextBase httpContext, string key) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } return (string)httpContext.Cache[AlterKey(key)]; }
// This is the important part. Everything else is either inherited from AuthorizeAttribute or, in the case of private or internal members, copied from AuthorizeAttribute. protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } IPrincipal user = httpContext.User; if (user == null || user.Identity == null || !user.Identity.IsAuthenticated) { return(false); } if (_usersSplit.Length > 0 && _usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) { return(false); } if (_rolesSplit.Length > 0 && _rolesSplit.Any(user.IsInRole)) { return(false); } return(true); }
/// <summary> /// 设置消息树到当前请求头 /// </summary> /// <param name="http"></param> /// <param name="context"></param> public static void SetCatContextToRequestHeader(System.Web.HttpContextBase http, CatContext context) { if (http.Request.Headers.GetValues("catContext") != null && http.Request.Headers.GetValues("catContext").Length > 0) { http.Request.Headers.Remove("catContext"); } http.Request.Headers.Add("catContext", Lind.DDD.Utils.SerializeMemoryHelper.SerializeToJson(context)); }
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { bool isAuthorized = base.AuthorizeCore(httpContext); httpContext.Items.Add(IS_AUTHORIZED, isAuthorized); return(isAuthorized); }
public static ReportingService2010 ReportWebServiceInstance(System.Web.HttpContextBase httpContext) { if (instance == null) { instance = (ReportingService2010)httpContext.Session[REPORTSERVERNAME]; } return(instance); }
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { bool?result = AuthorizationBehavior == null ? null : AuthorizationBehavior.OverrideAuthorize(this, httpContext); return(result.HasValue ? result.Value : base.AuthorizeCore(httpContext)); }
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { if (!CurrentRequestData.CurrentContext.Request.IsLocal && CurrentRequestData.SiteSettings.AllowedIPs.Any() && !CurrentRequestData.SiteSettings.AllowedIPs.Contains(CurrentRequestData.CurrentContext.GetCurrentIP())) { return(false); } return(base.AuthorizeCore(httpContext)); }
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { if (UserSession.IsLogin() && UserSession.IsAdmin()) { return(true); } return(false); }
public void RequestAuthentication(System.Web.HttpContextBase context, Uri returnUrl) { RavenRequest ravenRequest = new RavenRequest(); ravenRequest.Parameters.Add("url", returnUrl.AbsoluteUri); //string url = baseUrl + "&redirect_uri=" + HttpUtility.UrlEncode(returnUrl.ToString()); string url = String.Format("{0}{1}{2}", this.BaseURL, RAVEN_AUTHENTICATE, ravenRequest.ToString()); context.Response.Redirect(url); }
public void HubContext() { String connectionID = Context.ConnectionId; //System.Collections.Specialized.NameValueCollection queryString = Context.Request.QueryString; //string parameterValue = queryString["parametername"]; System.Collections.Generic.IDictionary <string, Cookie> cookies = Context.Request.Cookies; System.Security.Principal.IPrincipal user = Context.User; System.Web.HttpContextBase httpContext = Context.Request.GetHttpContext(); }
/// <summary> /// Test to see if the current http context is authorized for access to Shopify API /// </summary> /// <param name="httpContext">current httpContext</param> /// <returns>true if the current http context is authorized for access to Shopify API, otherwise false</returns> protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { var authState = httpContext.Session["shopify_auth_state"] as ShopifyAuthorizationState; if (authState == null || String.IsNullOrWhiteSpace(authState.AccessToken)) { return(false); } return(true); }
protected override bool Match(System.Web.HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { var baseMatch = base.Match(httpContext, route, parameterName, values, routeDirection); if (!baseMatch && routeDirection == RouteDirection.IncomingRequest) { baseMatch = AllowedMethods.Any(method => string.Equals(method, httpContext.Request.RequestType, StringComparison.OrdinalIgnoreCase)); } return(baseMatch); }
/// <summary> /// Test to see if the current http context is authorized for access to Shopify API /// </summary> /// <param name="httpContext">current httpContext</param> /// <returns>true if the current http context is authorized for access to Shopify API, otherwise false</returns> protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) { var authState = GetAuthorizationState(httpContext); if (authState == null || String.IsNullOrWhiteSpace(authState.AccessToken)) { return(false); } return(true); }
public static bool IsSessionExpired(System.Web.HttpContextBase httpContext) { var rs = ReportWebServiceInstance(httpContext); if (rs == null) { return(true); } return(false); }