asp.net Windows Forms Authentication for Admin fol

2019-08-20 07:51发布

问题:

Im using C# and ASP.NET. I have this file structure on my website:

~\Admin\SecuredFolder\ManageWebsite.aspx
~\Admin\Login.aspx
~\Homepage.aspx

What i'm trying to achieve is pretty much simple but i guess all my attempts till now turned out too complex and i'm kinda confused.

my goals:

  • Homepage.aspx and Login.aspx should be public for all (anonymous users)
  • SecuredFolder should be for logged users ONLY (ie: admin users). Whoever attempt to access any page in this folder (without being logged) should be redirected to login page.
  • Once login succeeds it will successfully redirect to ManageWebsite.aspx

I know this supposed to be a simple implementation but i feel like I have not internalized it properly yet.

Hope any of you could provide me an example.

回答1:

Put this webconfig in securedfolder ~\Admin\SecuredFolder\

<?xml version="1.0"?>
<configuration>

  <system.web>
    <authorization>
      <allow roles="admin" />
      <deny users="?"/>
    </authorization>
  </system.web>

</configuration>

put this in webconfig of root folder ~\

 <authentication mode="Forms">
      <forms loginUrl="~/Admin/Login.aspx" timeout="2880" />
    </authentication>
  <location>
    <system.web>
      <authorization>

        <allow users="*"/>

      </authorization>
    </system.web>
  </location>


回答2:

To your root web.config add these to make Homepage and Login aspx pages public

  <location path="Homepage.aspx">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
  <location path="Login.aspx">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>

Inside the Secure folder add a web.config file and to that add these to allow all contents inside SecuredFolder to be accessible only to Admin roles

  <authorization>
    <allow roles="Admin"/>
    <deny users="*"/>
  </authorization>

After successful authentication, in Login.aspx, check the users role, if the role is that of Admin, redirect him to the ManageWebsite.aspx page



回答3:

Place a web.config in your SecuredFolder and add

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <authorization>
          <allow roles="admin" />
          <deny users ="*" />
        </authorization>
    </system.web>
</configuration>

Now it will only allow the logged in(admin) user to access its contents.

You can also add <authentication> to your root web.config to automatically redirect an unauthorized user to the login page.

<authentication mode="Forms">
<forms loginUrl="~\Admin\Login.aspx" timeout="20" slidingExpiration="true" cookieless="AutoDetect" protection="All" requireSSL="false" enableCrossAppRedirects="false" defaultUrl="Homepage.aspx" path="/"/>
</authentication>