Forms authentication: disable redirect to the login page

后端 未结 12 2539
情歌与酒
情歌与酒 2020-12-02 09:29

I have an application that uses ASP.NET Forms Authentication. For the most part, it\'s working great, but I\'m trying to add support for a simple API via an .ashx file. I wa

12条回答
  •  一向
    一向 (楼主)
    2020-12-02 10:25

    I had the problem that I wanted to avoid not only the redirect but also the forms authentication itself in order to make a web api work. Entries in web.config with a location tag for the api didn't help. Thus I used SuppressFormAuthenticationRedirect and HttpContext.Current.SkipAuthorization to suppress the authentication in general. In order to identify the sender I used e.g. the UserAgent in the Header but it is of course recommendable to implement further authentification steps, e.g. check against the sending IP or send another key with the request. Below is inserted in the Global.asax.cs.

    protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.Request.UserAgent == "SECRET-AGENT")
            {
                AppLog.Log("Redirect suppressed");
    
                HttpApplication context = (HttpApplication)sender;
    
                context.Response.SuppressFormsAuthenticationRedirect = true;
                HttpContext.Current.SkipAuthorization = true;                
            }
        }
    

提交回复
热议问题