public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (AppUserManager userManager = _userManagerFactory())
            {
                ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

                ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
                                                                                     context.Options.AuthenticationType);

                ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
                                                                                       CookieAuthenticationDefaults.AuthenticationType);

                // ADDED FROM INTERNET!!!!/

                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Sid, user.Id.ToString()));
                cookiesIdentity.AddClaim(new Claim(ClaimTypes.Sid, user.Id.ToString()));



                AuthenticationProperties properties = CreateProperties(user.UserName);
                AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
        }
        public async Task <ActionResult> Login(LogInModel model)
        {
            if (!ModelState.IsValid) //Checks if input fields have the correct format
            {
                return(View());      //Returns the view with the input values.
            }

            User user = await userManager.FindAsync(model.UserName, model.Password);

            if (user != null && user.LockoutEnabled == false)
            {
                ClaimsIdentity identity = await userManager.CreateIdentityAsync(
                    user, DefaultAuthenticationTypes.ApplicationCookie);

                identity.AddClaim(new Claim(ClaimTypes.Sid, user.Id.ToString()));

                var authManager = Request.GetOwinContext().Authentication;
                authManager.SignIn(identity);

                return(Redirect(GetRedirectUrl(model.ReturnUrl)));
            }

            ModelState.AddModelError("", "Invalid email or password");
            return(View());
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                User user = new User
                {
                    UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName
                };
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    ClaimsIdentity claim = await UserManager.CreateIdentityAsync(user,
                                                                                 DefaultAuthenticationTypes.ApplicationCookie);

                    claim.AddClaim(new Claim("FirstName", user.FirstName));
                    AuthenticationManager.SignOut();
                    AuthenticationManager.SignIn(new AuthenticationProperties
                    {
                        IsPersistent = true
                    }, claim);
                    return(RedirectToAction("Main", "Main"));
                }
                else
                {
                    foreach (string error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }
            }

            return(View(model));
        }
        public async Task <ActionResult> Login(LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await UserManager.FindAsync(model.Email, model.Password);

                if (user == null)
                {
                    ModelState.AddModelError("", "无效的用户名和密码");
                }
                else
                {
                    var claimsIdentity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

                    //claimsIdentity.AddClaims(LocationClaimsProvider.GetClaims(claimsIdentity));
                    //claimsIdentity.AddClaims(ClaimsRoles.CreateRolesFromClaims(claimsIdentity));
                    AuthManager.SignOut();
                    AuthManager.SignIn(new AuthenticationProperties {
                        IsPersistent = false
                    }, claimsIdentity);
                    return(RedirectToAction("Index", "Home"));
                }
            }
            return(View(model));
        }
Esempio n. 5
0
        public async Task <ClaimsIdentity> GenerateUserIdentityAsync(AppUserManager userManager)
        {
            var userIdentity = await userManager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            // Add custom user claims here
            return(userIdentity);
        }
Esempio n. 6
0
        public async Task <ActionResult> Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                User user = new User {
                    UserName = model.Email, Email = model.Email, RegisterDate = DateTime.Now, LastOnline = DateTime.Now, Name = model.Name
                };
                IdentityResult result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    ClaimsIdentity claim = await UserManager.CreateIdentityAsync(user,
                                                                                 DefaultAuthenticationTypes.ApplicationCookie);

                    UserManager.AddToRole(user.Id, "user");
                    AuthenticationManager.SignOut();
                    AuthenticationManager.SignIn(new AuthenticationProperties
                    {
                        IsPersistent = true
                    }, claim);

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    foreach (string error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }
            }
            return(View(model));
        }
Esempio n. 7
0
        public async Task <ActionResult> Login(Login login)
        {
            var secret    = "6LfBQOIUAAAAAODnw5bhLcW7QO3nvL9EuZ5S27qC";
            var g_captcha = this.Request.Form["g-recaptcha-response"];

            var response          = new WebClient().DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, g_captcha));
            var recaptchaResponse = JsonConvert.DeserializeObject <RecaptchaResponse>(response);

            if (recaptchaResponse.Success)
            {
                var user = await _userManager.FindAsync(login.UserName, login.Password);

                if (user != null)
                {
                    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                    var identity = await _userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

                    AuthenticationManager.SignIn(new AuthenticationProperties()
                    {
                        IsPersistent = true
                    }, identity);

                    return(RedirectToAction("Create", new { cliente = login.UserName }));
                }
            }

            ViewBag.Error = "Usuario o contraseña incorrectos.";
            return(View(login));
        }
Esempio n. 8
0
        public async Task <ActionResult> Login(AdminLoginModel model, string ReturnUrl)
        {
            if (ModelState.IsValid)
            {
                AppUser user = await userManager.FindAsync(model.ID, model.Password);

                if (user == null)
                {
                    //ModelState.AddModelError("Password", "아이디 또는 비밀번호가 잘못되었습니다.");
                    TempData["message"] = "아이디 또는 비밀번호가 잘못되었습니다.";
                }
                else
                {
                    authManager = System.Web.HttpContext.Current.GetOwinContext().Authentication;
                    ClaimsIdentity ident = await userManager.CreateIdentityAsync(user,
                                                                                 DefaultAuthenticationTypes.ApplicationCookie);

                    authManager.SignOut();
                    authManager.SignIn(new AuthenticationProperties {
                        IsPersistent = true
                    }, ident);
                    ViewBag.AdminId = model.ID;
                    return(RedirectToAction("Index"));
                }
            }
            ViewBag.returnUrl = ReturnUrl;
            return(View(model));
        }
