Exemple #1
0
        public override void ExecuteResult(ControllerContext context)
        {
            FormsAuthentication.SignOut();
            var redirectResult = new RedirectResult("~/");

            redirectResult.ExecuteResult(context);
        }
        public ActionResult Auhorize(AppState passedAppState)
        {
            passedAppState.AppIsAuthorized = false;

            // hit the common endpoint for authorization,
            // after authorization we will use the tenant specific endpoint for getting app-only tokens
            UriBuilder authorizeRequest = new UriBuilder(appConfig.AuthorizationUri);

            // Maintain state for authorize request to prvenet cross forgery attacks
            var authstate = Guid.NewGuid().ToString();

            Session[AppSessionVariables.AuthState] = authstate;

            authorizeRequest.Query =
                "state=" + authstate +
                "&response_type=code+id_token" +
                "&scope=openid" +
                "&nonce=" + Guid.NewGuid().ToString() +
                "&client_id=" + appConfig.ClientId +
                "&redirect_uri=" + HttpUtility.UrlEncode(appConfig.RedirectUri) +
                "&resource=" + HttpUtility.UrlEncode(appConfig.GraphResourceUri) +
#if DEBUG
                "&login_hint=" + appConfig.DebugOffice365User +
#endif
                "&prompt=admin_consent" +
                "&response_mode=form_post";

            RedirectResult result = Redirect(authorizeRequest.Uri.ToString());
            result.ExecuteResult(this.ControllerContext);

            return(View("Index", passedAppState));
        }
Exemple #3
0
        public override void ExecuteResult(ControllerContext context)
        {
            var manager = ReturnUrlManagerFactory.GetDefault();
            var result  = new RedirectResult(manager.GetReturnUrl());

            result.ExecuteResult(context);
        }
Exemple #4
0
        public override void ExecuteResult(ControllerContext context)
        {
            FormsAuthentication.SetAuthCookie(UserName, true);
            var redirectResult = new RedirectResult("~/");

            redirectResult.ExecuteResult(context);
        }
        void IRule.ApplyRule(RewriteContext context)
        {
            var  request   = context.HttpContext.Request;
            bool wasSecure = Rewrite(request);

            if (!wasSecure && _httpsPolicy == HttpsPolicy.Required)
            {
                var newUrl = string.Concat(
                    "https://",
                    request.Host.ToUriComponent(),
                    request.PathBase.ToUriComponent(),
                    request.Path.ToUriComponent(),
                    request.QueryString.ToUriComponent());

                var action = new RedirectResult(newUrl);

                ActionContext actionContext = new ActionContext()
                {
                    HttpContext = context.HttpContext
                };

                action.ExecuteResult(actionContext);
                context.Result = RuleResult.EndResponse;
            }
        }
Exemple #6
0
        public void ExecuteResultCallsResponseRedirect()
        {
            // Arrange
            Mock <HttpResponseBase> mockResponse = new Mock <HttpResponseBase>();

            mockResponse
            .Setup(
                o =>
                o.Redirect(
                    _baseUrl,
                    false         /* endResponse */
                    )
                )
            .Verifiable();
            Mock <HttpContextBase> mockContext = new Mock <HttpContextBase>();

            mockContext.Setup(o => o.Response).Returns(mockResponse.Object);
            ControllerContext context = new ControllerContext(
                mockContext.Object,
                new RouteData(),
                new Mock <ControllerBase>().Object
                );
            var result = new RedirectResult(_baseUrl);

            // Act
            result.ExecuteResult(context);

            // Assert
            mockResponse.Verify();
        }
        private ViewResult RedirectHome()
        {
            RedirectResult result = Redirect(appConfig.RedirectUri);

            result.ExecuteResult(this.ControllerContext);

            return(View("Index", new AppState()));
        }
 public override void OnActionExecuting(ActionExecutingContext filterContext)
 {
     new CabDataContext().ValidateCookie();
     if (LoginHelper.Client == null)
     {
         var result = new RedirectResult("/logout");
         result.ExecuteResult(filterContext.Controller.ControllerContext);
     }
     base.OnActionExecuting(filterContext);
 }
Exemple #9
0
        public void ExecuteResultWithNullControllerContextThrows()
        {
            // Arrange
            var result = new RedirectResult(_baseUrl);

            // Act & Assert
            Assert.ThrowsArgumentNull(
                delegate { result.ExecuteResult(null /* context */); },
                "context");
        }
