approve user umbraco membership system - asp.net

hi i am working on Umbraco(6.1.2) membership system
ive made login ,registration, and authentication page
after registeration user is redirected to authentication page with token_id
now i want to set this user approved for this purpose i write the following code
but there is some error check it
string uname = Request.QueryString["a"];
string uguid = Request.QueryString["b"];
MembershipUser thisUser = Membership.GetUser(uname);
if (thisUser != null)
{
if (!thisUser.IsApproved)
{
MemberProfile mp = MemberProfile.GetUserProfile(uname);
if (mp != null)
{
if (mp.AuthGuid == uguid)
{
thisUser.IsApproved = true;
Membership.UpdateUser(thisUser);
lblMessage.Text = "Thank you for confirming your email address";
}
else
{
lblMessage.Text = "Error confirming your email address";
}
}
else
{
lblMessage.Text = "Error confirming your email address";
}
}
else
{
lblMessage.Text = "Email address is already confirmed";
}
}
control is return to else condition from this condition "if (!thisUser.IsApproved)"
and also if i reverse the condition it gets into if block and executes all commands without errors but still not mark user as approved
plz help me
Refrence:Authenticating new members before activating

I had problem with approved as well.
Now I just use this in my code:
MembershipUser user = Membership.GetUser(nodeIdOrUsername);
user.IsApproved = true;
Membership.UpdateUser(user);
You may also need to add a property to your Member type, eg. isApproved and then add it to your provider in web.config in profile > properties section:
<add name="isApproved" allowAnonymous="false" provider="UmbracoMembershipProvider" type="System.Boolean"/>
and then extend ProfileBase and added an Approved property.
In web.config in membership > provider section add this property to your provider key eg.:
<add name="UmbracoMembershipProvider" type="umbraco.providers.members.UmbracoMembershipProvider" umbracoApprovePropertyTypeAlias="isApproved" umbracoLockPropertyTypeAlias="isLocked" ... />
I can't remember for sure but I think without it it didn't work.
I hope this will be of any use.

Related

Get windows logon user in asp.net web forms iis

I want to get the active directory login user in asp.net web forms.I used the below code snippet,but it won't work on either runtime or iis.
Request.ServerVariables["REMOTE_USER"].ToString();
Try using System.Web.HttpContext.Current.User.Identity; to get details of the authenticated user.
Use Directory Entry to get the user status.
string username = "";
string userpassword = "";
bool valid = false;
using (DirectoryEntry Direntry = new DirectoryEntry(path, username, userpassword))
{
using (DirectorySearcher Dsearch = new DirectorySearcher(Direntry))
{
Dsearch.Filter = "(cn=" + username + ")";
try
{
SearchResult adsSearchResult = Dsearch.FindOne();
if (adsSearchResult != null)
{
valid = true;
}
}
catch (Exception ex)
{
}
finally
{
Direntry.Close();
}
}
}
One additional change you may need to make is in the web.config file.
Change the authentication mode from Forms to Windows.
<authentication mode="Windows"/>
Documentation

Sessions ASP.NET Timeout

