locked
Redirect to login page if not logged in. RRS feed

  • Question

  • User-1506965535 posted

    Hi,

    Some of my aspx forms are very important pages. I want whenever a user if not logged in, and if he puts the page name directly in the url he should be directed to login page of the site. Please help

    Thursday, November 27, 2014 10:21 AM

Answers

  • User1738843376 posted
    <authentication mode="Forms">
          <forms loginUrl="login.aspx" defaultUrl="default.aspx" name=".YourApplication" timeout="60" cookieless="AutoDetect" />
    </authentication>
    
    <authorization>
          <deny users="?" />
    </authorization>

    This goes into the web.config

    the loginUrl property tells the server where to direct the user if he is not logged in, and the defaultUrl property tells the server where to direct him after the user is logged.

    the deny users="?" tells the server to deny any user that is not authenticated and directs him to the loginUrl page

    In the codebehind of the login page, you need something like this after you check the credentials inserted:

    FormsAuthentication.RedirectFromLoginPage(userName.Text, True)

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 27, 2014 12:59 PM
  • User71929859 posted

    but when the page redirects to the login page it forms URL some what like this below:-

    Yes that's because it's keeping track on where to redirect after the user logs in. Since the user tries to access a particular page which he is not authorized, it does make sense to redirect the user to that requested page after (s)he provide the credentials.

    and the main issue is that the CSS of the page is lost. why

    That's because you've set deny access to all the folders for unauthorized request. You need to specifically allow access to resources regardless of the request is authenticated or not. Like below

    <location path="/Content">
        <system.web>
            <authorization>
                <allow users="*"/>
            </authorization>
        </system.web>
    </location>

    replace the path with your CSS folder path.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, November 29, 2014 7:30 AM
  • User-1151753377 posted

    Hi Nadeem157,

    Welcome to the ASP.NET forum.

    Please check the code below that the connectionStringName and I couldn't find it in your web.config file

     <membership>
          <providers>
            <clear/>
            <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="connect_str" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
          </providers>
        </membership>
    

    And in the code that set the defaultProvider property

    <roleManager enabled="true" defaultProvider="DefaultRoleProvider">
         
          <providers>
            <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultCSRConnection" applicationName="/"/>
                 </providers>
        </roleManager>

    Further information abput ASP.NET Membership and Role Provider.

    http://www.codeproject.com/Articles/281573/ASP-NET-Membership-and-Role-Provider

    FormsAuthentication.RedirectFromLoginPage Method:
    http://msdn.microsoft.com/en-us/library/ka5ffkce(v=vs.110).aspx

    Best Regards,

    Summer

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, December 4, 2014 2:45 AM
  • User724169276 posted

    You are coding role based authorization without any roles defined in web.config.Your Authentication steps are messed up ..try this below article which has explained this step by step.:

    http://www.aspsnippets.com/Articles/Role-based-Authorization-and-Authentication-in-ASPNet.aspx

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, December 4, 2014 2:51 AM

