Email confirmation and Password Policy Without ASP.NET Identity - asp.net

I am using OWIN form authentication in my project and not using any Identity specific classes that MVC templates generate.
I want to implement email confirmation and a password policy in my project. I'm not sure how this can be accomplished, as I don't have Identity related classes in my project as I don't want to use those. I am happy with the OWIN form authentication.
Is there any way I can verify via email and create a password policy by using OWIN form authentication?

I am not expert but Yes you can , To verify Email address you can send email with Guid as QueryString and add page to check id Guid is true and then flag user as confirmed did you mean like this ?
Send Email as html :
body = "<b>Wellcom Mr " + Username + " </b>";
body += "<br />";
body += "<b><a href=http://YourDomain/checkuseremail.aspx?
UserId=" + userId + " style='display:block; '>confirm</a></b>";
public partial class checkuseremail: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString["UserID"];
if(id != null){ select user id if email correct redirct to success page and flag user as confirmed}
else {redirct to error page}
}}

Related

Getting a members Email with asp.net login control

I am using asp login control.
Ex. getting the name with <asp:loginName ID="" runat="servet" />
How is it possible to get the email of the user. Not from code behind?
THANKS
To copy the user name to the email address, handle the CreatingUser event and do it there:
protected void CreateUserWizard1_CreatingUser( object sender, LoginCancelEventArgs e )
{
CreateUserWizard1.Email = CreateUserWizard1.UserName;
}
I'd also recommend adding a regexp to validate the email format for the user name.

LoginView Not Updating After User Login

I'm using ASP.NET Membership in order to manage a website users. But without using the specific 'Login Controls'. Actually, just applying Membership class methods in order to Create a user account and also to User login.
On the other hand, there is a LoginView control in Site.Master which is responsible to 'Welcome Username' task.
The problem is that, the LoginView control isn't updated after creating new account or any login.
Do I have to Definitely use the specific login controls?
----Also, I have set the Login Button CommandName to 'Login'!
----Should I set something like that for Create User Button?
I would appreciate any help...
The following is my code for login:
if (!Membership.ValidateUser(HttpUtility.HtmlEncode(txtUserName.Text), HttpUtility.HtmlEncode(txtPass.Text)))
{
lblResult.Text = "Invalid user name and password.";
lblResult.Visible = true;
}
else
{
Response.Redirect("~/Default.aspx");
}
And here the registration code:
MembershipCreateStatus statusUser;
try
{
Membership.CreateUser(HttpUtility.HtmlEncode(txtUserName.Text), HttpUtility.HtmlEncode(txtPass.Text), HttpUtility.HtmlEncode(txtEmail.Text), ddlSexQues.SelectedValue != "-1" ? ddlSexQues.Text : string.Empty, txtSecAnsw.Text == string.Empty ? string.Empty : txtSecAnsw.Text, true, out statusUser);
txtEmail.Text = string.Empty;
txtPass.Text = string.Empty;
txtRepass.Text = string.Empty;
txtSecAnsw.Text = string.Empty;
txtUserName.Text = string.Empty;
ddlSexQues.SelectedValue = "-1";
lblRsl.ForeColor = Color.Green;
lblRsl.Text = "حساب کاربری شما با موفقیت ایجاد شد.";
lblRsl.Visible = true;
}
catch (MembershipCreateUserException error)
{
lblRsl.Text = GetErrorMessage(error.StatusCode);
lblRsl.Visible = true;
}
If you're using your own login code, you'll need to persist the user's authentication information, for instance by adding a cookie to the response. The built-in controls do this automatically.
I'm assuming you're using Forms-based authentication. There's a reference to the .NET security class for Forms auth here, which details what options are available to you:
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication%28v=vs.100%29.aspx
Look at the SetAuthCookie and RedirectFromLoginPage methods in particular.
As far as I'm aware, the CommandName property is for distinguishing between Button controls in code. As you're using your own methods to handle user creation, I don't think you need to add it to your own control. More here:
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication%28v=vs.100%29.aspx

session variable for username

Hey I am creating a forum where users can login and post ocmments in a forum, I want the username as a session variable so I can get it when they post a comment and insert the username in the db and also to display a hello user message.
Below is my login code:
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
localhost.Service1 myws = new localhost.Service1();
ds = myws.GetUsers();
foreach (DataRow row in ds.Tables[0].Rows)
if (txtusername.Text == System.Convert.ToString(row["username"]) &&
txtpassword.Text == System.Convert.ToString(row["password"]))
{
System.Web.Security.FormsAuthentication.RedirectFromLoginPage(txtusername.Text, false);
}
else
Label3.Text = "Invalid Username/Password";
}
Do I declare the session variable here?
Like:
Session["username"] = "username";
Also not sure what to type to get the value username from the db
Thanks
You don't need to use a session. Once you call the FormsAuthentication.RedirectFromLoginPage method, inside the target page you could access the currently connected user from the authentication cookie that was emitted by this method using User.Identity.Name.
protected void Page_Load(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated)
{
string username = User.Identity.Name;
// ...
}
}
To learn more about how Forms Authentication works in ASP.NET I invite you to read the following article.
You are already using forms authentication (FormsAuthentication.RedirectFromLoginPage(txtusername.Text, false)) which is great. Consequently, you don't need to store the username is session as it's already available via User.Identity.Name, as Darin noted.
I have written two tutorials on forms authentication you might find useful:
An Overview of Forms Authentication
Forms Authentication Configuration and Advanced Topics
Additionally, consider using Membership. Membership is a subsystem built into ASP.NET that handles user accounts and provides an API for creating accounts, deleting accounts, etc. In short, you don't have to write all that code yourself. And with the login Web controls, creating new accounts, signing users in, resetting passwords, and so on, are all quite simple and involve zero to little code. For more information see my Membership tutorials.
Happy Programming!

