ASP.NET MVC Futures RequireSSL Attribute and Authorize Attribute Together

Does anyone successfully use the Authorize and RequireSSL attributes (from MVC futures) together on the controller? I created a controller for which I must enforce the rule in which the user must log in and use a secure connection to execute it. If the user is not in a secure connection, I want the application to be redirected to https, so I use Redirect = true in the RequireSSL attribute. The code looks something like this: CheckPasswordExpired is my native attribute):

[Authorize]
[RequireSsl(Redirect = true)]
[CheckPasswordExpired(ActionName = "ChangePassword",
    ControllerName = "Account")]
[HandleError]
public class ActionsController : Controller
{
    ....
}

mysite.com/Actions/Index is the default route for the site, as well as the default page for redirecting forms authentication.

http://mysite.com, , , , . HTTP 400 (Bad Request). http://mysite.com/Account/Login, , , [].

- ?

!

+3
1

. ?

public class HomeController : BaseController
{
  [Authorize]
  [RequireSsl]
  public ActionResult Index ()
  {
  }
}

BTW , , SSL :

[AttributeUsage (AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class RequireSslAttribute : FilterAttribute, IAuthorizationFilter
{
    public RequireSslAttribute ()
    {
        Redirect = true;
    }

    public bool Redirect { get; set; }

    public void OnAuthorization (AuthorizationContext filterContext)
    {
        Validate.IsNotNull (filterContext, "filterContext");

        if (!Enable)
        {
            return;
        }

        if (!filterContext.HttpContext.Request.IsSecureConnection)
        {
            // request is not SSL-protected, so throw or redirect
            if (Redirect)
            {
                // form new URL
                UriBuilder builder = new UriBuilder
                {
                    Scheme = "https",
                    Host = filterContext.HttpContext.Request.Url.Host,
                    // use the RawUrl since it works with URL Rewriting
                    Path = filterContext.HttpContext.Request.RawUrl
                };
                filterContext.Result = new RedirectResult (builder.ToString ());
            }
            else
            {
                throw new HttpException ((int)HttpStatusCode.Forbidden, "Access forbidden. The requested resource requires an SSL connection.");
            }
        }
    }

    public static bool Enable { get; set; }
}
+4

Source: https://habr.com/ru/post/1712705/


All Articles