asked
Donald Symmons 941Reputation points
I recently tried to use authentication and authorization on my login, but when I click to login nothing happens; it does not redirect
here is my code
Login.aspx.cs
private bool ValidateUser(string email, string pass) { SqlConnection conn; SqlCommand cmd; string lookupPassword = null; // Check for invalid userName. // userName must not be null and must be between 1 and 15 characters. if ((null == email) || (0 == email.Length) || (email.Length > 15)) { System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed."); return false; } // Check for invalid passWord. // passWord must not be null and must be between 1 and 25 characters. if ((null == pass) || (0 == pass.Length) || (pass.Length > 25)) { System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed."); return false; } try { // Consult with your SQL Server administrator for an appropriate connection // string to use to connect to your local SQL Server. conn = new SqlConnection("Data Source=(LocalDB) conn.Open(); // Create SqlCommand to select pwd field from users table given supplied userName. cmd = new SqlCommand("Select pass from Users where email=@email", conn); cmd.Parameters.Add("@email", SqlDbType.NVarChar, 25); cmd.Parameters["@email"].Value = email; // Execute command and fetch pwd field into lookupPassword string. lookupPassword = (string)cmd.ExecuteScalar(); // Cleanup command and connection objects. cmd.Dispose(); conn.Dispose(); } catch (Exception ex) { // Add error handling here for debugging. // This error message should not be sent back to the caller. System.Diagnostics.Trace.WriteLine("[ValidateUser] Exception " + ex.Message); } // If no password found, return false. if (null == lookupPassword) { // You could write failed login attempts here to event log for additional security. return false; } // Compare lookupPassword and input passWord, using a case-sensitive comparison. return (0 == string.Compare(lookupPassword, pass, false)); } private void CmdLogin_ServerClick(object sender, System.EventArgs e) { if (ValidateUser(txtUserName.Value, (txtUserPass.Value))) FormsAuthentication.RedirectFromLoginPage(txtUserName.Value, chkPersistCookie.Checked); else Response.Redirect("Login.aspx", true); }
Login.aspx
<asp:Label ID="lblMsg" ForeColor="red" Font-Size="10" runat="server" /> <label for="txtUsername" style="font-weight: 500;">Email</label> <input id="txtUserName" type="text" runat="server" class="form-control" style="font-size: 11pt;" placeholder="Email Address"/> <asp:RequiredFieldValidator ControlToValidate="txtUserName" Display="Static" ErrorMessage="Field Required" ForeColor="Red" Font-Size="9pt" runat="server" ID="vUserName" /> <label for="txtPassword" style="font-weight: 500;">Password</label> <input id="txtUserPass" type="password" runat="server" class="form-control" style="font-size: 11pt;" placeholder="Password"/> <asp:RequiredFieldValidator ControlToValidate="txtUserPass" Display="Static" ErrorMessage="Field Required" ForeColor="Red" Font-Size="9pt" runat="server" ID="vUserPass" /> Remember me: <asp:CheckBox ID="chkPersistCookie" runat="server" AutoPostBack="false" /> <input type="submit" value="Login" runat="server" class="btn btn-primary" id="CmdLogin" style="background-color: #32657c;" />
ASP.NET Web Forms
ASP.NET Web Forms
A part of the ASP.NET web application framework that can be used to create ASP.NET web applications.
374 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
6,829 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
1,162 questions
0{count} votes
P a u l 7,561Reputation points
2023-01-13T16:09:29.3133333+00:00 Are you binding your
CmdLogin_ServerClick
method to your login button?Donald Symmons 941Reputation points
2023-01-13T16:21:52.38+00:00 How do I bind
CmdLogin_ServerClick
method to login button?Donald Symmons 941Reputation points
(Video) How to fix the reply URL mismatch error in Azure AD - Microsoft Identity Platform2023-01-13T16:27:03.8633333+00:00 I read about a line of code to be added to the initializeComponent method in the designer.cs file but I don't know where to add it in the designer.cs. Please can you show me in an image where and how to bind the CmdLogin_ServerClick?
P a u l 7,561Reputation points
2023-01-13T17:18:31.21+00:00 You could try adding
OnClick="CmdLogin_ServerClick"
to the<input type="submit" value="Login">
element.Donald Symmons 941Reputation points
2023-01-13T19:03:38.0266667+00:00 I did that and still getting same result. When I click on the input button nothing happens I added
OnClick="CmdLogin_ServerClick"
to the<input type="submit" value="Login">
element and tried again and nothing happened. When I click on the login input it does absolutely nothingKaren Payne MVP 29,116Reputation points • Microsoft MVP
2023-01-14T15:24:39.07+00:00 On a side note, all the validation can be done using FluentValidation by setting up rules for each property e.g. user name, password (and even confirm password) and email.
public class UserValidator : AbstractValidator<User>{ public UserValidator() { Include(new UserNameValidator()); Include(new EmailAddressValidator()); Include(new PasswordValidator()); }}
Usage
UserValidator validator = new();ValidationResult result = validator.Validate(user);result.IsValid // true or false
And there is an
Error
property to get what is wrong.
Sign in to comment
Accepted answer
answered
2023-01-17T07:32:16.2933333+00:00 byQiYou-MSFT 621Reputation points • Microsoft Employee
Hi @Donald Symmons
Your problem should be that Server_Click command is not right.
Add in Page_Load:
protected void Page_Load(object sender, EventArgs e) { cmdLogin.ServerClick += new EventHandler(cmdLogin_ServerClick); }
Here is my code
Logon.aspx.cs
Logon.aspx
Default.aspx.cs
Default.aspx
public partial class Logon : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { cmdLogin.ServerClick += new EventHandler(cmdLogin_ServerClick); } private bool ValidateUser(string userName, string passWord) { SqlConnection conn; SqlCommand cmd; string lookupPassword = null; // Check for invalid userName. // userName must not be null and must be between 1 and 15 characters. if ((null == userName) || (0 == userName.Length) || (userName.Length > 15)) { System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed."); return false; } // Check for invalid passWord. // passWord must not be null and must be between 1 and 25 characters. if ((null == passWord) || (0 == passWord.Length) || (passWord.Length > 25)) { System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed."); return false; } try { // Consult with your SQL Server administrator for an appropriate connection // string to use to connect to your local SQL Server. conn = new SqlConnection("server=localhost;Integrated Security=SSPI;database=pubs"); conn.Open(); // Create SqlCommand to select pwd field from users table given supplied userName. cmd = new SqlCommand("Select pwd from users where uname=@userName", conn); cmd.Parameters.Add("@userName", SqlDbType.VarChar, 25); cmd.Parameters["@userName"].Value = userName; // Execute command and fetch pwd field into lookupPassword string. lookupPassword = (string)cmd.ExecuteScalar(); // Cleanup command and connection objects. cmd.Dispose(); conn.Dispose(); } catch (Exception ex) { // Add error handling here for debugging. // This error message should not be sent back to the caller. System.Diagnostics.Trace.WriteLine("[ValidateUser] Exception " + ex.Message); } // If no password found, return false. if (null == lookupPassword) { // You could write failed login attempts here to event log for additional security. return false; } // Compare lookupPassword and input passWord, using a case-sensitive comparison. return (0 == string.Compare(lookupPassword, passWord, false)); } private void cmdLogin_ServerClick(object sender, System.EventArgs e) { if (ValidateUser(txtUserName.Value, txtUserPass.Value)) { FormsAuthenticationTicket tkt; string cookiestr; HttpCookie ck; tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now, DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data"); cookiestr = FormsAuthentication.Encrypt(tkt); ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr); if (chkPersistCookie.Checked) ck.Expires = tkt.Expiration; ck.Path = FormsAuthentication.FormsCookiePath; Response.Cookies.Add(ck); string strRedirect; strRedirect = Request["ReturnUrl"]; if (strRedirect == null) strRedirect = "default.aspx"; Response.Redirect(strRedirect, true); } else Response.Redirect("logon.aspx", true); } }
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Logon.aspx.cs" Inherits="Test1_17.Logon" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title></title></head><body> <form id="form1" runat="server"> <h3> <font face="Verdana">Logon Page</font></h3><table> <tr> <td>Email:</td> <td><input id="txtUserName" type="text" runat="server"/></td> <td><ASP:RequiredFieldValidator ControlToValidate="txtUserName" Display="Static" ErrorMessage="*" runat="server" ID="vUserName" /></td> </tr> <tr> <td>Password:</td> <td><input id="txtUserPass" type="password" runat="server"/></td> <td><ASP:RequiredFieldValidator ControlToValidate="txtUserPass" Display="Static" ErrorMessage="*" runat="server" ID="vUserPass" /> </td> </tr> <tr> <td>Persistent Cookie:</td> <td><ASP:CheckBox id="chkPersistCookie" runat="server" autopostback="false" /></td> <td></td> </tr></table><input type="submit" Value="Logon" runat="server" ID="cmdLogin" /><p></p><asp:Label id="lblMsg" ForeColor="red" Font-Name="Verdana" Font-Size="10" runat="server" /> </form></body></html>
protected void Page_Load(object sender, EventArgs e) { cmdSignOut.ServerClick += new EventHandler(cmdSignOut_ServerClick); } private void cmdSignOut_ServerClick(object sender, System.EventArgs e) { FormsAuthentication.SignOut(); Response.Redirect("logon.aspx", true); }
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Test1_17.Default" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title></title></head><body> <form id="form1" runat="server"> <input type="submit" Value="SignOut" runat="server" id="cmdSignOut"/> </form></body></html>
Best Regards
Qi You
Donald Symmons 941Reputation points
2023-01-17T09:49:30.7+00:00 I appreciate this @QiYou-MSFT
But please I got 2 more questions on this.
- What does this mean "your custom data", can you please explain?
- Can I use textbox control in-place of the input controls you used?
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
(Video) Stop Office 365 Automatic LoginQiYou-MSFT 621Reputation points • Microsoft Employee
2023-01-18T02:41:38.0266667+00:00 @Donald Symmons
Question1:Gets a user-specific string stored with the ticket.
Question2:It is achievable.
The following is the relevant documentation:
Question1
Question2
Donald Symmons 941Reputation points
2023-01-18T06:09:19.77+00:00 So in question1, I'll leave the line at this, "your custom data", without writing anything ?
Donald Symmons 941Reputation points
2023-01-18T07:06:00.68+00:00 Hi @QiYou-MSFT
Please I want to personally seek your opinion on this, because I have tried exactly as you did in the code you shared to me and I’m still finding it doesn’t fire the click event.
So I decided to rewrite my login code after digging deeper into using authentication in my login.
Please help me check if it is okay
Here are how my login details goes:
I have 2 tables, one is the users table which stores user’s info, and user activation table that stores a bit of user ID and an activation code (which uses unique identifier as data type).
On sign up, user’s info is stored in both tables and an activation code is sent to user’s email. Then after user clicks on the activation code in his or her mailbox, the user is redirected to the activation page. And on the activation page load event, a delete function is done to delete that user’s data in the row in the activation table.
Finally, when user tries to login, it will check the login, as well as the activation table to see if the user’s data exists in the activation table. If user’s data exists in the activation table, then a message will show that user has not been activated, but if user’s data does not exist in the activation table, then user account has been activated. Other login process takes place..
LOGIN PAGE
protected void Page_Load(object sender, EventArgs e){ if (!this.IsPostBack) { if (this.Page.User.Identity.IsAuthenticated) { FormsAuthentication.SignOut(); Response.Redirect("~/Login.aspx"); } }} protected void ValidateUser(object sender, EventArgs e){//checks for empty textboxes if (!string.IsNullOrEmpty(textUser.Text) & !string.IsNullOrEmpty(txtPassword.Text)) { using (SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\AuthenticationTestDatabase.mdf;Integrated Security = True")) {//checks if user login details are correct using (SqlCommand cmd = new SqlCommand("SELECT UserId FROM UserTable WHERE email = @email AND pass = @pass", con)) { con.Open(); cmd.Parameters.AddWithValue("@email", emailtxtbox.Text.Trim()); cmd.Parameters.AddWithValue("@pass", Passwordtxtbox.Text.Trim()); string UserId = Convert.ToString(cmd.ExecuteScalar()); con.Close(); if (!string.IsNullOrEmpty(Uid)) {//this part checks if the account has been activated string users = ""; using (SqlCommand cmd1 = new SqlCommand("SELECT UserId FROM AccountActivation WHERE UserId = @UserId")) { cmd1.CommandType = CommandType.Text; cmd1.Parameters.AddWithValue("@UserId", UserId); cmd1.Connection = con; con.Open(); users = Convert.ToString(cmd1.ExecuteScalar()); con.Close(); } if (string.IsNullOrEmpty(users)) { int user = 0; using (SqlCommand cmd2 = new SqlCommand("SELECT UserId FROM UserTable WHERE pass = @pass COLLATE SQL_Latin1_General_CP1_CS_AS AND email = @email AND pass = @pass")) { cmd2.CommandType = CommandType.Text; cmd2.Parameters.AddWithValue("@email", emailtxtbox.Text.Trim()); cmd2.Parameters.AddWithValue("@pass", Passwordtxtbox.Text.Trim()); cmd2.Connection = con; con.Open(); user = Convert.ToInt32(cmd2.ExecuteScalar()); con.Close(); } if (user > 0) {//this checks the last login and Is Active columns and updates both accordingly Session["user"] = UserId; con.Open(); string query = "SELECT LastLogin, IsActive from UserTable WHERE UserId = @UserId"; using (SqlCommand cmd3 = new SqlCommand(query, con)) { cmd3.Parameters.AddWithValue("@UserId", Session["user"]); Session["LastLogin"] = Convert.ToDateTime(cmd3.ExecuteScalar()); } string UpdateLog = @"UPDATE UserTable SET LastLogin=@dateandtime, IsActive=@IsActive WHERE UserId = @UserId"; using (SqlCommand cmd4 = new SqlCommand(UpdateLog, con)) { //updated LastLogin is used to display last login date and time of user//Isactive is used to indicate if user is currently logged incmd.Parameters.AddWithValue("@dateandtime", DateTime.UtcNow); cmd.Parameters.AddWithValue("@IsActive", "1"); cmd4.Parameters.AddWithValue("@UserId", Session["user"]); cmd4.ExecuteNonQuery(); } con.Close(); } Session["user"] = UserId; FormsAuthentication.RedirectFromLoginPage(UserId, true); } else { dvMessage.Visible = true; lblMessage.Visible = true; lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "Account not activated"; txtPassword.Text = ""; txtPassword.Focus(); } } else { dvMessage.Visible = true; lblMessage.Visible = true; lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "Login Details are Invalid"; txtPassword.Text = ""; txtPassword.Focus(); } } } } else { dvMessage.Visible = true; lblMessage.Visible = true; lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "Required Fields"; }}
Default Page
<h1>Home</h1><asp:Label ID="lblMessage" runat="server"></asp:Label>
Default Code
protected void Page_Load(object sender, EventArgs e){ if (this.Page.User.Identity.IsAuthenticated) { lblMessage.Text = Session["user"].ToString(); } }
QiYou-MSFT 621Reputation points • Microsoft Employee
2023-01-18T09:24:24.23+00:00 Hi @Donald Symmons
First of all, let me tell you the first question:Gets a user-specific string stored with the ticket.It is usually not very important, and generally plays the role of identification.
Let me help you explain the second problem: the click event is unsuccessful.
I'll give you an example:If you want a **<input>**control (asp:buttont will also do) implement a functional event.
aspx:
<input type="submit" Value="Logon" runat="server" ID="cmdLogin" />
(Video) How to Fix ‘Msftconnecttest Redirect’ Error on Windows 10 [Tutorial]aspx.cs
protected void Page_Load(object sender, EventArgs e)
First you need to declare this feature when the page loads. Write cmdLogin_ServerClick next.
private void cmdLogin_ServerClick(object sender, System.EventArgs e)
I will give you an analysis of your needs. First of all, you need to put your project online so that others can get the website corresponding to the verification code in the email.
As for sending emails, I give you three classes for reference.
The MailMessage class, which is used to construct e-mail messages
The MailAttachment class, which is used to construct e-mail attachments
The SmtpMail class, which is used to send emails and their attachments
The other aspect of the problem is the content of a database CRUD.
You need to figure out SQLcommand.
Best Regards
Qi You
Donald Symmons 941Reputation points
2023-01-18T15:27:22.8666667+00:00 Hi I understand.. I know how to send mail in my project using SmtpMail class and MailMessage. I am please asking that you take a look at my updated login code to see if it's okay? All these is for learnig purposes, to see if I can write my own code to achieve same objective of authentication
QiYou-MSFT 621Reputation points • Microsoft Employee
2023-01-19T05:59:08.0033333+00:00 All you gave me was part of the code. I think it works logically, you need to run it and get the result to know if it's okay.
Donald Symmons 941Reputation points
2023-01-19T06:59:36.5966667+00:00 It works. Thanks a lot for your time. I'm really grateful. I just wish this platform had a way to send personal messages to people they follow... I would love it because they are issues I would have loved to discuss but other people may play down on them......but you always give me your time to help me with them calmly. THANK YOU
Sign in to comment
2 additional answers
Sort by: Most helpful
Most helpful Newest Oldest
answered
2023-01-14T12:32:18.7066667+00:00 byJose Zero 481Reputation points
The RedirectFromLoginPage method redirects to the return URL specified in the query string using the
ReturnURL
variable name. If theReturnURL
variable does not exist, the RedirectFromLoginPage method redirects to the URL in the DefaultUrl property.Sounds you missed set DefaultUrl in web.config.
As an example:<authentication mode="Forms"> <forms loginUrl="member_login.aspx" defaultUrl="index.aspx" /></authentication>
Donald Symmons 941Reputation points
(Video) How To Create a Clickable Table of Contents in Microsoft Word2023-01-14T16:56:54.8566667+00:00 I did exactly this and it still does nothing when I click the Login input
<authentication mode="Forms"> <forms name="MyfirstWebApp" loginUrl="Login.aspx" defaultUrl="SiteManagement.aspx" protection="All" path="/" timeout="30" /></authentication>
Sign in to comment
answered
2023-01-16T08:34:38.6166667+00:00 byQiYou-MSFT 621Reputation points • Microsoft Employee
Hi @Donald Symmons
First of all, if you use input as an input control, the way our backend gets the data is:
string username=Request[txtUserName];
Then we're comparing it to the data you get in your database.
We can use this method to implement redirection.
Response.Redirect("");
But here I suggest you use asp:TextBox as an input control, because it is more convenient.
Here is my example:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="About.aspx.cs" Inherits="WebApplication1.About" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title></title></head><body> <form id="form1" runat="server"> <div> <table> <tr> <td> <asp:Label ID="Label1" runat="server" Text="UserName:"></asp:Label> </td> <td> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td> </tr> <tr> <td> <asp:Label ID="Label2" runat="server" Text="PassWord:" ></asp:Label> </td> <td> <asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox></td> </tr> <tr> <td> <asp:Button ID="Button1" runat="server" Text="Login" onclick="Button1_Click" /> </asp:TextBox></td> </tr> </table> </div> </form></body></html>
using System;using System.Collections.Generic;using System.Configuration;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace WebApplication1{ public partial class About : Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { string username = TextBox1.Text; string password = TextBox2.Text; if (username != null || password != null) { if (username == "1234" && password == "1234") { Response.Redirect("Default.aspx"); } else { Response.Write("Fail"); } } } }}
</body>
}
Best Regards
Qi You
Donald Symmons 941Reputation points
2023-01-16T09:43:07.9+00:00 Hi @QiYou-MSFT
Please, I wanted to learn hw to use forms authentication, but in your example I don't see how the login has been authenticated.
I followed the documentation in the article
[https://learn.microsoft.com/en-us/troubleshoot/developer/webapps/aspnet/development/forms-based-authentication
QiYou-MSFT 621Reputation points • Microsoft Employee
2023-01-16T09:54:22.7333333+00:00 The example I just gave you is a relatively simple string contrast to complete authentication. It is usually used to log into the system. The examples of the links you give are mostly used for secure authentication. I'll write you an example tomorrow.
Donald Symmons 941Reputation points
2023-01-16T11:20:38.5633333+00:00 @QiYou-MSFT
Okay. I'll appreciate that. Thanks
Sign in to comment
Sign in to answer
Activity
Sign in to follow questions and users