ASP.NET: Authenticating user in code

2019-04-11 00:44发布

问题:

I'm playing around with authentication and authorization to prepare for some task. I've created two pages: Login.aspx and Default.aspx. In config file i've set authentication to forms and denied unauthenticated users access:

<authentication mode="Forms">
      <forms name="aaa" defaultUrl="~/Login.aspx" />
    </authentication>
    <authorization>
      <deny users="?"/>
    </authorization>

Then I've written some simple code to authenticate my user in Login.aspx:

protected void Page_Load(object sender, EventArgs e)
        {
            GenericIdentity identity = new GenericIdentity("aga", "bbb");
            Context.User = new GenericPrincipal(identity, new String[] { "User" }); ;
            Response.Redirect("~/Default.aspx");
        }

When i run it, the redirection doesn't take place. Instead Login.aspx is called over and over because the user is not authenticated (Context.User.Identity.IsAuthenticated is false at every load). What am i doing wrong?

回答1:

Context.User only sets the principal for the current request. Once the redirect takes place, the current request ends and a new one begins with the non-overridden principal again (which is apparently not authenticated). So, setting Context.User doesn't actually authenticate anything.

Using FormsAuthentication.SetAuthCookie() will set the user's cookie to a valid value accepted by the FormsAuthentication provider, or put the token in the URL. You can redirect to your heart's content because the cookie obviously sticks with the user for future requests.

From MSDN (em added):

With forms authentication, you can use the SetAuthCookie method when you want to authenticate a user but still retain control of the navigation with redirects.

As stated, this does not necessarily require cookies - the name is a little misleading, because it will still work via the URL if FormsAuthentication is in cookieless mode:

The SetAuthCookie method adds a forms-authentication ticket to either the cookies collection, or to the URL if CookiesSupported is false.



回答2:

Use FormsAuthentication.SetAuthCookie(..). Or FormsAuthentication.RedirectFromLoginPage(..).



回答3:

You need to actually set the user as authenticated. All of the following methods will work and let you actually get away from your login screen.

FormsAuthentication.Authenticate()
FormsAuthentication.RedirectFromLoginPage()
FormsAuthentication.SetAuthCookie()

Lots of ways to get to the same result.



回答4:

You need to actually make a call to the formsAuthentication provider to set the login.

FormsAuthentication.RedirectFromLoginPage(txtUser.Text, chkPersistLogin.Checked)

is a simple example



回答5:

After creating the dummy Context.User, you need to perform a FormsAuthentication.SetAuthCookie or RedirectFromLoginPage method.