Override ASP.NET forms authentication for a single page

前端 未结 3 2056
长情又很酷
长情又很酷 2021-02-10 00:16

In our ASP.NET MVC application, we automatically redirect users to a log-on page via the section of when they

相关标签:
3条回答
  • 2021-02-10 00:41

    The following solution works, although I'm not at all sure it's optimal:

    public class HttpAuthenticationRequiredResult : ActionResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;
            response.StatusCode = 401;
            response.AddHeader("WWW-Authenticate", "Basic realm=\"whatever\"");
            response.Flush();
            response.Close();
        }
    }
    

    You can then return the above result instead of an HttpUnauthorizedResult to generate the required 401 code. This feels quite klugy to me, however.

    0 讨论(0)
  • 2021-02-10 00:55

    You can have separate <system.web> sections for separate paths. Here's an example:

    <configuration>
      <location path="Foo/Bar.aspx">
        <system.web>
          <authorization>
            <allow roles="GoodGuys" />
            <deny users="*"/>
          </authorization>
        </system.web>
      </location>
    </configuration>
    

    In this case, the page "Foo/Bar.aspx" is allowed to folks with the GoodGuys role, but denied to all others.

    In your case, you might want to allow all without authentication:

    <configuration>
      <location path="Foo/Bar.aspx">
        <system.web>
          <authentication mode="None" />
          <authorization>
            <allow users="*" />
          </authorization>
        </system.web>
      </location>
    </configuration>
    
    0 讨论(0)
  • 2021-02-10 00:57

    Had a similar case where I needed to return back something that triggered an undesired redirect (basically a message about how authentication failed and it was redirecting to the login screen without the error information).

    This solved the problem:

    Response.SuppressFormsAuthenticationRedirect = true;
    
    0 讨论(0)
提交回复
热议问题