Пример #1
0
        public async Task <ActionResult <AuthenticatedVM> > Login([FromBody] LoginVM loginVM)
        {
            // Validation
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            AuthenticatedVM authenticatedVM = await this.bll.Login(loginVM);

            return(Ok(authenticatedVM));
        }
Пример #2
0
        public async Task <AuthenticatedVM> Login(LoginVM loginVM)
        {
            // Validation
            if (loginVM == null)
            {
                return(null);
            }

            // Result
            AuthenticatedVM authenticatedVM = new AuthenticatedVM()
            {
                RememberMe = loginVM.RememberMe
            };

            // Retrieve user by email or username
            User user = await userManager.FindByEmailAsync(loginVM.EmailOrUsername) ?? await userManager.FindByNameAsync(loginVM.EmailOrUsername);

            if (user == null)
            {
                logger.LogWarning("User not found during login", loginVM.EmailOrUsername);

                throw new LoginFailedException("invalid");
            }

            // Log the user in by password
            SignInResult signInResult = await signInManager.PasswordSignInAsync(user, loginVM.Password, loginVM.RememberMe, lockoutOnFailure : true);

            // Success
            if (signInResult.Succeeded)
            {
                // Authenticated by password
                logger.LogInformation("User logged in", user);

                // Retrieve roles of user
                user.Roles = (List <string>) await userManager.GetRolesAsync(user);

                // Set claims of user
                List <Claim> claims = new List <Claim>()
                {
                    new Claim(JwtRegisteredClaimNames.NameId, user.Id.ToString().ToUpper()),
                    new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
                    new Claim(JwtRegisteredClaimNames.Email, user.Email),
                    new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString(CultureInfo.CurrentCulture))
                };

                // TODO: Custom fields
                if (!string.IsNullOrEmpty(user.FirstName))
                {
                    claims.Add(new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName));
                }
                if (!string.IsNullOrEmpty(user.LastName))
                {
                    claims.Add(new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName));
                }

                // Add roles as claims
                foreach (var role in user.Roles)
                {
                    claims.Add(new Claim(ClaimTypes.Role, role));
                }

                // Authentication successful => Generate JWT token based on the user's claims
                string token = this.GenerateJWT(claims);

                // Return user with token
                authenticatedVM.User  = mapper.Map <User, UserVM>(user);
                authenticatedVM.Token = token;

                return(authenticatedVM);
            }

            // Failed
            //if (signInResult.RequiresTwoFactor)
            //{
            //    logger.LogInformation("User requires two factor auth", user);
            //
            //    return RedirectToAction(nameof(LoginWith2fa), new { returnUrl, loginVM.RememberMe });
            //}
            if (signInResult.IsLockedOut)
            {
                logger.LogWarning("User is locked out", user);

                throw new LoginFailedException("locked-out");
            }
            else if (signInResult.IsNotAllowed)
            {
                logger.LogWarning("User is not allowed to login", user);

                throw new LoginFailedException("not-allowed");
            }

            logger.LogWarning("User login is invalid", user);

            throw new LoginFailedException("invalid");
        }