Webforms ASP.NET Identity system reset password - webforms

How can I get the password of a user in the new ASP.NET Identity system using webforms? Or how can I reset without knowing the current one (user forgot password)?

I tied this way to reset password and send it to the user
if (userId != string.Empty)
{
string _newPass = RandomPass();
if (manager.HasPassword(userId))
{
IdentityResult ir1 = manager.RemovePassword(userId);
if (ir1.Succeeded)
{
IdentityResult ir2 = manager.AddPassword(userId, _newPass);
if (ir1.Succeeded && ir2.Succeeded)
{
//Send password to user via sms or email
Response.Redirect("~/RecoverPassword?m=ChangePwdSuccess");
}
else
{
AddErrors(ir1);
AddErrors(ir2);
}
}
}
}

Related

How to set the value for getter and setter method which is optional in spring boot

I am trying to set the value of setIs_active to true when user registration gets complete but I have taken method findByEmail as optional not I am not able to set the value to true.Can ayone tell me what is the reason for that?
public String confirmAccount(String confirmationToken)
{
ConfirmationToken token = confirmationTokenRepository.findByConfirmationToken(confirmationToken);
if(token != null)
{
Optional<User> user = userRepository.findByEmail(token.getUser().getEmail());
user.setIs_active(true);//here I am getting error
userRepository.save(user);//here I am getting error
return "Your account is activated" ;
}
else
return "Error ! Please try again";
}
You get Optional User object not user object.
Way 1:
User user = userRepository.findByEmail(token.getUser().getEmail()).orElse(null);
Way 2:
check is Present then set:
Optional<User> user = userRepository.findByEmail(token.getUser().getEmail());
if (user.isPresent()) {
User user1 = user.get();
//set && save
}
User is an optional, so you cant use the setter on it.
Optional<User> user = userRepository.findByEmail(token.getUser().getEmail());
if(user.isPresent())
{
User myUser = user.get();
myUser.setIs_active(true);
userRepository.save(user);
return "Your account is activated" ;
}

Correct Implementation of Forgot Password AspNetBoilerPlate

Im using aspnetboilerplate (MVC) and wanted to implement a forgot password feature to allow the user to reset their own passwords using a link on the login screen.
I imagine this to work by generating a password reset code which is then emailed to the user.The user follows the link and is taken to a screen allowing them to reset the password.
Im stuck at the initial stage. i started with a copy of the login action after noticing that when attempting to log in the user object was returned. From here i attempt to set a password reset code.
[HttpPost]
[UnitOfWork]
public virtual async Task<JsonResult> ForgotPassword(ForgotPasswordViewModel forgotPasswordModel, string returnUrl = "", string returnUrlHash = "")
{
returnUrl = NormalizeReturnUrl(returnUrl);
if (!string.IsNullOrWhiteSpace(returnUrlHash))
{
returnUrl = returnUrl + returnUrlHash;
}
var loginResult = await _logInManager.LoginAsync(forgotPasswordModel.UsernameOrEmailAddress, "ForgotPassword", GetTenancyNameOrNull());
loginResult.User.SetNewPasswordResetCode();
switch (loginResult.Result)
{
case AbpLoginResultType.Success:
return Json(loginResult);
default:
throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(loginResult.Result, forgotPasswordModel.UsernameOrEmailAddress, GetTenancyNameOrNull());
}
}
Checking the AbpUser table after the
loginResult.User.SetNewPasswordResetCode();
i cannot see any password reset code for the user, they are all null.
Could someone point me in the right direction.
Thanks in advance
Thanks to answer below for being correct, just for completion below is exactly what worked. Obviously ignore the json return at the end
public virtual async Task<JsonResult> ForgotPassword(ForgotPasswordViewModel forgotPasswordModel, string returnUrl = "", string returnUrlHash = "")
{
//var user = await GetUserByChecking(emailAddress);
var user = await _userManager.FindByEmailAsync(forgotPasswordModel.UsernameOrEmailAddress);
if (user == null)
{
throw new UserFriendlyException("User not found!");
}
user.SetNewPasswordResetCode();
//Send an email to user with the below password reset code
/* Uri.EscapeDataString(user.PasswordResetCode) */
return Json("");
}
public class AccountAppService: IAccountAppService
{
public UserManager UserManager {get; set; }
public async Task SendPasswordResetCode(string emailAddress)
{
var user = await UserManager.FindByEmailAsync(emailAddress);
if (user == null)
{
throw new UserFriendlyException("User not found!");
}
user.SetNewPasswordResetCode();
//Send an email to user with the below password reset code
/* Uri.EscapeDataString(user.PasswordResetCode) */
}
}