I have problems with sessions in asp.net. I searched the web for a while, but couldn't find the reason why it doesn't works. The session disappears after some minutes. It is a project that isn't created by myself, i'm not a hero in aspx. But I'm trying to solve this problem.
Web.config
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Default.aspx" timeout="120" slidingExpiration="true" />
</authentication>
<customErrors mode="RemoteOnly"/>
<httpRuntime requestValidationMode="2.0"/>
<pages validateRequest="false" />
<sessionState mode="InProc" cookieless="false" timeout="120" />
</system.web>
Checking if Logged in on the pages that you have to be logged in
if (!functions.isLoggedIn(Session))
{
Response.Redirect("Default.aspx");
}
Functions
public static bool isLoggedIn(HttpSessionState session)
{
return session["user"] != null;
}
Not logged in ? Showing login form, filling in the form and then send it to server to check
protected void Page_Load(object sender, EventArgs e)
{
if (Request["do"] != null)
{
switch (Request["do"])
{
case "logout":
Session.Abandon();
break;
}
}
if (Request.ServerVariables["REQUEST_METHOD"].ToLower() == "post")
{
//get username en password
string username = Request["username"];
string password = Request["password"];
if (String.IsNullOrWhiteSpace(username) || String.IsNullOrWhiteSpace(password))
{
LoginMessage.Text = "Please fill in all the fields...";
}
else
{
password = FormsAuthentication.HashPasswordForStoringInConfigFile(
password,
"SHA1");
UserService gs = new UserService();
user g = gs.getUserByLogin(username, password);
if (g == null)
{
//wrong login
LoginMessage.Text = "Invalid username/password.";
}
else
{
//good login
Session["user"] = g;
System.Diagnostics.Debug.WriteLine("timeout:" + Session.Timeout);
Response.Redirect("Home.aspx");
}
}
}
}
GetUserByLogin function in userservice
public user getUserByLogin(string username, string password)
{
user g;
var db = new projectName.Db.Models.projectnetContext();
IQueryable<user> query = from gb in db.users
where gb.username.Equals(username)
&& gb.Passwoord.Equals(password.ToLower())
&& gb.Status == 1
select gb;
if (!query.Any())
g = null;
else
g = query.First();
return g;
}
After login in, creating the session
Session["user"] = g;
My problem is that I have set the time-out. But it doesn't seems to work. If I check the timeout on the server, it is set to 120. But after 2 minutes, I'm redirected to the login form. Can I solve this? If I debug on localhost, It seems to work, but not online.
The login works. The session is set (otherwise I couldn't enter the next pages). If I go to another page (faster then +-5minutes), then I'm still logged in. So the problem is reproductive.
Or if it isn't possible, Cookies? Normally I work with cookies in PHP,.. But is there a way to do it in ASP.NET on a safe way?
Hmm I Recommend you to use profile instead of session in asp .net .
There is two aspects in your scenario. You have the authentication and the session. These are two different things.
Session that you are manage in your web.config stored a value with a timeout of 120 minutes (2 hours)
But Authentication also have a configuration section in web.config.
https://msdn.microsoft.com/en-us/library/532aee0e%28v=vs.85%29.aspx
So what do you want to do exactly first ?
Please find this MVC controller action method sample.
// POST: /Secure/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginFormModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.Login, model.Password))
{
using (var db = new DatabaseEntities())
{
var user = db.Users.Single(u => u.Login == model.Login);
Membership.UpdateUser(new MembershipUser("UserMembershipProvider", user.Login, null, null, null, null, true, false, DateTime.MinValue, DateTime.Now, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue));
#region Create Authentication Cookie
Response.Cookies.Add(MyAppFormAuthenticationCookie.Create(user, model.RememberMe));
#endregion
if (!string.IsNullOrWhiteSpace(returnUrl))
{
return Redirect(HttpUtility.UrlDecode(returnUrl));
}
if (model.UserFormType == UserType.Candidate)
{
return RedirectToAction("Index", "Dashboard", new { area = "Candidate" });
}
if (model.UserFormType == UserType.Recruiter)
{
return RedirectToAction("Index", "Dashboard", new { area = "Recruiter" });
}
if (model.UserFormType == UserType.SuperAdmin || model.UserFormType == UserType.Admin)
{
return RedirectToAction("Index", "Dashboard", new { area = "Admin" });
}
}
}
ModelState.AddModelError("", "Incorrect username and/or password");
return View("Index", model);
}
return RedirectToAction("Index", "Home");
}
In this sample, you have :
UPDATE of the user profile to set the last connection date and others if you want ...
CREATION of the authentication cookie in a custom way for this sample
REDIRECTION to the homepage according to the type of user
So, do you have a similar approach to authenticate user in your application ?
EDIT1:
Normally you must finalize authentication process something like this :
var authTicket = new FormsAuthenticationTicket("MyAuthTicket", rememberMe, timeout: 120);
var encryptAuthTicket = FormsAuthentication.Encrypt(authTicket);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encryptAuthTicket) { Expires = authTicket.Expiration });
Just an advice... do you have any re-directions(Response.Redierct) to diff. sites or trying to access the resources for which you don't have access? Session will expire in these cases.

Reset Password Strategy

I have a custom Register form which includes a security question and answer - works fine.
However, I have the following reset password logic which only works if the requiresQuestionAndAnswer property is set to false in my Web.Config file. Can someone show me a recommended way to code the question and answer logic into my ResetPassword code-behind? Is another trip to the DB necessary here?
public void ResetPassword_OnClick(object sender, EventArgs args)
{
string newPassword;
u = Membership.GetUser(UsernameTextBox.Text, false);
newPassword = u.ResetPassword();
if (newPassword != null)
{
Msg.Text
= "Password reset. Your new password is: "
+ Server.HtmlEncode(newPassword);
}
else
{
Msg.Text
= "Password reset failed. Please re-enter your values.";
}
}
I found the answer here:
MembershipUser.PasswordQuestion Property
"If RequiresQuestionAndAnswer is true, then the password answer for a membership user must be supplied to the GetPassword and ResetPassword methods."

asp.net membership change password without knowing old one

