ASP.NET: User Authentication in Code

I play with authentication and authorization to prepare for some kind of task. I created two pages: Login.aspx and Default.aspx. In the configuration file, I set authentication for forms and refused to non-authenticated users:

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

Then I wrote 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 redirect fails. Instead, Login.aspx is called again and again because the user is not authenticated (Context.User.Identity.IsAuthenticated is false on every download). What am I doing wrong?

+3
source share
5 answers

Context.User . , , (, -, ). , Context.User .

FormsAuthentication.SetAuthCookie() cookie , FormsAuthentication, URL. , cookie, , .

MSDN (em ):

SetAuthCookie, , .

, - , - URL-, FormsAuthentication cookieless:

SetAuthCookie cookie URL-, CookiesSupported .

+7

. .

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

Many ways to get the same result.

+1
source

To set up a login, you need to call the formsAuthentication provider.

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

- a simple example

0
source

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

0
source

Source: https://habr.com/ru/post/1717944/


All Articles