Background Registration MVC3

Working on an MVC4 Application where users first fill in a form as the starting point. With this form there is a field to provide user email and a unique 9 digit number and other details. What I want to achieve is after submitting this form I want the user to be silently registered using the unique 9 digit number as username, and an auto-generated password hashed and saved as password in the membership(extended simplemembership) database. An email with password will be sent to the user afterwards. I will be grateful for any hints or help in this regards.
After the form is filled, I make the following redirection
return RedirectToAction("AutoRegister", new RouteValueDictionary(new { controller = "Account", action = "AutoRegister", Uname= ViewBag.Uname, Uemail = ViewBag.Uemail }));
and I have the following code in Account Controller
[AllowAnonymous]
public ActionResult AutoRegister()
{
return View();
}
[AllowAnonymous]
[HttpPost]
public ActionResult AutoRegister(RegisterModel model,string Uname, string Uemail)
{
//if (ModelState.IsValid)
if(Uemail!=null && Uname!=null)
{
string Upass = Membership.GeneratePassword(12, 1);
model.Email = Uemail;
model.UserName = Uname;
model.Password = Upass;
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: false, providerUserKey: null, status: out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
return RedirectToAction("Welcome", "OnlineApplication");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
I have also set the RouteConfig to accept the url. When I fill the form it redirects allright to a page with the url parameters populated but nothing happens. The user is not created. As for emailing of password I can fix that with no problems.
Could anyone assist on how I can commit the new user details in database

User isn't authenticated till the next page request

I have this following mvc application
The problem is when Im trying to assign profile values:
// Attempt to register the user
MembershipCreateStatus createStatus = MembershipService.CreateUser(model.Email, model.Password);
if (createStatus == MembershipCreateStatus.Success)
{
//Adding role
MembershipService.AddDefaultRole(model.Email);
FormsService.SignIn(model.Email, false /* createPersistentCookie */);
//Add other initial profile data
HttpContext.Profile["FirstName"] = model.FirstName; //PROBLEM
HttpContext.Profile["LastName"] = model.LastName; //PROBLEM
return RedirectToAction("List", new { area = "", controller = "Requests" });
}
else
{
ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
}
Inside FormsService.SignIn(model.Email, false):
public void SignIn(string email, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
FormsAuthentication.SetAuthCookie(email, createPersistentCookie);
}
How come after calling FormsAuthentication.SetAuthCookie, User isn't yet authenticated?
I'm getting an error b.c. im trying to assign some profile value to anonymous user .
Any idea?
When you set a cookie, it's added to the Response, but the IsAuthenticated bool is set from the Request. After setting the authentication and setting up your session variables, you should redirect to another page, like the home page or the original request.

Login Procedure that does not require a Email Address

I have been asked to create a site where the user isn't required to provide a email to login because of privacy issues. In the past I have simple said this isn't advisable but in this case the client has stringently requested it. My initial thoughts are to potentially create administrators with a email whom could create generic logins (username and a password) and pass them to members of there group on site. Then at least I have a point of contact for login resets and such.
Has anyone had any experience with such situations where they have needed to create logins without the use of a email address? Could you direct me towards any relevant materials or tutorials that may be of use. I'm using MVC3 to develop this project.
I hope I understand your question right and you want to implement a login using username and password instead of email adress and password.
In that case you would have to implement your own custom membership provider and a custom roleprovider if needed.
You want to check the following page for more information:
Custom Membership Provider # Codeproject
EDIT
Fyi you dont need to implement every function - just implement the ones you need.
Custom membership provider from some of my older mvc3 projects. Removed most of the not-implemented functions for shorter code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
namespace Domain.Models
{
public class PlatformMembershipProvider : MembershipProvider
{
public SalesModelContainer ******** = new SalesModelContainer();
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
var user = ********.UserSet.Single(s => s.Email == username);
if (user.Password == oldPassword)
{
user.Password = newPassword;
return true;
}
else
{
return false;
}
}
public override string GetUserNameByEmail(string email)
{
var user = ********.UserSet.Single(s => s.Email == email);
return user.CompanyName;
}
public override void UpdateUser(System.Web.Security.MembershipUser user)
{
throw new NotImplementedException();
}
//TODO: use MD5 for password encryption
public override bool ValidateUser(string username, string password)
{
bool returnValue;
var user = ********.UserSet.SingleOrDefault(s => (s.Email == username) && (s.Password == password));
if (user != null)
returnValue = true;
else
returnValue = false;
return returnValue;
}
}
}

Resources