Esempio n. 9
0
        public async Task <ActionResult> Login(UserLoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                AppUser user = await _userManager.FindAsync(model.Email, model.Password);

                if (user == null)
                {
                    ModelState.AddModelError("", "Invalid name or password");
                }
                else
                {
                    if (!await _userManager.IsEmailConfirmedAsync(user.Id))
                    {
                        string code = await _userManager.GenerateEmailConfirmationTokenAsync(user.Id);

                        string callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        _mailingRepository.ActivationMail(user.Email, callbackUrl);
                        Response.StatusCode = (int)HttpStatusCode.Forbidden;
                        return(PartialView("_Error", new string[] { "You must have a confirmed email to log on. Check your email for activation link." }));
                    }

                    ClaimsIdentity ident = await _userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

                    _authManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                    _authManager.SignIn(new AuthenticationProperties
                    {
                        IsPersistent = false,
                    }, ident);
                    return(Json(new { url = "/" }));
                }
            }
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return(PartialView(model));
        }
Esempio n. 10
0
        private void CreateIdentity(string sessionJson)
        {
            var session = _apiProvider.DeserializeJson <Session>(sessionJson);
            var appUser = new AppUser(session.UserId.ToString(), "User");
            var task    = _appUserManager.CreateIdentityAsync(appUser, DefaultAuthenticationTypes.ApplicationCookie);

            task.Wait();
            var claim = task.Result;

            var authMgr        = HttpContext.GetOwinContext().Authentication;
            var authProperties = new AuthenticationProperties()
            {
                IsPersistent = false
            };

            authProperties.Dictionary["Session"] = sessionJson;

            foreach (var role in session.Roles)
            {
                var appRole = _appRoleManager.FindById(role.RoleID.ToString());
                if (appRole != null)
                {
                    _appUserManager.AddToRoleAsync(appUser.Id.ToString(), appRole.Name);
                }
            }

            authMgr.SignIn(authProperties, claim);
        }
Esempio n. 11
0
        public async Task <ClaimsIdentity> GenerateUserIdentityAsync(AppUserManager manager, string authenticationType)
        {
            var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);

            // Add custom user claims here
            return(userIdentity);
        }
Esempio n. 12
0
        public async Task <ClaimsIdentity> GenerateUserIdentityAsync(AppUserManager manager, string authenticationType)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);

            // Add custom user claims here
            return(userIdentity);
        }
Esempio n. 13
0
        public async Task <ClaimsIdentity> Authenticate(UserDTO userDto)
        {
            AppUser user = await _userMng.FindAsync(userDto.Email, userDto.Password);

            ClaimsIdentity claim = user != null ? await _userMng.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie) : null;

            _userMng.Dispose();
            return(claim);
        }
        /// <summary>
        /// Sign out as current identity and sign in as newly-created identity
        /// </summary>
        private async Task SignInAsync(Backer user, bool isPersistent)
        {
            Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
            var identity = await AppUserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

            Authentication.SignIn(new AuthenticationProperties()
            {
                IsPersistent = isPersistent
            }, identity);
        }
Esempio n. 15
0
        public async Task <ClaimsIdentity> Login(LoginViewModel model)
        {
            var user = await userManager.FindAsync(model.Username, model.Password);

            if (user == null)
            {
                throw new ApplicationException("Invalid name or password.");
            }

            return(await userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie));
        }
Esempio n. 16
0
        public async Task <ClaimsIdentity> GenerateUserIdentityAsync(AppUserManager manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            // Store the company id in a claim.
            // manager.AddClaim(Id, new Claim("CompanyId", CompanyId.ToString()));

            // Add custom user claims here
            return(userIdentity);
        }
Esempio n. 17
0
        private async Task SignInAsync(User user, bool isPersistent)
        {
            var claimsIdentity =
                await _userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

            AuthenticationManager.SignOut();
            AuthenticationManager.SignIn(new AuthenticationProperties {
                IsPersistent = isPersistent
            },
                                         claimsIdentity);
        }
Esempio n. 18
0
        public async Task <ClaimsIdentity> Authenticate(UserDTO userDto)
        {
            AppUserManager appUserManager = (AppUserManager)Database.UserManager;

            ClaimsIdentity claim = null;
            // find user
            ApplicationUser user = await appUserManager.FindAsync(userDto.Email, userDto.Password);

            // authorize user и return object ClaimsIdentity
            if (user != null)
            {
                claim = await appUserManager.CreateIdentityAsync(user,
                                                                 DefaultAuthenticationTypes.ApplicationCookie);
            }
            return(claim);
        }
Esempio n. 19
0
        public async Task <ClaimsIdentity> GenerateUserIdentityAsync(AppUserManager appUserManager, bool isPersistentState, bool screenLockedState)
        {
            var identity = await appUserManager.CreateIdentityAsync(
                this,
                DefaultAuthenticationTypes.ApplicationCookie
                );

            var claims = AppPrincipal.GetAdminClaims(
                appUserEntity: this,
                isPersistent: isPersistentState,
                screenLocked: screenLockedState
                );

            foreach (var claim in claims)
            {
                if (!identity.HasClaim(claim.Type, claim.Value))
                {
                    identity.AddClaim(claim);
                }
            }

            return(identity);
        }
Esempio n. 20
0
        public async Task <ClaimsIdentity> GenerateUserIdentityAsync(AppUserManager <ApplicationUser> manager)
        {
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            return(userIdentity);
        }
Esempio n. 21
0
 public async Task <ClaimsIdentity> CreateIdentityAsync(ApplicationUser user, string authenticationType)
 {
     return(await _userManager.CreateIdentityAsync(user, authenticationType));
 }