All replies

  • User1428246847 posted

    Below the basic idea; it depends on how you do your authentication (I'm using my own mechanism)

    I have a few session variables; one indicates if a user is logged in. A little further in the code, it checks if the user is not logged in; if not, redirect.

    // get session variables
    g_IsLoggedIn = Session["IsLoggedIn"] == null ? false : (bool)Session["IsLoggedIn"];
    ...
    ...
    
    // check if logged in
    if (!g_IsLoggedIn)
    {
        Response.Redirect("Login.aspx", true);
    }
    


    Thursday, November 27, 2014 12:51 PM
  • User1738843376 posted
    <authentication mode="Forms">
          <forms loginUrl="login.aspx" defaultUrl="default.aspx" name=".YourApplication" timeout="60" cookieless="AutoDetect" />
    </authentication>
    
    <authorization>
          <deny users="?" />
    </authorization>

    This goes into the web.config

    the loginUrl property tells the server where to direct the user if he is not logged in, and the defaultUrl property tells the server where to direct him after the user is logged.

    the deny users="?" tells the server to deny any user that is not authenticated and directs him to the loginUrl page

    In the codebehind of the login page, you need something like this after you check the credentials inserted:

    FormsAuthentication.RedirectFromLoginPage(userName.Text, True)

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 27, 2014 12:59 PM
  • User-1506965535 posted

    what does 

    name=".YourApplication"

    means ?

    Also where should I write the below code on login page  ?

    FormsAuthentication.RedirectFromLoginPage(userName.Text, True)

    Friday, November 28, 2014 8:33 AM
  • User1738843376 posted

    The .YourApplication is whatever name you wish, provided you start it with a dot, so that the authentication session can be identified.

    the FormsAuthentication.RedirectFromLoginPage(userName.Text, True) is the call you make on your code behind after confirming that the credentials introduced onthe ASP form as correct, for instance:

    Dim uName As string = "myUsername"
    Dim pWord As string = "myPassword"
    If username.text = uName And password.text = pWord then
         FormsAuthentication.RedirectFromLoginPage(userName.Text, True)
    End if

    Friday, November 28, 2014 10:33 AM
  • User-1506965535 posted

    Hi Obelix,

    The code is working fine, but when the page redirects to the login page it forms URL some what like this below:-

    http://localhost:49924/login.aspx?ReturnUrl=%2fcsrpage.aspx

    and the main issue is that the CSS of the page is lost. why

    Saturday, November 29, 2014 1:48 AM
  • User71929859 posted

    but when the page redirects to the login page it forms URL some what like this below:-

    Yes that's because it's keeping track on where to redirect after the user logs in. Since the user tries to access a particular page which he is not authorized, it does make sense to redirect the user to that requested page after (s)he provide the credentials.

    and the main issue is that the CSS of the page is lost. why

    That's because you've set deny access to all the folders for unauthorized request. You need to specifically allow access to resources regardless of the request is authenticated or not. Like below

    <location path="/Content">
        <system.web>
            <authorization>
                <allow users="*"/>
            </authorization>
        </system.web>
    </location>

    replace the path with your CSS folder path.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, November 29, 2014 7:30 AM
  • User-1506965535 posted

    Hi Ruchira,

    Thanks for your answer, but my concern is that, whether I should use 

    <allow users="*"/>

    or

      <deny users="?"/>

    or both. 

    Thanks.

    Saturday, November 29, 2014 10:11 AM
  • User71929859 posted

    or both. 

    both

    <location path="/Content">
        <system.web>
            <authorization>
                <allow users="*"/>
            </authorization>
        </system.web>
    </location>
    <authorization>
          <deny users="?"/>
    </authorization>
    Saturday, November 29, 2014 3:11 PM
  • User-1506965535 posted

    Hi Ruchira,

    I added in web.config file like below:-

     <location path="css/style.css">
      <system.web>
        <compilation debug="true" targetFramework="4.0" />
        <authentication mode="Forms">
          <forms loginUrl="Login.aspx" defaultUrl="Login.aspx" name=".csrproject" timeout="60" cookieless="AutoDetect" />
        </authentication>
        <authorization>
          <allow users="*" />
        </authorization>

    What if I want to add two css fiesl ?

    Sunday, November 30, 2014 12:18 AM
  • User71929859 posted

     <location path="css/style.css">

    Remove the file name so the authorization rule applies to the whole folder

    <location path="css">
      <system.web>
        <compilation debug="true" targetFramework="4.0" />
        <authentication mode="Forms">
          <forms loginUrl="Login.aspx" defaultUrl="Login.aspx" name=".csrproject" timeout="60" cookieless="AutoDetect" />
        </authentication>
        <authorization>
          <allow users="*" />
        </authorization>
    Sunday, November 30, 2014 1:41 AM
  • User-1506965535 posted

    Hi Ruchira,

    Tried with your code, but still nothing is happening. Please see the way I implemented.

    The below is the code which I implemented on web.config file:-

    <?xml version="1.0"?>
    <!--
      For more information on how to configure your ASP.NET application, please visit
      http://go.microsoft.com/fwlink/?LinkId=169433
      -->
    <configuration>
      <configSections>
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
      </configSections>
      <connectionStrings>
        <add name="DefaultCSRConnection" connectionString="Data Source=0.0.0.0.0;Initial Catalog=Test;Persist Security Info=True;User ID=Test;Password=**************;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient"/>
        <add name="CSRConnectionString" connectionString="Data Source=0.0.0.0.0;Initial Catalog=Test;Persist Security Info=True;User ID=Test;Password=**************;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>
      </connectionStrings>
      <location>
      <system.web>
        <compilation debug="true" targetFramework="4.0" />
        <authentication mode="Forms">
          <forms loginUrl="Login.aspx" defaultUrl="Login.aspx" name=".csrproject" cookieless="AutoDetect" timeout="60" />
        </authentication>
        <authorization>
          <allow users="*" />
        </authorization>
        
        
        <profile defaultProvider="DefaultProfileProvider">
          <providers>
            <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultCSRConnection" applicationName="/"/>
          </providers>
        </profile>
        <membership>
          <providers>
            <clear/>
            <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="connect_str" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
          </providers>
        </membership>
        <roleManager enabled="true">
          <providers>
            <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultCSRConnection" applicationName="/"/>
          </providers>
        </roleManager>
        <!--
                If you are deploying to a cloud environment that has multiple web server instances,
                you should change session state mode from "InProc" to "Custom". In addition,
                change the connection string named "DefaultCSRConnection" to connect to an instance
                of SQL Server (including SQL Azure and SQL  Compact) instead of to SQL Server Express.
          -->
        <sessionState mode="InProc" customProvider="DefaultSessionProvider">
          <providers>
            <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultCSRConnection"/>
          </providers>
        </sessionState>
      </system.web>
      </location>
      <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
      </system.webServer>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246"/>
            <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.1.0.0"/>
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246"/>
            <bindingRedirect oldVersion="0.0.0.0-4.1.0.0" newVersion="4.1.0.0"/>
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral"/>
            <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
      <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
          <parameters>
            <parameter value="v11.0"/>
          </parameters>
        </defaultConnectionFactory>
      </entityFramework>
    </configuration>

    Also, I implemented the something on button click after submission like below in login.aspx.cs

     protected void btnSubmit_Click(object sender, EventArgs e)
            {
                String LoginID = txtUsername.Text.Trim().ToLower();
                String LoginPassword = txtPassword.Text.Trim();
    
                SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString);
                conn.Open();
                SqlCommand cmd = new SqlCommand("select username,password,usertype from tbl_User where username=@username and password=@password and Active= 1 ", conn);
                cmd.Parameters.AddWithValue("@username", txtUsername.Text);
                cmd.Parameters.AddWithValue("@password", txtPassword.Text);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                if (dt != null && dt.Rows.Count > 0)
                {   
                    if (dt.Rows[0]["usertype"].ToString() == "0") //SuperAdmin
                    {
                        FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true); /*for redirection*/
                        Session["User"] = "0";
                        Response.Redirect("csrpage.aspx");
                    }
                    else if (dt.Rows[0]["usertype"].ToString() == "1") // Admin
                    {
                       FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true); /*for redirection*/
                        Session["User"] = "1";
                        Response.Redirect("Admin.aspx");
                    }
                    else if (dt.Rows[0]["usertype"].ToString() == "2") // User
                    {
                      FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true); /*for redirection*/
                        Session["User"] = "2";
                        Response.Redirect("User.aspx");
                    }
                }
                else
                {
                    ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
                }
            }

    Please help.

    Tuesday, December 2, 2014 5:17 AM
  • User-1151753377 posted

    Hi Nadeem157,

    Welcome to the ASP.NET forum.

    Please check the code below that the connectionStringName and I couldn't find it in your web.config file

     <membership>
          <providers>
            <clear/>
            <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="connect_str" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
          </providers>
        </membership>
    

    And in the code that set the defaultProvider property

    <roleManager enabled="true" defaultProvider="DefaultRoleProvider">
         
          <providers>
            <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultCSRConnection" applicationName="/"/>
                 </providers>
        </roleManager>

    Further information abput ASP.NET Membership and Role Provider.

    http://www.codeproject.com/Articles/281573/ASP-NET-Membership-and-Role-Provider

    FormsAuthentication.RedirectFromLoginPage Method:
    http://msdn.microsoft.com/en-us/library/ka5ffkce(v=vs.110).aspx

    Best Regards,

    Summer

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, December 4, 2014 2:45 AM
  • User724169276 posted

    You are coding role based authorization without any roles defined in web.config.Your Authentication steps are messed up ..try this below article which has explained this step by step.:

    http://www.aspsnippets.com/Articles/Role-based-Authorization-and-Authentication-in-ASPNet.aspx

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, December 4, 2014 2:51 AM
  • User-1506965535 posted

    Thanks Summer and Ashim sir.

    Thursday, December 4, 2014 4:16 AM