How to use forms authentication without login cont

2019-04-14 03:38发布

问题:

How to use forms authentication without login control.I don't want to use asp.net login control in my site.But i have to implement forms authentication and to validate users in my database.

回答1:

I am assuming that instead of using a login control, you are using a few textboxes(eg username/password) and a logon button. The code could look something like this:

In your aspx file

<asp:Textbox runat="server" ID="Username"/>
<asp:Textbox runat="server" ID="Password"/>
<asp:Button runat="server" ID="Login" OnClick="Login_OnClick"/>

<asp:Label runat="server" ID="Msg" >

And on server side:

public void Login_OnClick(object sender, EventArgs args)
{
if (Membership.ValidateUser(Username.Text,Password.Text))
{
     FormsAuthentication.RedirectFromLoginPage(Username.Text,
     NotPublicCheckBox.Checked);
}
else
Msg.Text = "Login failed.";
}

The forms authentication usually consists of 2 parts:

  • Calling membership API to authenticate/validate the user
  • Using FormsAuthentication API to log the user on (creating auth cookies, etc)

For more info look at these articles:

  • http://msdn.microsoft.com/en-us/library/aa480476.aspx
  • http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.redirectfromloginpage.aspx
  • http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.authenticate.aspx


回答2:

  <forms

  loginUrl ="~/Login.aspx"
  cookieless= "AutoDetect" 
  slidingExpiration="true"
  timeout="10"
   protection ="All"
  />

</authentication>
<authorization>
  <deny users ="?" />
  <allow users="*" />
</authorization>

loginUrl-->Use your login page there , the default is Login.aspx On the click of your login button or sign in button use this after verifying credentials from database

        HttpCookie authCookie = FormsAuthentication.GetAuthCookie(txtUsername.Text, false);
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
        FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent,"");
        authCookie.Value = FormsAuthentication.Encrypt(newTicket);
        Response.Cookies.Add(authCookie);
        string redirUrl = FormsAuthentication.GetRedirectUrl(txtUsername.Text, false);
        Response.Redirect(redirUrl);

Here you can find additional information about configuring web.config to match your needs Forms Authentication