How to provide different pages on login for different users?

I'm working on web application which has a database
UserName|Password|UserType
Anil|Anil|Manager
ghouse|Ghouse|Admin
raghu|raghu|User
Now my task is to provide each user their own page on login...They all have a same login page.
I tried this code it's working fine for two users. What to do if I have more than two users?
SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DebitCareBankApp;Data Source=SSDEV7-HP\\SQLEXPRESS");
string cmdStr = "select LoginType from Login where UserName='" + TxtUsername.Text + "' AND Password = '" + TxtPassword.Text + "'";
SqlCommand cmd = new SqlCommand(cmdStr, con);
con.Open();
Object TypeUser = cmd.ExecuteScalar();
con.Close();
if (TypeUser != null)
{
LblError.Visible = false;
LblError.Text = "";
if (TypeUser.ToString() == "Manager")
Response.Redirect("~/CallingAgents/CallingAgents_Login.aspx");
else
Response.Redirect("~/UserRegistrationForm.aspx");
}
else
{
LblError.Visible = true;
LblError.Text = "Invalid Credentials Entered, Try again";
}
I think you should create a common class where insert your user type on successful login.
In that common class redirect it to respective page.
On successful login:
Response.Redirect(clsCommon.GetDefaultPage(userType));
your commaon class code:
public static string GetDefaultPage(string userType){
//Default Redirects
Dictionary<string, string> userInfo = new Dictionary<string, string>(){
{"Manager","~/ManagerLogin.aspx"}, {"Admin","~/AdminLogin.aspx"},
{"User","~/UserLogin.aspx"}
};
return userInfo[roleName];
}
If you are using struts then you can redirect to different pages depending upon some Id. In actionforward you can achieve so. Or you can get some values from the url and try to redirect it
A simple way would be to use the Login-control and provide event handlers for the Authenticate event and the LoggedIn event. But i think it would be worth while for you to check out the capabilities of the asp.net membership system.
I assume you are not using Membership provider and make your login functionality by hand.
I do not fully understand the purpose of this customization. It make no sense for me. But there are multiple solutions for you:
convert the login page (aspx) into a user/custom control (ascx) and put in into different pages - simple, quick but not fully transparent, more info ScottGu
use IIS URL-Rewrite engine to provide multiple entry-points (urls)
to the same login page - clear, recomended, more info ScottGu
With first scenario you need to check UserType for credentials given by the user and confront it with page Url (aspx). In the second scenario, you need to obtain Request.RawUrl which contain base Url and make simple case.
Make use of sessions.
For a workaround, you can follow this:
+provide the same login page.
+Ask for username and password.
+use a drop down for selecting the usertype (ie Admin or Manager or User).
So based on the selection from drop down list you process the request.
I hope this helps.

Passing querystring with login control in asp.net 4?

Scenario:
I am doing project in C# ASP.NET 4.
I have a page of question. When somebody clicks on question (ie a Link Button) he is redirected to page where user can give answer but first he needs to login. So I put Login to Answer button that redirects user to GuestLogin.aspx with question id like this :
protected void LoginToAnswwer_Click(object sender, EventArgs e)
{
int qidrequest = int.Parse(Request.QueryString["qid"]);
Response.Redirect("~/GuestLogin.aspx?qid=" + qidrequest);
//This is working OK
}
And then when I am redirected to GuestLogin.aspx, I am putting below code in LoginButton of built in Login Control.
protected void LoginButton_Click(object sender, EventArgs e)
{
int qidrequest = int.Parse(Request.QueryString["qid"]);
Response.Redirect("QDisplay.aspx?qid=" + qidrequest);
}
Which is not working.
Question:
How to pass querystring with login button of built login control in asp.net 4 ?
You could pass a return URL to the login page, like this:
Response.Redirect(String.Format("/auth/login.aspx?return={0}", Server.UrlEncode(Request.Url.AbsoluteUri)));
In the login page, after authenticating the user:
Response.Redirect(Request.QueryString["return"]);
Pass Parameters from One Page to Another Page using QueryString :
//Set the Querystring parameters
Note: Maximum length of the
string that can be passed through QueryString is 255.
string URL =“QueryString.aspx?Name=” + txtFirstName.Text + “&Address=” + txtAddress.Text + “&City=” + txtCity.Text ;
//After Setting the Querystring Paramter values Use Response.Redirect to navigate the page
Response.Redirect(URL);
In the Page Load Event of the Navigated
Page,You can access the querystring parameter values like below :
lblName.Text = Request.QueryString["Name"].ToString();
lblAddress.Text = Request.QueryString["Address"].ToString();
lblCity.Text= Request.QueryString["City"].ToString();
That's how you have to use QueryString for passing parameters

Resources