Manual Access control in ASP .Net

2019-03-06 01:29发布

问题:

Is there a way I can restrict access to pages without the built in role based way?

Essentially if the user tries to access admin.aspx then it redirects to login.aspx&redirect_url=admin.aspx

\then, they will postback with their credentials and I will give them a session cookie and so forth.

Is there an example of this?

Thanks

Edit:

I cannot use the way ASP.NET does it because my database has employees with usernames and passwords. ASP creates its own with roles and such

回答1:

First, you should set a FormsAuthentication cookie on login. So, in your code, on successful login you can set the cookie with:

FormsAuthentication.SetAuthCookie(theUsername, true); 

or better yet, you can use this to handle the cookie and the redirect:

FormsAuthentication.RedirectFromLoginPage(theUsername, true);

(true if you want to cookie to persist)

The you can secure the admin folder by putting a web.config file in that folder:

<?xml version="1.0"?>
<configuration>
    <system.web>
        <authorization>
            <allow users="adminusername1,adminusername2"/>
            <deny users="*"/>
        </authorization>
    </system.web>
</configuration>

Now when someone hits that admin folder and they aren't logged in, it will automatically send them to login.aspx?ReturnUrl=admin.aspx

Another thing to consider would be to implement your own RoleProvider. It's a lot less daunting that you may think. If you need to put people into roles (like Admin), then this is a good idea.



回答2:

You can use HttpContext.Session to keep session variables.

When You put something to session like:

HttpContext.Current.Session["IsAuthenticated"] = "true"

Asp.Net will create cookie for You, so You do not need to care about it. The cookie will expire at the end of the session. You can use Your custom login method and store in session variable that user is authenticated. Then on restricted page You just check session variable like:

string isAuthenticated = HttpContext.Current.Session["IsAuthenticated"]

Edit:

If You want to use Asp.Net authorization and restrict access base on user name then:

<authorization>
    <allow users="John"/>
    <deny users="*"/>
</authorization>

Take a look at Asp.Net site navigation as well where You can use same access rules for user.

Edit:

If You want to authenticate against Your credentials database then way suggested by MikeSmithDev is the way to go. Create custom MembershipProvider or use FormsAuthentication methods.