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