Evaluting the method signature, it is required to know old password while changing it.
membershipUser.ChangePassword(userWrapper.OldPassword, userWrapper.Password)
Is there any way to change password without knowing old one.
string username = "username";
string password = "newpassword";
MembershipUser mu = Membership.GetUser(username);
mu.ChangePassword(mu.ResetPassword(), password);
The other answers here are correct, but can leave the password in an unknown state.
ChangePassword will throw exceptions if the password doesn't meet the requirements laid out in Web.Config (minimum length, etc.). But it only fails after ResetPassword has been called, so the password will not be known to the original user or to the person who's tried to change it. Check for complexity requirements before changing the password to avoid this:
var user = Membership.GetUser(userName, false);
if ((newPassword.Length >= Membership.MinRequiredPasswordLength) &&
(newPassword.ToCharArray().Count(c => !Char.IsLetterOrDigit(c)) >=
Membership.MinRequiredNonAlphanumericCharacters) &&
((Membership.PasswordStrengthRegularExpression.Length == 0) ||
Regex.IsMatch(newPassword, Membership.PasswordStrengthRegularExpression))) {
user.ChangePassword(user.ResetPassword(), newPassword);
} else {
// Tell user new password isn't strong enough
}
You need to reset the user's password before changing it, and pass in the generated password to ChangePassword.
string randompassword = membershipUser.ResetPassword();
membershipUser.ChangePassword(randompassword , userWrapper.Password)
or inline:
membershipUser.ChangePassword(membershipUser.ResetPassword(), userWrapper.Password)
Try to use SimpleMembershipProvider it's easier:
var token = WebSecurity.GeneratePasswordResetToken("LoginOfUserToChange");
WebSecurity.ResetPassword(token, "YourNewPassword");
Please note, all these mentioned solutions will only work if the RequiresQuestionAndAnswer property is set to false in Membership system configuration. If RequiresQuestionAndAnswer is true then the ResetPassword method needs to be passed the security answer, otherwise it will throw an exception.
In case you need RequiresQuestionAndAnswer set to true, you can use this workaround
This code mentioned on posts above is working:
string username = "username";
string password = "newpassword";
MembershipUser mu = Membership.GetUser(username);
mu.ChangePassword(mu.ResetPassword(), password);
But you have to set requiresQuestionAndAnswer="false" in web.config in membership provider tag. If it is true, resetpassword method generate an error "Value can not be null".
In this case you must supply question answer as parameter to ResetPassword.
Use the password you want to set from textbox in place of 123456.
MembershipUser user;
user = Membership.GetUser(userName,false);
user.ChangePassword(user.ResetPassword(),"123456");
#Rob Church is right:
The other answers here are correct but can leave the password in an
unknown state.
However, instead of his solution to do the validation by hand, I would try to change the password using the ResetPassword from token method and catch and show the error:
var user = UserManager.FindByName(User.Identity.Name);
string token = UserManager.GeneratePasswordResetToken(user.Id);
var result = UserManager.ResetPassword(user.Id, token, model.Password);
if (!result.Succeeded){
// show error
}
string username = "UserName";
string userpassword = "NewPassword";
string resetpassword;
MembershipUser mu = Membership.GetUser(username, false);
if (mu == null){
Response.Write("<script>alert('Invalid Username!')</script>");
}
else{
resetpassword = mu.ResetPassword(username);
if (resetpassword != null){
if (mu.ChangePassword(resetpassword, userpassword)){
Response.Write("<script>alert('Password changed successfully!')</script>");
}
}
else{
Response.Write("<script>alert('Oh some error occurred!')</script>");
}
}
string username = "UserName";
string userpassword = "NewPassword";
MembershipUser mu = Membership.GetUser(username, false);
mu.ChangePassword(mu.ResetPassword(username), userpassword);

How do you change a hashed password using asp.net membership provider if you don't know the current password?

Problem, there's no method:
bool ChangePassword(string newPassword);
You have to know the current password (which is probably hashed and forgotten).
This is an easy one that I wasted too much time on. Hopefully this post saves someone else the pain of slapping their forehead as hard as I did.
Solution, reset the password randomly and pass that into the change method.
MembershipUser u = Membership.GetUser();
u.ChangePassword(u.ResetPassword(), "myAwesomePassword");
You are not able to change the password if the requiresQuestionAndAnswer="true"
I got the work around for this
Created two membership providers in web.config
i am using the AspNetSqlMembershipProviderReset provider for reseting the password since it has the requiresQuestionAndAnswer= false where as AspNetSqlMembershipProvider is the default provider used.
i wrote the following code to reset the password for the user.
public bool ResetUserPassword(String psUserName, String psNewPassword)
{
try
{
// Get Membership user details using secound membership provider with required question answer set to false.
MembershipUser currentUser = Membership.Providers["AspNetSqlMembershipProviderReset"].GetUser(psUserName,false);
//Reset the user password.
String vsResetPassword = currentUser.ResetPassword();
//Change the User password with the required password
currentUser.ChangePassword(vsResetPassword, psNewPassword);
//Changed the comments to to force the user to change the password on next login attempt
currentUser.Comment = "CHANGEPASS";
//Check if the user is locked out and if yes unlock the user
if (currentUser.IsLockedOut == true)
{
currentUser.UnlockUser();
}
Membership.Providers["AspNetSqlMembershipProviderReset"].UpdateUser(currentUser); return true;
}
catch (Exception ex)
{
throw ex;
return false;
}
}

Resources