Exemple #10
0
        public void ExecuteResultWithNullControllerContextThrows() {
            // Arrange
            var result = new RedirectResult(_baseUrl);

            // Act & Assert
            ExceptionHelper.ExpectArgumentNullException(
                delegate {
                    result.ExecuteResult(null /* context */);
                },
                "context");
        }
Exemple #11
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            var cookie = HttpContext.Current.Request.Cookies["ValidateUser"];

            if (cookie == null)
            {
                var result = new RedirectResult("/Account/Login");
                result.ExecuteResult(filterContext);
            }
        }
        public async override Task ExecuteResultAsync(ActionContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            _wrapped           = new RedirectResult(await GetUrlAsync());
            _wrapped.Permanent = false;
            _wrapped.ExecuteResult(context);
        }
Exemple #13
0
        public void RedirectInChildActionThrows() {
            // Arrange
            RouteData routeData = new RouteData();
            routeData.DataTokens[ControllerContext.PARENT_ACTION_VIEWCONTEXT] = new ViewContext();
            ControllerContext context = new ControllerContext(new Mock<HttpContextBase>().Object, routeData, new Mock<ControllerBase>().Object);
            RedirectResult result = new RedirectResult(_baseUrl);

            // Act & Assert
            ExceptionHelper.ExpectInvalidOperationException(
                () => result.ExecuteResult(context),
                MvcResources.RedirectAction_CannotRedirectInChildAction
            );
        }
Exemple #14
0
        private static void RedirectWithLanguage(ControllerContext filterContext, RouteValueDictionary values, string language)
        {
            if (!values.ContainsKey("language"))
            {
                values.Add("language", language);
            }

            var helper = new UrlHelper(filterContext.RequestContext);
            var url    = helper.RouteUrl(values);

            var result = new RedirectResult(url);

            result.ExecuteResult(filterContext);
        }
Exemple #15
0
        public void RedirectInChildActionThrows()
        {
            // Arrange
            RouteData routeData = new RouteData();

            routeData.DataTokens[ControllerContext.PARENT_ACTION_VIEWCONTEXT] = new ViewContext();
            ControllerContext context = new ControllerContext(new Mock <HttpContextBase>().Object, routeData, new Mock <ControllerBase>().Object);
            RedirectResult    result  = new RedirectResult(_baseUrl);

            // Act & Assert
            ExceptionHelper.ExpectInvalidOperationException(
                () => result.ExecuteResult(context),
                MvcResources.RedirectAction_CannotRedirectInChildAction
                );
        }
Exemple #16
0
        public void ExecuteResultCallsResponseRedirect() {
            // Arrange
            Mock<HttpResponseBase> mockResponse = new Mock<HttpResponseBase>();
            mockResponse.Expect(o => o.Redirect(_baseUrl, false /* endResponse */));
            Mock<HttpContextBase> mockContext = new Mock<HttpContextBase>();
            mockContext.Expect(o => o.Response).Returns(mockResponse.Object);
            ControllerContext context = new ControllerContext(mockContext.Object, new RouteData(), new Mock<ControllerBase>().Object);
            var result = new RedirectResult(_baseUrl);

            // Act
            result.ExecuteResult(context);

            // Assert
            mockResponse.Verify();
        }
Exemple #17
0
        public void RedirectInChildActionThrows()
        {
            // Arrange
            RouteData routeData = new RouteData();

            routeData.DataTokens[ControllerContext.ParentActionViewContextToken] = new ViewContext();
            ControllerContext context = new ControllerContext(new Mock <HttpContextBase>().Object, routeData, new Mock <ControllerBase>().Object);
            RedirectResult    result  = new RedirectResult(_baseUrl);

            // Act & Assert
            Assert.Throws <InvalidOperationException>(
                () => result.ExecuteResult(context),
                MvcResources.RedirectAction_CannotRedirectInChildAction
                );
        }
Exemple #18
0
        public void Execute_ReturnsContentPath_WhenItDoesNotStartWithTilde(string appRoot,
                                                                           string contentPath,
                                                                           string expectedPath)
        {
            // Arrange
            var httpResponse = new Mock<HttpResponse>();
            httpResponse.Setup(o => o.Redirect(expectedPath, false))
                        .Verifiable();

            var httpContext = GetHttpContext(appRoot, contentPath, expectedPath, httpResponse.Object);
            var actionContext = GetActionContext(httpContext);
            var result = new RedirectResult(contentPath);

            // Act
            result.ExecuteResult(actionContext);

            // Assert
            // Verifying if Redirect was called with the specific Url and parameter flag.
            httpResponse.Verify();
        }
        public ActionResult StartOver(AppState passedAppState)
        {
            if (!IsSessionInProgress())
            {
                return(RedirectHome());
            }

            AppState appState = new AppState();

            Session.Clear();

            UriBuilder signOutRequest = new UriBuilder(appConfig.SignoutUri.Replace("common", passedAppState.TenantId));

            signOutRequest.Query = "post_logout_redirect_uri=" + HttpUtility.UrlEncode(appConfig.RedirectUri);

            RedirectResult result = Redirect(signOutRequest.Uri.ToString());

            result.ExecuteResult(this.ControllerContext);

            return(View("Index", appState));
        }
