private static void SetupRolesAndUsers(DbContext context) { var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); // add roles if (!roleManager.RoleExists(Role.Guest.ToString())) roleManager.Create(new IdentityRole(Role.Guest.ToString())); if (!roleManager.RoleExists(Role.Supplier.ToString())) roleManager.Create(new IdentityRole(Role.Supplier.ToString())); if (!roleManager.RoleExists(Role.Deactivated.ToString())) roleManager.Create(new IdentityRole(Role.Deactivated.ToString())); if (!roleManager.RoleExists(Role.User.ToString())) roleManager.Create(new IdentityRole(Role.User.ToString())); var adminRole = roleManager.FindByName(Role.Admin.ToString()); if (adminRole == null) { adminRole = new IdentityRole(Role.Admin.ToString()); roleManager.Create(adminRole); } #if DEBUG //add admin user var admin = userManager.Find(Admin_User, Admin_Pass); if (admin == null) { admin = new ApplicationUser { UserName = Admin_User, Email = Admin_Mail, EmailConfirmed = true }; var result = userManager.Create(admin, Admin_Pass); // TODO: verify returned IdentityResult userManager.AddToRole(admin.Id, Role.Admin.ToString()); result = userManager.SetLockoutEnabled(admin.Id, false); } var rolesForUser = userManager.GetRoles(admin.Id); if (!rolesForUser.Contains(adminRole.Name)) { var result = userManager.AddToRole(admin.Id, adminRole.Name); } //add normal user if (userManager.Find("[email protected]", "1q2w3e4r") == null) { var user = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]", EmailConfirmed = true }; userManager.Create(user, "1q2w3e4r"); // TODO: verify returned IdentityResult userManager.AddToRole(user.Id, Role.User.ToString()); } #endif }
protected void LogIn(object sender, EventArgs e) { if (IsValid) { // Validate the user password var manager = new UserManager(); var returnUrl = Request.QueryString["ReturnUrl"]; ApplicationUser user = manager.Find(UserName.Text, Password.Text); if (user != null) { IdentityHelper.SignIn(manager, user, RememberMe.Checked); if (returnUrl == null) { IdentityHelper.RedirectToReturnUrl("~/Game/User-Home.aspx", Response); } else { IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } } else { FailureText.Text = "Invalid username or password."; ErrorMessage.Visible = true; } } }
protected void btnSignIn_OnClick(object sender, EventArgs e) { UserStore<IdentityUser> userStore = new UserStore<IdentityUser>(); userStore.Context.Database.Connection.ConnectionString = System.Configuration.ConfigurationManager. ConnectionStrings["GarageDBConnectionString"].ConnectionString; UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore); //to retrieve a user from the database var user = manager.Find(txtUserName.Text, txtPassword.Text); if (user != null) { //Call OWIN functionality var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); //Sign in user authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, userIdentity); //Redirect user to homepage Response.Redirect("~/Index.aspx"); } else { litStatus.Text = "Invalid username or password"; } }
protected void btnLogin_Click(object sender, EventArgs e) { UserStore<IdentityUser> userStore = new UserStore<IdentityUser>(); userStore.Context.Database.Connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["CANDZOILPDBConnectionString"].ConnectionString; UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore); var user = manager.Find(txtUserName.Text, txtPassword.Text); if (user != null) { var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties{ IsPersistent = false }, userIdentity); Response.Redirect("~/Index.aspx"); }else{ litStatus.Text = "Invalid username or password"; } }
protected void SignIn(object sender, EventArgs e) { var userStore = new UserStore<IdentityUser>(); var userManager = new UserManager<IdentityUser>(userStore); var user = userManager.Find(UserName.Text, Password.Text); try { if (user != null) { var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity); Response.Redirect("admin/main-menu.aspx"); } else { StatusText.Text = "Invalid username or password."; LoginStatus.Visible = true; } } catch (Exception) { Server.Transfer("/error.aspx"); } }
public override void Validate(string userNameOrEmail, string password) { try { using (var context = new IdentityDbContext()) { using (var userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(context))) { string userName = userNameOrEmail; if (userNameOrEmail.Contains('@')) { var userForEmail = userManager.FindByEmail(userNameOrEmail); if (userForEmail != null) { userName = userForEmail.UserName; } } var user = userManager.Find(userName, password); if (user == null) { var msg = String.Format("Unknown Username {0} or incorrect password {1}", userNameOrEmail, password); Trace.TraceWarning(msg); throw new FaultException(msg); } } } } catch (Exception e) { var msg = e.Message; Trace.TraceWarning(msg); throw new FaultException(msg); } }
public AuthModule() : base("/api") { Post["/authenticate"] = x => { var bind = this.Bind<LoginRequest>(); UserManager<User> manager = new UserManager<User>(new UserStore()); var user = manager.Find(bind.Username, bind.Password); if (user == null) { return new Response { StatusCode = HttpStatusCode.Unauthorized }; } else { var response = new Response { StatusCode = HttpStatusCode.OK }; return response.WithCookie("sq-valid", user.UserName, DateTime.Now.AddMinutes(5)); } }; Get["/logout"] = x => { var response = new Response { StatusCode = HttpStatusCode.OK }; return response.WithCookie("sq-valid", null, DateTime.Now.AddYears(-5)); }; }
protected void btnSave_Click(object sender, EventArgs e) { //try //{ var userStore = new UserStore<IdentityUser>(); var userManager = new UserManager<IdentityUser>(userStore); var user = userManager.Find(txtUserName.Text, txtPassword.Text); if (user != null) { var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity); Response.Redirect("~/admin/MainMenu.aspx"); } else { lblStatus.Text = "Invalid username or password."; } //} //catch (System.Exception) //{ // Response.Redirect("/MainMenu.aspx"); //} }
/** Login - authenticate entered user credientials. **/ protected void btnLogin_Click(object sender, EventArgs e) { try { var userStore = new UserStore<IdentityUser>(); var userManager = new UserManager<IdentityUser>(userStore); var user = userManager.Find(txtUsername.Text, txtPassword.Text); if (user != null) { var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity); Response.Redirect("admin/bibleMenu.aspx"); } else { lblStatus.Text = "Invalid username or password."; } } catch (Exception ex) { Response.Redirect("/errors.aspx"); } }
protected void LoginButton_Click(object sender, EventArgs e) { // create new userStore and userManager objects var userStore = new UserStore<IdentityUser>(); var userManager = new UserManager<IdentityUser>(userStore); // search for and create a new user object var user = userManager.Find(UserNameTextBox.Text, PasswordTextBox.Text); // if a match is found for the user if(user != null) { // authenticate and login our new user var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); // Sign the user authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity); // Redirect to Main Menu Response.Redirect("~/Contoso/MainMenu.aspx"); } else { // throw an error to the AlertFlash div StatusLabel.Text = "Invalid Username or Password"; AlertFlash.Visible = true; } }
protected void LogIn(object sender, EventArgs e) { if (IsValid) { // Validate the user password var manager = new UserManager(); ApplicationUser user = manager.Find(UserName.Text, Password.Text); if (user != null) { IdentityHelper.SignIn(manager, user, RememberMe.Checked); SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["J1500ConnectionString"].ConnectionString); conn.Open(); SqlCommand cmd3 = new SqlCommand("Update AspNetUsers set LastLogin=GETDATE() where id='" + user.Id + "'", conn); cmd3.ExecuteNonQuery(); conn.Close(); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { FailureText.Text = "Invalid username or password."; ErrorMessage.Visible = true; } } }
protected void LogIn(object sender, EventArgs e) { if (IsValid) { // Validate the user password var manager = new UserManager(); ApplicationUser user = manager.Find(UserName.Text, Password.Text); if (user != null) { IdentityHelper.SignIn(manager, user, RememberMe.Checked); // call db to get number of saved cars for logged in user userName = UserName.Text; if (!userName.Equals("")) { Application["userName"] = userName; loadNextPage(userName); } } else { FailureText.Text = "Invalid username or password."; ErrorMessage.Visible = true; } } }
protected void btnLogin_Click(object sender, EventArgs e) { //declare the collection of users UserStore<IdentityUser> userStore = new UserStore<IdentityUser>(); //declare the user manager UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore); //try to find the user IdentityUser user = manager.Find(txtEmpNum.Text, txtPassword.Text); if (user == null) lblStatus.Text = "Username or Password is incorrect"; else { if (txtEmpNum.Text == "Administrator") { IdentityResult userResult = manager.AddToRole(user.Id, "Admin"); } //add user to role //authenticate user var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(userIdentity); Response.Redirect("~/MainPage.aspx"); } }
//public OrderDetail UpdateOrderDetail(string id,DateTime deliveryTime, int ) //{ // mergedEntities db = new mergedEntities(); // OrderDetail orderDetail = db.OrderDetails.Where(o => o.Id == id) // .FirstOrDefault(); // orderDetail.orderNumber = productID; // orderDetail.deliveryTime = deliveryTime; // db.SaveChanges(); // return orderDetail; //} //Get profile details // change public AspNetUser to public RegisteredUser public RegisteredUser GetProfileDetail(Login login) { UserStore<IdentityUser> userStore = new UserStore<IdentityUser>(); UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore); IdentityUser identityUser = manager.Find(login.UserName, login.Password); mergedEntities db = new mergedEntities(); RegisteredUser USER = new RegisteredUser(); var query = from a in db.AspNetUsers where (a.Id == identityUser.Id) select new { ID = a.Id, UserName = a.UserName, PhoneNumber = a.PhoneNumber, Email = a.Email, }; foreach (var item in query) { USER.Id = item.ID; USER.UserName = item.UserName; USER.TelNumber = item.PhoneNumber; USER.Email = item.Email; } return USER; }
public ActionResult Index(Login login) { // UserStore and UserManager manages data retreival. UserStore<IdentityUser> userStore = new UserStore<IdentityUser>(); UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore); IdentityUser identityUser = manager.Find(login.UserName, login.Password); if (ModelState.IsValid) { if (ValidLogin(login)) { IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication; authenticationManager .SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, login.UserName), }, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role); // SignIn() accepts ClaimsIdentity and issues logged in cookie. authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, identity); return RedirectToAction("SecureArea", "Home"); } } return View(); }
protected void btnLogin_Click(object sender, EventArgs e) { try { //store user information into variables var userStore = new UserStore<IdentityUser>(); var userManager = new UserManager<IdentityUser>(userStore); var user = userManager.Find(txtUsername.Text, txtPassword.Text); //if there is a current user if (user != null) { //if the user is authenticated, redirect to products page var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity); Response.Redirect("/admin/products.aspx", false); } else //if any fields are blank { //show a message to the user lblStatusMessage.Text = "Invalid username or password."; lblStatusMessage.Visible = true; } } catch (Exception) { Response.Redirect("/Error.aspx"); } }
protected void SignIn(object sender, EventArgs e) { var userStore = new UserStore<IdentityUser>(); var userManager = new UserManager<IdentityUser>(userStore); IdentityUser user = userManager.Find(tbUsername.Text, tbPassword.Text); //if user info is found if (user != null) { //create cookie IAuthenticationManager authenticationManager = HttpContext.Current.GetOwinContext().Authentication; ClaimsIdentity userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); //sign in authenticationManager.SignIn(new AuthenticationProperties {IsPersistent = false}, userIdentity); var returnUrl = Request.QueryString["returnUrl"]; //if user came from different page, redirect to that one. Otherwise redirect to main page. Response.Redirect(returnUrl ?? "~/default.aspx"); } //if not, show error message. else { lblConfirmationText.Text = "Invalid username or password."; } }
protected void CreateUser_Click(object sender, EventArgs e) { var manager = new UserManager(); var user = new ApplicationUser() { UserName = UserName.Text }; IdentityResult result = manager.Create(user, Password.Text); if (result.Succeeded) { ApplicationUser newUser = manager.Find(UserName.Text, Password.Text); var sa = new StoredAccount(); sa.CreateNewAccount(newUser.Id,Email.Text); var returnUrl = Request.QueryString["ReturnUrl"]; IdentityHelper.SignIn(manager, user, isPersistent: false); if (returnUrl == null) { IdentityHelper.RedirectToReturnUrl("~/Game/User-Home.aspx", Response); } else { IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } } else { ErrorMessage.Text = result.Errors.FirstOrDefault(); } }
protected void LogIn(object sender, EventArgs e) { if (IsValid) { // Validate the user password var manager = new UserManager(); ApplicationUser user = manager.Find(UserName.Text, Password.Text); if (user != null) { Analytics.Client.Identify(user.Id, new Segment.Model.Traits { { "name", user.UserName }, { "email", user.Email } }); IdentityHelper.SignIn(manager, user, RememberMe.Checked); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { FailureText.Text = "Invalid username or password."; ErrorMessage.Visible = true; } } }
protected void LoginButton_Click(object sender, EventArgs e) { // create new userStore and userManager objects var userStore = new UserStore<IdentityUser>(); var userManager = new UserManager<IdentityUser>(userStore); // Find the user var user = userManager.Find(UserNameTextBox.Text, PasswordTextBox.Text); // check if username and password combo exists if (user != null) { // authenticate and login new user var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity); // redirect to the Main Menu page Response.Redirect("~/game.aspx"); } else { StatusLabel.Text = "Invalid Username or Password"; AlertFlash.Visible = true; } }
protected void LoginButton_Click(object sender, EventArgs e) { var userStore = new UserStore<IdentityUser>(); var manager = new UserManager<IdentityUser>(userStore); IdentityUser user = manager.Find(LoginUser.UserName, LoginUser.Password); if (user != null) { var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity); if (Request.QueryString["ReturnUrl"] == null) Response.Redirect("../Default.aspx"); else Response.Redirect(Request.QueryString["ReturnUrl"]); } else { LoginUser.FailureText = "Invalid User Name or Password"; } }
protected void btnLogin_Click(object sender, EventArgs e) { var userStore = new UserStore<IdentityUser>(); var userManager = new UserManager<IdentityUser>(userStore); //database connection not-authicating //System.Data.Entity.Core.EntityCommandExecutionException //System.Data.SqlClient.SqlException try { var user = userManager.Find(txtUsername.Text, txtPassword.Text); if (user != null) { var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity); Response.Redirect("/admin/main.aspx"); } else { lblStatus.Text = "Invalid username or password."; } } catch (System.Data.Entity.Core.EntityCommandExecutionException ECEE) { Server.Transfer("/ErrorPage.aspx", true); } catch (System.Data.SqlClient.SqlException SqlE) { Server.Transfer("/ErrorPage.aspx", true); } }
protected void Page_Load() { // Process the result from an auth provider in the request ProviderName = IdentityHelper.GetProviderNameFromRequest(Request); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect("~/Account/Login"); } if (!IsPostBack) { var manager = new UserManager(); var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/Account/Login"); } var user = manager.Find(loginInfo.Login); if (user != null) { //MyUser user1 = MyUser.getUser(user.UserName, ""); //if(Session["UserId"]!=null && Convert.ToInt32(Session["UserId"].ToString())!=user1.userId) // Session.Add("UserId", user1.userId); IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else if (User.Identity.IsAuthenticated) { // Apply Xsrf check when linking var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId()); if (verifiedloginInfo == null) { Response.Redirect("~/Account/Login"); } var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login); if (result.Succeeded) { MyUser user1 = MyUser.getUser(user.UserName, ""); if (Session["UserId"] != null && Convert.ToInt32(Session["UserId"].ToString()) != user1.userId) Session.Add("UserId", user1.userId); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { AddErrors(result); return; } } else { userName.Text = loginInfo.DefaultUserName; } } }
protected void btnIngresar_Click(object sender, EventArgs e) { var userStore = new UserStore<IdentityUser>(); var userManager = new UserManager<IdentityUser>(userStore); var user = userManager.Find(txtNombreUsuario.Text, txtContrasenna.Text); if (user != null) { var authenticationManager = HttpContext.Current.GetOwinContext().Authentication; var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity); Response.Redirect("~/wfrmInicio.aspx"); } }
protected void LogIn(object sender, EventArgs e) { if (IsValid) { // Validate the user password var userMgr = new UserManager(); var thisUsers = userMgr.Users; ApplicationUser user = userMgr.Find(UserName.Text, Password.Text); if (user != null) { if (!userMgr.IsInRole(user.Id, rdUserRole.Text)) { FailureText.Text = "Invalid username or password"; ErrorMessage.Visible = true; return; } IdentityHelper.SignIn(userMgr, user, RememberMe.Checked); //ApplicationDbContext dbcon = new ApplicationDbContext(); //Grievance gr = new Grievance(); //gr.GrievanceDescription ="hello"; //gr.DateLogged = DateTime.Now; //gr.TargetCompletionDate = DateTime.Now; //gr.ResolutionStatus = Grievance.ResolutionStatuses.Created; ////gr.DateLogged = DateTime.Now; //dbcon.Grievances.Add(gr); //dbcon.SaveChanges(); if (rdUserRole.Text == "Auditor") { Response.Redirect("~/AuditorPortal/Complaints.aspx"); } else if (rdUserRole.Text == "Administrator") { Response.Redirect("~/AdministratorPortal/Complaints.aspx"); } else if (rdUserRole.Text == "Employee") { Response.Redirect("~/EmployeePortal/Tasks.aspx"); } IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { FailureText.Text = "Invalid username or password."; ErrorMessage.Visible = true; } } }
protected void Page_Load() { // 要求の認証プロバイダーからの結果を処理します ProviderName = IdentityHelper.GetProviderNameFromRequest(Request); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect("~/Account/Login"); } if (!IsPostBack) { var manager = new UserManager(); var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/Account/Login"); } var user = manager.Find(loginInfo.Login); if (user != null) { IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else if (User.Identity.IsAuthenticated) { // Apply Xsrf check when linking var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId()); if (verifiedloginInfo == null) { Response.Redirect("~/Account/Login"); } var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login); if (result.Succeeded) { IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { AddErrors(result); return; } } else { userName.Text = loginInfo.DefaultUserName; } } }
protected void Page_Load() { // Procesar el resultado de un proveedor de autenticación en la solicitud ProviderName = IdentityHelper.GetProviderNameFromRequest(Request); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect("~/Account/Login"); } if (!IsPostBack) { var manager = new UserManager(); var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(); if (loginInfo == null) { Response.Redirect("~/Account/Login"); } var user = manager.Find(loginInfo.Login); if (user != null) { IdentityHelper.SignIn(manager, user, isPersistent: false); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else if (User.Identity.IsAuthenticated) { // Aplicar comprobación de Xsrf durante la vinculación var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId()); if (verifiedloginInfo == null) { Response.Redirect("~/Account/Login"); } var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login); if (result.Succeeded) { IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { AddErrors(result); return; } } else { userName.Text = loginInfo.DefaultUserName; } } }
public override void Validate(string userName, string password) { using (var context = new ApplicationDbContext()) { using (var userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(context))) { var user = userManager.Find(userName, password); if (user == null) { var msg = String.Format("Unknown Username {0} or incorrect password {1}", userName, password); Trace.TraceWarning(msg); throw new FaultException(msg); } } } }
public ActionResult Login(Login login) { UserStore<IdentityUser> userStore = new UserStore<IdentityUser>(); UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore); IdentityUser identityUser = manager.Find(login.UserName, login.Password); if (ModelState.IsValid) { if (ValidLogin(login)) { IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication; authenticationManager .SignOut(DefaultAuthenticationTypes.ExternalCookie); var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, login.UserName), }, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role); authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = false }, identity); System.Threading.Thread.Sleep(2000); SecurityEntities context = new SecurityEntities(); var query = context.AspNetUsers.Where(u => u.Id == identityUser.Id).FirstOrDefault(); if (query.AspNetRoles.Single().Name == "admin") { return RedirectToAction("AdminDashboard", "Accounts"); } else if (query.AspNetRoles.Single().Name == "consumer") { return RedirectToAction("ConsumerDashboard", "Accounts"); } } } return View(); }
protected void LogIn(object sender, EventArgs e) { if (IsValid) { // Проверка пароля пользователя var manager = new UserManager(); ApplicationUser user = manager.Find(UserName.Text, Password.Text); if (user != null) { IdentityHelper.SignIn(manager, user, RememberMe.Checked); IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response); } else { FailureText.Text = "Invalid username or password."; ErrorMessage.Visible = true; } } }