Form based Authentication using C# failing for the application

213 views Asked by At

I am trying to implement form authentication in asp.net for one of my applications under default website in IIS to prevent anonymous users from accessing the website and I am facing some issues when I try to do this

I have the below settings done in web.config file for this application to implement form-auth. I have included the machine key tag, authentication tag for form-based auth and authorization tag to deny anonymous user

<authentication mode="Forms">
  <forms name="cookiename" cookieless="UseCookies" path="/" protection="None" timeout="30" />
</authentication>
<authorization>
  <deny users="?"/>
</authorization>

In the IIS UI,

  • .NET Authorization rules have Anonymous Users with Deny Rule and All Users (of Inherited type) with Allow rule
  • Also, under Authentication UI, I have Anonymous Authentication disabled and From based Authentication enabled (Do we need to disable the Anonymous authentication here?)

When user logs into our portal, a cookie gets assigned to this user so that IIS can keep track of user's identity and gets navigated to the application (Aspx page) for which I am trying to implement form authentication. I am using webclient to post some request to perform some validation before navigating to this application and I am using CookieAwareWebClient to handle the cookies.

public class CookieAwareWebClient : WebClient
{
  public CookieAwareWebClient()
  {
     CookieContainer = new CookieContainer();
  }
  public CookieContainer CookieContainer { get; private set; }

  protected override WebRequest GetWebRequest(Uri address)
  {
    var request = (HttpWebRequest)base.GetWebRequest(address);
    request.CookieContainer = CookieContainer;
    return request;
   }
 }

Using the CookieAwareWebClient, I am trying to post the request. Here, authenticationCookie is the cookie which gets created right after user login and I am setting this value to myCookie object so that IIS can keep track of user's identity

using (CookieAwareWebClient client = new CookieAwareWebClient())
{         
  Cookie myCookie = new Cookie();
  myCookie.Name = authenticationCookie.Name; 
  myCookie.Value = authenticationCookie.Value;
  myCookie.Domain = URL.Host;
  client.CookieContainer.Add(myCookie);                    
  client.UseDefaultCredentials = true;

  byte[] responsebytes = client.UploadValues(URL, "POST", reqparm);
}

When I try to post the request to the URL, the identity of the user is lost somewhere even though the web client has cookie container which holds the cookie value, and I am getting 401 error

 Remote server returned an error (401) Unauthorized

Because of this, IIS thinks the user as anonymous and hence not able to load the application. Is this the right way to handle form-auth to prevent anonymous users from accessing website and where am I going wrong? I am using IIS 8.5 version

0

There are 0 answers