Exemple #20
0
        public void Execute_ReturnsAppRelativePath_WhenItStartsWithTilde(string appRoot,
                                                                         string contentPath,
                                                                         string expectedPath)
        {
            // Arrange
            var httpResponse = new Mock <HttpResponse>();

            httpResponse.Setup(o => o.Redirect(expectedPath, false))
            .Verifiable();

            var httpContext   = GetHttpContext(appRoot, contentPath, expectedPath, httpResponse.Object);
            var actionContext = GetActionContext(httpContext);
            var result        = new RedirectResult(contentPath);

            // Act
            result.ExecuteResult(actionContext);

            // Assert
            // Verifying if Redirect was called with the specific Url and parameter flag.
            httpResponse.Verify();
        }
Exemple #21
0
        public void LogOnAuthenticateCorrectCredentials()
        {
            AccountController c = new AccountController();

            StringBuilder sb = new StringBuilder();

            this.BuildUpController(c, null, null, sb);

            LogOnModel model = new LogOnModel();

            model.UserName = "******";
            model.Password = "******";

            var result = c.LogOn(model, "ret");

            Assert.IsInstanceOf <RedirectResult>(result);

            RedirectResult redirect = (RedirectResult)result;

            redirect.ExecuteResult(c.ControllerContext);

            Assert.AreEqual(redirect.Url, "ret");
        }
        /// <summary>
        /// 验证权限(action执行前会先执行这里)
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (Role == "*")
            {
                var session = SessionInfo.GetSession();
                if (session == null)
                {
                    RedirectResult redirectResult = new RedirectResult("/error?c=身份已过期, 请您重新登录");
                    filterContext.Result = redirectResult;
                    redirectResult.ExecuteResult(filterContext);
                }
                return;
            }

            //如果存在身份信息
            if (!SessionInfo.IsLogin)
            {
                ContentResult Content = new ContentResult();
                Content.Content      = "<script type='text/javascript'>alert('请先登录!');location.href='/bootstrap/index';</script>";
                filterContext.Result = Content;
            }
            else
            {
                var      permissions           = SessionInfo.GetSession().UserDetail.Permissions;
                string[] permissionArray       = permissions.Select(item => item.RoleName).ToArray();
                string   permissionJoinStrings = string.Join(",", permissionArray);
                var      isContains            = Role.Contains(permissionJoinStrings);
                if (!isContains)//验证权限
                {
                    //验证不通过
                    ContentResult Content = new ContentResult();
                    Content.Content      = "<script type='text/javascript'>alert('您没有权限访问!');location.href='/bootstrap/index';</script>";
                    filterContext.Result = Content;
                }
            }
        }
