public UserManager(UserStore store) : base(store) { _emailProvider = new IdentityEmailProvider(); PasswordHasher = new SqlPasswordHasher(); ClaimsIdentityFactory = new ClaimsFactory(); var provider = new DpapiDataProtectionProvider(); UserTokenProvider = new DataProtectorTokenProvider <User>(provider.Create("EmailConfirmation")); //Configure user lockout defaults UserLockoutEnabledByDefault = true; DefaultAccountLockoutTimeSpan = ConfigurationManager.AppSettings["DefaultAccountLockoutTimeSpan"].NoNull(TimeSpan.FromMinutes(5)); MaxFailedAccessAttemptsBeforeLockout = ConfigurationManager.AppSettings["MaxFailedAccessAttemptsBeforeLockout"].NoNull(5); }
/* ------------------ End Create Home ------------------ */ public void SendWelcomeEmail(int id) { var provider = new DpapiDataProtectionProvider("VideoManager"); UserManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>( provider.Create("EmailConfirmation")); FuneralHome home = db.FuneralHomes.Find(id); var code = UserManager.GeneratePasswordResetToken(home.UserId); home.TempAccessToken = code; db.Entry(home).State = EntityState.Modified; db.SaveChanges(); Email.sendWelcomeEmail(home); }
public static UserManager <ApplicationIdentityUser, Int32> CreateUserManager(DbContext context) { var manager = new UserManager <ApplicationIdentityUser, Int32>(new UserStore <ApplicationIdentityUser, ApplicationIdentityRole, Int32, ApplicationIdentityUserLogin, ApplicationIdentityUserRole, ApplicationIdentityUserClaim>(context)); // Configure validation logic for usernames manager.UserValidator = new UserValidator <ApplicationIdentityUser, Int32>(manager) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = false }; // Configure validation logic for passwords manager.PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = false, RequireDigit = false, RequireLowercase = false, RequireUppercase = false, }; // Configure user lockout defaults manager.UserLockoutEnabledByDefault = true; manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); manager.MaxFailedAccessAttemptsBeforeLockout = 5; // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user // You can write your own provider and plug in here. manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider <ApplicationIdentityUser, Int32> { MessageFormat = "Your security code is: {0}" }); manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider <ApplicationIdentityUser, Int32> { Subject = "SecurityCode", BodyFormat = "Your security code is {0}" }); manager.EmailService = new EmailService(); manager.SmsService = new SmsService(); var provider = new DpapiDataProtectionProvider("Wizitup"); manager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationIdentityUser, Int32>( provider.Create("ASP.NET Identity")); return(manager); }
public async Task <ActionResult> PasswordReset(PasswordResetModel model) { if (ModelState.IsValid) { var user = await UserManager.FindByNameAsync(model.Username); if (user == null) { // Don't reveal that the user does not exist or is not confirmed return(View("PasswordReset")); } if (model.NewPassword != model.ConfirmPassword) { ModelState.AddModelError("", "Passwords do not match"); return(View("PasswordReset")); } bool isValidPassword = UserManager.CheckPassword(user, model.CurrentPassword); //IdentityResult validatePasswordResult = await UserManager.PasswordValidator<IdentityUser>().ValidateAsync(model.CurrentPassword); if (isValidPassword) { var provider = new DpapiDataProtectionProvider("SampleAppName"); UserManager.UserTokenProvider = new DataProtectorTokenProvider <IdentityUser>( provider.Create("UserToken")); string resetToken = await UserManager.GeneratePasswordResetTokenAsync(user.Id); IdentityResult passwordChangeResult = await UserManager.ResetPasswordAsync(user.Id, resetToken, model.NewPassword); if (passwordChangeResult.Succeeded) { return(View("~/Views/ResetPassword/ResetPasswordConfirmation.cshtml")); } else { ModelState.AddModelError("", "Could not Reset Password"); return(View("PasswordReset")); } } else { ModelState.AddModelError("", "Incorrect Password"); return(View("PasswordReset")); } } // If we got this far, something failed, redisplay form return(View(model)); }
protected void btn_reset_Click(object sender, EventArgs e) { if (IsValid) { var provider = new DpapiDataProtectionProvider("provider"); var user_manager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext())); user_manager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>( provider.Create("EmailConfirmation")); ApplicationUser user = user_manager.FindByEmail(txt_email.Text); if (user == null) { FailureText.Text = "The user does not exist."; ErrorMessage.Visible = true; return; } else { // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send email with the code and the redirect to reset password page string code = user_manager.GeneratePasswordResetToken(user.Id); string callbackUrl = IdentityHelper.GetResetPasswordRedirectUrl(code, Request, txt_email.Text); //sending email string system_mail_account = WebConfigurationManager.AppSettings["system email account"]; string system_mail_password = WebConfigurationManager.AppSettings["system email password"]; string system_mail_stmp = WebConfigurationManager.AppSettings["system email smtp"]; string userEmailAddress = user.Email; MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient(system_mail_stmp); mail.From = new MailAddress(system_mail_account); mail.To.Add(userEmailAddress); mail.Subject = "Library password reset request"; string bodyHtml = "<h4>Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>.</h4>"; AlternateView body = AlternateView.CreateAlternateViewFromString(bodyHtml, new System.Net.Mime.ContentType("text/html")); mail.AlternateViews.Add(body); SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential(system_mail_account, system_mail_password); SmtpServer.EnableSsl = true; SmtpServer.Send(mail); loginForm.Visible = false; ErrorMessage.Visible = true; DisplayEmail.Visible = true; } } }
public ActionResult ResetPassword(string userString, string password, string confirmPassword) { var userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>(); var resultEmail = userManager.FindByEmail(userString); var resultName = userManager.FindByName(userString); if (resultName == null && resultEmail == null) { ViewBag.ResetPasswordResult = "User with such email or username is not found"; return(View()); } ApplicationUser user; if (resultName?.Email != null) { user = resultName; } else if (resultEmail != null) { user = resultEmail; } else { return(View()); } if (password != confirmPassword) { ViewBag.ResetPasswordResult = "Your password has not been changed! The password and confirm password fields do not match!"; return(View()); } var provider = new DpapiDataProtectionProvider("Sample"); userManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>( provider.Create("ResetingPassword")); string token = userManager.GeneratePasswordResetToken(user.Id); var result = userManager.ResetPassword(user.Id, token, password); if (result.Succeeded) { _logger.Info("user set a new password " + User.Identity.Name); return(View("ResetPasswordConfirmation")); } else { ViewBag.ResetPasswordResult = "Your password has not been changed!"; } return(View()); }
public ApplicationUserManager(IUserStore <ApplicationUser, int> store) : base(store) { // Configurando validator para nome de usuario UserValidator = new UserValidator <ApplicationUser, int>(this) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Logica de validação e complexidade de senha PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = false, RequireDigit = false, RequireLowercase = false, RequireUppercase = false, }; // Configuração de Lockout UserLockoutEnabledByDefault = true; DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); MaxFailedAccessAttemptsBeforeLockout = 5; // Providers de Two Factor Autentication RegisterTwoFactorProvider("Código via SMS", new PhoneNumberTokenProvider <ApplicationUser, int> { MessageFormat = "Seu código de segurança é: {0}" }); RegisterTwoFactorProvider("Código via E-mail", new EmailTokenProvider <ApplicationUser, int> { Subject = "Código de Segurança", BodyFormat = "Seu código de segurança é: {0}" }); // Definindo a classe de serviço de e-mail EmailService = new EmailService(); // Definindo a classe de serviço de SMS SmsService = new SmsService(); var provider = new DpapiDataProtectionProvider("Thiago"); var dataProtector = provider.Create("ASP.NET Identity"); UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser, int>(dataProtector); }
public ApplicationUserManager(IUserStore <ApplicationUser> store) : base(store) { // Configuring validator for username UserValidator = new UserValidator <ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Password's validation and complexity PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true, }; // Lockout configutation UserLockoutEnabledByDefault = true; DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); MaxFailedAccessAttemptsBeforeLockout = 5; // Two factor authentication provider RegisterTwoFactorProvider("SMS Code", new PhoneNumberTokenProvider <ApplicationUser> { MessageFormat = "Your safety code is: {0}" }); RegisterTwoFactorProvider("E-mail Code", new EmailTokenProvider <ApplicationUser> { Subject = "Safety Code", BodyFormat = "Your safety code is: {0}" }); // E-mail service class definition EmailService = new EmailService(); // SMS service class definition SmsService = new SmsService(); var provider = new DpapiDataProtectionProvider(nameof(DAFA)); var dataProtector = provider.Create("ASP.NET Identity"); UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(dataProtector); }
public ApplicationUserManager(IUserStore <ApplicationUser> store) : base(store) { // Configure validation logic for usernames UserValidator = new UserValidator <ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Configure validation logic for passwords PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true, }; // Configure user lockout defaults UserLockoutEnabledByDefault = true; DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); MaxFailedAccessAttemptsBeforeLockout = 5; // Register two factor authentication providers. // This application uses Phone and Emails as a step of receiving a code for verifying the user // You can write your own provider and plug it in here. RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider <ApplicationUser> { MessageFormat = "Your security code is {0}" }); RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <ApplicationUser> { Subject = "Security Code", BodyFormat = "Your security code is {0}" }); //Define email and sms services EmailService = new EmailService(); SmsService = new SmsService(); var provider = new DpapiDataProtectionProvider("MvcAppExample"); var dataProtector = provider.Create("ASP.NET Identity"); UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(dataProtector); }
public async Task <ActionResult> Index(ChangeModel model) { if (ModelState.IsValid) { string userId = User.Identity.GetUserId(); if (model.Email != null) { var user = await UserManager.FindByIdAsync(userId); user.Email = model.Email; user.UserName = model.Email; IdentityResult emailResult = await UserManager.UpdateAsync(user); //IdentityResult nameResult = await UserManager. if (!emailResult.Succeeded) // TODO: иначе выводить "емаил успешно изменен" { foreach (var error in emailResult.Errors) { ModelState.AddModelError("", error); } ModelState.AddModelError("", "Почта не обновлена."); } } if (model.Password != null) { var provider = new DpapiDataProtectionProvider("TaskScheduler"); UserManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>( provider.Create("PasswordReset")); string resetToken = await UserManager.GeneratePasswordResetTokenAsync(userId); IdentityResult passwordChangeResult = await UserManager.ResetPasswordAsync(userId, resetToken, model.Password); if (!passwordChangeResult.Succeeded) // TODO: иначе выводить "пароль успешно изменен" { foreach (var error in passwordChangeResult.Errors) { ModelState.AddModelError("", error); } ModelState.AddModelError("", "Пароль не изменен."); } } } model.Password = null; model.PasswordConfirm = null; return(View(model)); }
public AppUserManager(IUserStore <User, Guid> store, IUnitOfWork unitOfWork, IAppRoleManager roleManager, IEmailSecuriyService emailSecuriyService) : base(store) { _unitOfWork = unitOfWork; _roleManager = roleManager; _users = _unitOfWork.Set <User>(); _roles = _unitOfWork.Set <Role>(); this.EmailService = emailSecuriyService; var provider = new DpapiDataProtectionProvider("Sample"); this.UserTokenProvider = new DataProtectorTokenProvider <User, Guid>( provider.Create("EmailConfirmation")); UserLockoutEnabledByDefault = true; DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(10); MaxFailedAccessAttemptsBeforeLockout = 5; _currUser = new Lazy <User>(GetCurrentUser, false); }
public AppUserManager(IUserStore <AppUser> store) : base(store) { var provider = new DpapiDataProtectionProvider("SalesStatistics"); UserTokenProvider = new DataProtectorTokenProvider <AppUser>(provider.Create("Passwords")); PasswordValidator = new PasswordValidator() { RequireDigit = false, RequiredLength = 4, RequireLowercase = false, RequireNonLetterOrDigit = false, RequireUppercase = false }; UserValidator = new AppUserValidator(this); }
private void ConfigureUserManager() { UserValidator = new UserValidator <AppUser>(this) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = false, RequireDigit = false, RequireLowercase = false, RequireUppercase = false }; UserLockoutEnabledByDefault = true; DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); MaxFailedAccessAttemptsBeforeLockout = 5; RegisterTwoFactorProvider("Código via SMS", new PhoneNumberTokenProvider <AppUser> { MessageFormat = "Seu código de segurança é: {0}" }); RegisterTwoFactorProvider("Código via E-mail", new EmailTokenProvider <AppUser> { Subject = "Código de Segurança", BodyFormat = "Seu código de segurança é: {0}" }); EmailService = new EmailService(); SmsService = new SmsService(); using (var ctx = new IdentityDbContext()) { var flag = ctx.Users.Include(x => x.Claims).SelectMany(x => x.Claims).Any(); } var provider = new DpapiDataProtectionProvider("Identity_Exemplo"); var dataProtector = provider.Create("UserToken"); UserTokenProvider = new DataProtectorTokenProvider <AppUser, string>(dataProtector); }
public async System.Threading.Tasks.Task <ActionResult> Create([Bind(Include = "Email,Name,PhoneNumber,Username,AccountType, Password, ConfirmPassword")] RegisterViewModel account) { var UserStore = new UserStore <Account>(db); var UserManager = new UserManager <Account>(UserStore); if (isAdmin() == false || getAccount() == null) { this.AddNotification("Sorry! You do not have permisson to access this page!", NotificationType.ERROR); return(RedirectToAction("Index", "Home")); } if (ModelState.IsValid) { Account finalAccount = new Models.Account() { Email = account.Email, UserName = account.Username, PhoneNumber = account.PhoneNumber, AccountType = account.AccountType, Name = account.Name }; //Adds the new user to the database var userCreateResult = UserManager.Create(finalAccount, account.Password); if (userCreateResult.Succeeded) { //if the account creation succeeds, then send confirmation email to recipient var client = new DpapiDataProtectionProvider("ASP.NET Identity"); UserManager.UserTokenProvider = new DataProtectorTokenProvider <Account>( client.Create("ASP.NET Identity")); // Send an email with this link string code = await UserManager.GenerateEmailConfirmationTokenAsync(finalAccount.Id); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = finalAccount.Id, code = code }, protocol: Request.Url.Scheme); await UserManager.SendEmailAsync(finalAccount.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(RedirectToAction("Index")); } return(RedirectToAction("Index")); } return(View(account)); }
public ActionResult ConfirmEmail(string userId, string code) { var provider = new DpapiDataProtectionProvider("Sample"); UserManager.UserTokenProvider = new DataProtectorTokenProvider <MyUser>( provider.Create("EmailConfirmation")); IdentityResult result = UserManager.ConfirmEmail(userId, code); if (result.Succeeded) { return(RedirectToAction("Index", "Account")); } else { ModelState.AddModelError("", "Что-то пошло не так"); } return(RedirectToAction("Index", "Account")); }
/// <summary> /// Systematically confirms the user's email if the url link sent to the user's email /// has been clicked. Only the referred user has access to this email link, which will /// automatically confirm the email upon clicking. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Page_Load(object sender, EventArgs e) { // Obtain code and user Id for email confirmation string code = IdentityHelper.GetCodeFromRequest(Request); string userId = IdentityHelper.GetUserIdFromRequest(Request); ApplicationUser User = new ApplicationUser(); var manager = new UserManager(); User = manager.FindById(userId); var provider = new DpapiDataProtectionProvider("ProjectManagement"); manager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>( provider.Create("EmailConfirmation")); // Confirms email based on received code and user id. IdentityResult validToken = manager.ConfirmEmail(User.Id, code); }
public override bool AuthorizeHubConnection(HubDescriptor hubDescriptor, IRequest request) { var dataProtectionProvider = new DpapiDataProtectionProvider(); var secureDataFormat = new TicketDataFormat(dataProtectionProvider.Create()); // authenticate by using bearer token in query string var token = request.QueryString.Get(OAuthDefaults.AuthenticationType); var ticket = secureDataFormat.Unprotect(token); if (ticket != null && ticket.Identity != null && ticket.Identity.IsAuthenticated) { // set the authenticated user principal into environment so that it can be used in the future request.Environment["server.User"] = new ClaimsPrincipal(ticket.Identity); return(true); } else { return(false); } }
public ApplicationUserManager Create(IUserStore <AppUser, long> store) { //var manager = new ApplicationUserManager( // new UserStore<User, Role, long, UserLogin, UserRole, UserClaim>(context.Get<DiscountappDbContext>())); //this.Store = new UserStore<AppUser, AppRole, long, AppUserLogin, AppUserRole, AppUserClaim>(null); this.UserValidator = new UserValidator <AppUser, long>(this) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; this.PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = false, RequireDigit = true, RequireLowercase = false, RequireUppercase = false }; //Двухфакторная аутентификация this.RegisterTwoFactorProvider( "PhoneCode", new PhoneNumberTokenProvider <AppUser, long> { MessageFormat = "Ваш код безопасности {0}" }); this.RegisterTwoFactorProvider( "EmailCode", new EmailTokenProvider <AppUser, long> { Subject = "Код безопасности", BodyFormat = "Ваш код безопасности {0}" }); this.EmailService = new EmailService(); this.SmsService = new SmsService(); var provider = new DpapiDataProtectionProvider("Sample"); this.UserTokenProvider = new DataProtectorTokenProvider <AppUser, long>(provider.Create("EmailConfirmation"));// as IUserTokenProvider<AppUser, long>; return(this); }
public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model) { var background = new DbTables.BackgroundImage(); var backgroundList = _context.BackgroundImage.ToList(); if (backgroundList.Any()) { background = backgroundList.First(); if (background.Enabeled) { ViewBag.Style = "background:url('/File/Background?id=" + background.Image.FileId + "') no-repeat center center fixed;-webkit-background-size: cover;-moz-background-size: cover;-o-background-size: cover;background-size: cove;overflow-x: hidden;"; ViewBag.BackGround = "background-color:transparent;"; } } if (ModelState.IsValid) { var user = await UserManager.FindByNameAsync(model.Email); if (user == null) { return(View("ForgotPasswordConfirmation")); } var provider = new DpapiDataProtectionProvider("ButterflyFriends"); UserManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(provider.Create("Passwordresetting")); var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code, area = "" }, Request.Url.Scheme); if (!SendEmail(user, callbackUrl)) { return(RedirectToAction("Login", "Account", new { message = "Sendgrid er ikke konfigurert for applikasjonen eller slått av" })); } return(RedirectToAction("ForgotPasswordConfirmation", "Account")); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (!ModelState.IsValid) { return(View(model)); } var usuario = await UserManager.FindByEmailAsync(model.Email); if (usuario == null) { TempData["FlashError"] = "Cuenta de correo incorrecta"; return(RedirectToAction("ForgotPassword", "Account")); } try { var provider = new DpapiDataProtectionProvider("Sample"); UserManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>( provider.Create("EmailConfirmation")); var code = UserManager.GeneratePasswordResetToken(usuario.Id); var commonManager = new CommonManager(); await commonManager.SendHtmlMail("Portal de Proveedores del Grupo Nazan - Reestablecer Contraseña", string.Format( "Estimado {0},<BR/>Por acceda al al siguiente link para cambiar su contraseña: <a href=\"{1}\" title=\"Recuperar Contraseña\">Cambio de contraseña</a>", usuario.Nombre + " " + usuario.Apellido, Url.Action("ResetPassword", "Account", new { token = usuario.Id, code, email = usuario.Email }, Request.Url.Scheme)), usuario.Email); return(RedirectToAction("ForgotPasswordConfirmation", "Account")); } catch (Exception) { ModelState.AddModelError("", "Error enviando correo para restablecer su contraseña, por favor Intente mas tarde."); return(View(model)); } }
public ApplicationUserManager(IUserStore <ApplicationUser> store, IEmailService emailService, ISmsService smsService) : base(store) { UserValidator = new UserValidator <ApplicationUser>(this) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; PasswordValidator = new PasswordValidator { RequiredLength = 4, RequireNonLetterOrDigit = false, RequireDigit = false, RequireLowercase = false, RequireUppercase = false, }; UserLockoutEnabledByDefault = true; DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5); MaxFailedAccessAttemptsBeforeLockout = 5; RegisterTwoFactorProvider("SMS", new PhoneNumberTokenProvider <ApplicationUser> { MessageFormat = "Seu código de segurança é: {0}" }); RegisterTwoFactorProvider("Email", new EmailTokenProvider <ApplicationUser> { Subject = "Código de Segurança", BodyFormat = "Seu código de segurança é: {0}" }); EmailService = emailService; SmsService = smsService; var provider = new DpapiDataProtectionProvider("AHAS"); var dataProtector = provider.Create("PortalObrigacoes"); UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(dataProtector); }
private void CreateRolesandUsers() { ApplicationDbContext context = new ApplicationDbContext(); var provider = new DpapiDataProtectionProvider("ArticleReviewSystem"); var roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context)); var UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context)); if (!roleManager.RoleExists("Admin")) { var role = new IdentityRole(); role.Name = "Admin"; roleManager.Create(role); var user = new ApplicationUser { UserName = "******", Email = "*****@*****.**", Name = "Super", Surname = "Admin", RegistrationDate = DateTime.Now }; string password = "******"; var superAdminAccount = UserManager.Create(user, password); if (superAdminAccount.Succeeded) { var result1 = UserManager.AddToRole(user.Id, "Admin"); UserManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>( provider.Create("EmailConfirmation")); var token = UserManager.GenerateEmailConfirmationToken(user.Id); var result = UserManager.ConfirmEmail(user.Id, token); } } if (!roleManager.RoleExists("User")) { var role = new IdentityRole(); role.Name = "User"; roleManager.Create(role); } }
public async Task <ActionResult> ResetPassword(ResetPasswordModel model, string userId, string code) { var provider = new DpapiDataProtectionProvider("Sample"); var userManager = new UserManager <MyUser>(new UserStore <MyUser>()); UserManager.UserTokenProvider = new DataProtectorTokenProvider <MyUser>( provider.Create("ResetPassword")); IdentityResult result = await UserManager.ResetPasswordAsync(userId, code, model.Password); if (result.Succeeded) { return(RedirectToAction("Login", "Account")); } else { ModelState.AddModelError("", "Что-то пошло не так"); } return(RedirectToAction("Index", "Account")); }
protected void btn_password_renew_Click(object sender, EventArgs e) { var provider = new DpapiDataProtectionProvider("provider"); var user_manager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext())); user_manager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>( provider.Create("EmailConfirmation")); ApplicationUser user = user_manager.FindByEmail(Request.QueryString["user_email"].ToString()); string code = IdentityHelper.GetCodeFromRequest(Request); var result = user_manager.ResetPassword(user.Id, code, txt_password.Text); if (result.Succeeded) { Response.Redirect("~/message" + "?msg=" + "Password has reset. Please use your new password to login."); } else { ErrorMessage.Text = result.Errors.FirstOrDefault(); } }
public async Task <ActionResult> SetPassword(SetPasswordViewModel model) { var background = new DbTables.BackgroundImage(); var backgroundList = _context.BackgroundImage.ToList(); if (backgroundList.Any()) { background = backgroundList.First(); if (background.Enabeled) { ViewBag.Style = "background:url('/File/Background?id=" + background.Image.FileId + "') no-repeat center center fixed;-webkit-background-size: cover;-moz-background-size: cover;-o-background-size: cover;background-size: cove;overflow-x: hidden;"; ViewBag.BackGround = "background-color:transparent;"; } } if (!ModelState.IsValid) { return(View(model)); } var user = await UserManager.FindByIdAsync(model.userId); if (user == null) { return(RedirectToAction("SetPasswordConfirmation", "Account")); } var provider = new DpapiDataProtectionProvider("ButterflyFriends"); UserManager.UserTokenProvider = new DataProtectorTokenProvider <ApplicationUser>(provider.Create("Passwordresetting")); var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.NewPassword); if (result.Succeeded) { return(RedirectToAction("SetPasswordConfirmation", "Account")); } AddErrors(result); return(View()); }
public static AppUserManager GetInstance(IdentityFactoryOptions <AppUserManager> option, IOwinContext owinContext) { var dbContext = new RuporDbContext(); var usermgr = new AppUserManager(new UserStore <UserEntity>(dbContext)); usermgr.PasswordValidator = new PasswordValidator { RequireDigit = true, RequiredLength = 8, RequireUppercase = true, RequireLowercase = true, }; usermgr.UserValidator = new UserValidator <UserEntity>(usermgr) { RequireUniqueEmail = true, AllowOnlyAlphanumericUserNames = true }; var tokenProvider = new DpapiDataProtectionProvider("therupor"); usermgr.UserTokenProvider = new DataProtectorTokenProvider <UserEntity>(tokenProvider.Create("EmailConfirmation")); return(usermgr); }
public async Task <JsonResult> SendForgetPasswordEmail(string UserName, string email) { eCommerceContext context = new eCommerceContext(); JsonResult jResult = new JsonResult(); eCommerceUser user = await userApiService.GetUser(UserName, email); var UserManager = new UserManager <eCommerceUser>(new UserStore <eCommerceUser>(context)); var provider = new DpapiDataProtectionProvider("SampleAppName"); UserManager.UserTokenProvider = new DataProtectorTokenProvider <eCommerceUser>( provider.Create("SampleTokenName")); string Code = UserManager.GeneratePasswordResetToken(user.Id); var callbackUrl = "http://jomlahjo.com/reset-password?userId=" + user.Id + "&code=" + Code; await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>"); //For more security alawys return True jResult.Data = new { Success = true, Message = "Check your Email for reset your password" }; return(jResult); }
public async Task <ActionResult> ForgotPass(ForgotModel model) { var user = await userManager.FindByEmailAsync(model.Email); if (user != null) { var provider = new DpapiDataProtectionProvider("MVC_Prices2"); userManager.UserTokenProvider = new DataProtectorTokenProvider <AppUser>( provider.Create("MVC_Prices2")); string code = await userManager.GeneratePasswordResetTokenAsync(user.Id); string message; var callbackUrl = Url.Action("ResetPass", "Account", new { UserId = user.Id, code = code }, protocol: Request.Url.Scheme); message = "To reset your password please click <a href=\"" + callbackUrl + "\">here</a>"; ModelState.AddModelError("", "Please check your email."); await SendEmail(user.Email, "Reset Your Password", message); } else { ModelState.AddModelError("", "There is no user signed with this e-mail. "); } return(View()); }
public async Task <string> GenerateEmailConfirmationTokenAsync(string userId) { try { var provider = new DpapiDataProtectionProvider("Sample"); this._userManager.UserTokenProvider = new DataProtectorTokenProvider <AppUser>(provider.Create("EmailConfirmation")); var result = await this._userManager.GenerateEmailConfirmationTokenAsync(userId); return(result); } catch (Exception ex) { throw new Exception(ex.Message, ex.InnerException); } }
public async Task <IdentityResult> ConfirmEmailAsync(string userid, string code) { IdentityResult response; try { var provider = new DpapiDataProtectionProvider("Sample"); this._userManager.UserTokenProvider = new DataProtectorTokenProvider <AppUser>(provider.Create("EmailConfirmation")); response = await this._userManager.ConfirmEmailAsync(userid, code); } catch (Exception ex) { throw new Exception(ex.Message, ex.InnerException); } return(response); }