2012-05-27 3 views
3

특정 작업 세트에 대해 SSL을 요구하는 MVC 4 웹 응용 프로그램이 있으며 지금은 로그인 프로세스가 SSL로 보호되기를 바랍니다.로그인 및 특정 페이지에 대해서만 SSL을 활성화하는 방법 MVC

모든 설정을 마치면 Login 페이지의 redirectToUrl 매개 변수가 스키마를 지정하지 않기 때문에 로그인이 필요한 모든 페이지가 [RequireHttps] 속성에 관계없이 https로 리디렉션됩니다. 이 아닙니다).

내가 RequireHttps 속성으로 혼합 된 콘텐츠를 장식하지 않은 페이지는 사용자에게 혼란을주는 일반적인 브라우저 경고를 유발하므로 피해야합니다.

이 문제를 해결할 방법이 있습니까? 로그인 액션에서 스키마를 가져 오는 것을 생각했지만, 상대 경로 인 returnUrl 매개 변수를 제외하고는 원래 요청에 대한 참조를 찾을 수 없었습니다.

내가 찾은 참조는 https가 필요없는 모든 작업을 꾸미기 위해 creating a custom attribute이지만 이보다 더 건조한 것이 있습니까?

+0

HttpsNotRequired 특성을 반복하지 않으려면베이스 컨트롤러를 꾸미기 위해 사용할 수 있습니다. 그래도 더 멋진 솔루션이 있는지 궁금해하고 있습니다. – eddo

답변

2

음, 나는 마지막으로 가장 고통 방법을 증명 내 원래의 게시물에 코멘트에 설명 된 솔루션을 선택했다.

public class ExitHttpsIfNotRequiredAttribute : FilterAttribute, IAuthorizationFilter 
    { 
     public void OnAuthorization(AuthorizationContext filterContext) 
     { 
      // abort if it's not a secure connection 
      if (!filterContext.HttpContext.Request.IsSecureConnection) return; 

      // abort if a [RequireHttps] attribute is applied to controller or action 
      if (filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(RequireHttpsAttribute), true).Length > 0) return; 
      if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(RequireHttpsAttribute), true).Length > 0) return; 

      // abort if a [RetainHttps] attribute is applied to controller or action 
      if (filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(RetainHttpsAttribute), true).Length > 0) return; 
      if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(RetainHttpsAttribute), true).Length > 0) return; 

      // abort if it's not a GET request - we don't want to be redirecting on a form post 
      if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) return; 

      // redirect to HTTP 
      string url = "http://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl; 
      filterContext.Result = new RedirectResult(url); 
     } 
    } 
    public class RetainHttpsAttribute:FilterAttribute{} 

ExitHttpsIfNotRequired 속성을 장식하는 데 사용할 수 있습니다

그냥이 기본적으로 코드입니다 (난 그냥 빠른 참조 여기를 다시 게시하고, 코드에 대한 누가 복음 Sampsons 모든 신용)를 요약합니다 웹 응용 프로그램의 모든 컨트롤러를 파생시키는 데 사용되는 기본 컨트롤러 클래스입니다.

2

[RequireHttps]로 꾸미기보다는 다음을 유용하게 사용했습니다. [Secure]로 꾸미기 만하면이 속성이 나를 대신합니다.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 

namespace MyNameSpace.Attributes 
{ 
    public class SecureAttribute : ActionFilterAttribute 
    { 
     #region Variables and Properties 
     public bool PermanentRedirect { get; set; } 
     #endregion 

     #region Public Methods 
     public override void OnActionExecuting(ActionExecutingContext filterContext) 
     { 
      // Cache for efficiency 
      var request = filterContext.HttpContext.Request; 
      var response = filterContext.HttpContext.Response; 

      // Make sure we're not in https or local 
      if (!request.IsSecureConnection) 
      { 
       string redirectUrl = request.Url.ToString().Replace(
        Uri.UriSchemeHttp, 
        Uri.UriSchemeHttps); 

       if (PermanentRedirect) 
       { 
        // Set the status code and text description to redirect permanently 
        response.StatusCode = 301; 
        response.StatusDescription = "Moved Permanently"; 
       } 
       else 
       { 
        // Set the status code and text description to redirect temporary (found) 
        response.StatusCode = 302; 
        response.StatusDescription = "Found"; 
       } 

       // Add the location header to do the redirect 
       response.AddHeader("Location", redirectUrl); 
      } 

      base.OnActionExecuting(filterContext); 
     } 
     #endregion 
    } 
} 
+0

글쎄, 나는이 속성을 사용하여 로그인 액션을 장식해야한다. 불행히도 도움이되지 않는 것 같습니다. 로그인 후에 페이지는 여전히 https로 리디렉션됩니다. 확실하지 않은 경우에 대비하여 필자가 의도 한대로 사용하고 있는지 잘 모르겠다. – eddo

+0

사용자가 로그인했는지 여부를 감지하는 모듈이 필요할 수 있습니다. https에 계속 있으면 http로 리디렉션하지 않습니다. 사용자가 로그인 한 경우 향후 요청을 보호하기 위해 https에 보관하기를 원합니다. 또는 로그인이 완료되면 모든 것이 http로 리디렉션되도록 하시겠습니까? –

관련 문제