Exemple #23
0
        public void Execute_Calls_TempDataKeep()
        {
            // Arrange
            var tempData = new Mock <ITempDataDictionary>();

            tempData.Setup(t => t.Keep()).Verifiable();

            var httpContext = new Mock <HttpContext>();

            httpContext.Setup(o => o.Response).Returns(new Mock <HttpResponse>().Object);
            httpContext.Setup(o => o.RequestServices.GetService(typeof(ITempDataDictionary))).Returns(tempData.Object);
            var actionContext = GetActionContext(httpContext.Object);

            var result = new RedirectResult("url")
            {
                UrlHelper = Mock.Of <IUrlHelper>()
            };

            // Act
            result.ExecuteResult(actionContext);

            // Assert
            tempData.Verify(t => t.Keep(), Times.Once());
        }
        public void RedirectInChildActionThrows()
        {
            // Arrange
            RouteData routeData = new RouteData();
            routeData.DataTokens[ControllerContext.ParentActionViewContextToken] = new ViewContext();
            ControllerContext context = new ControllerContext(new Mock<HttpContextBase>().Object, routeData, new Mock<ControllerBase>().Object);
            RedirectResult result = new RedirectResult(_baseUrl);

            // Act & Assert
            Assert.Throws<InvalidOperationException>(
                () => result.ExecuteResult(context),
                MvcResources.RedirectAction_CannotRedirectInChildAction
                );
        }
        //
        // GET: /Home/
        public async Task <ActionResult> Index()
        {
            // Force SSL
            if (!Request.IsSecureConnection)
            {
                string         httplength   = "http";
                string         nonsecureurl = Request.Url.AbsoluteUri.Substring(httplength.Length);
                string         secureurl    = String.Format("https{0}", nonsecureurl);
                RedirectResult result       = Redirect(secureurl);
                result.ExecuteResult(this.ControllerContext);
            }

            // This is where state of the app is maintained and data passed between view and controller
            AppState appState = new AppState();

            // Authorization back from AAD in a form post as requested in the authorize request
            if (Request.Form != null)
            {
                // Did it return with an error?
                if (!String.IsNullOrEmpty(Request.Form["error"]))
                {
                    appState.ErrorMessage    = Request.Form["error"];
                    appState.AppIsAuthorized = false;

                    return(View(appState));
                }

                // Authorized without error: Check to see if we have an ID token
                if (String.IsNullOrEmpty(Request.Form["id_token"]))
                {
                    appState.AppIsAuthorized = false;
                }
                else
                {
                    // Was it correlated with authorize request
                    var authstate = Session[AppSessionVariables.AuthState] as String;
                    Session[AppSessionVariables.AuthState] = null;
                    if (String.IsNullOrEmpty(authstate))
                    {
                        appState.ErrorMessage    = "Oops. Something went wrong with the authorization state (No auth state). Please retry.";
                        appState.AppIsAuthorized = false;

                        return(View(appState));
                    }
                    if (!Request.Form["state"].Equals(authstate))
                    {
                        appState.ErrorMessage    = "Oops. Something went wrong with the authorization state (Invalid auth state). Please retry.";
                        appState.AppIsAuthorized = false;

                        return(View(appState));
                    }

                    // Get the TenantId out of the ID Token to address tenant specific token endpoint.
                    // No validation of ID Token as the only info we need is the tenantID
                    // If for any case your app wants to use the ID Token to authenticate
                    // it must be validated.
                    JwtToken openIDToken = GetTenantId(Request.Form["id_token"]);
                    appState.TenantId     = openIDToken.tid;
                    appState.TenantDomain = openIDToken.domain;
                    appState.LoggedOnUser = openIDToken.upn;

                    appState.AppIsAuthorized = true;
                }
            }

            if (appState.AppIsAuthorized)
            {
                // Get app-only access tokens ....
                try
                {
                    // Get an app-only access token for the AAD Graph Rest APIs
                    var authResult = await GetAppOnlyAccessToken(appConfig.GraphResourceUri, appState.TenantId);

                    // Get list of users in this Tenant from AAD Graph to fill drop down with smtp addresses
                    List <GraphUser> users = GetUsers(appState.TenantId, authResult.AccessToken);

                    appState.MailboxList        = this.BuildMailboxDropDownList(string.Empty, users);
                    appState.MailboxSmtpAddress = appState.MailboxList.SelectedValue as String;

                    // For convenience maintain this list as a session
                    Session[AppSessionVariables.MailboxList] = users;

                    // Get app-only access tokens for Exchange Rest APIs
                    authResult = await GetAppOnlyAccessToken(appConfig.ExchangeResourceUri, appState.TenantId);

                    appState.AccessToken = authResult.AccessToken;
                    appState.AccessTokenAquiredWithoutError = true;

                    SetSessionInProgress();
                }
                catch (Exception ex)
                {
                    appState.ErrorMessage = ex.Message;
                }
            }

            return(View(appState));
        }
        public void Execute_Calls_TempDataKeep()
        {
            // Arrange
            var tempData = new Mock<ITempDataDictionary>();
            tempData.Setup(t => t.Keep()).Verifiable();

            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(o => o.Response).Returns(new Mock<HttpResponse>().Object);
            httpContext.Setup(o => o.RequestServices.GetService(typeof(ITempDataDictionary))).Returns(tempData.Object);
            var actionContext = GetActionContext(httpContext.Object);

            var result = new RedirectResult("url")
            {
                UrlHelper = Mock.Of<IUrlHelper>()
            };

            // Act
            result.ExecuteResult(actionContext);

            // Assert
            tempData.Verify(t => t.Keep(), Times.Once());
        }