コード例 #1
0
        public async Task LoginUserAsync(LoginDto dto)
        {
            HttpContext context = _httpContextAccessor.HttpContext;

            if (context.User.Identity.IsAuthenticated)
            {
                throw HttpError.Forbidden("User is still authenticated");
            }

            if (dto.Name == null || dto.Password == null)
            {
                throw HttpError.InternalServerError("Username or password is null");
            }

            User user = (await _userRepository.Find(x => x.Name == dto.Name)).FirstOrDefault();

            if (user == null)
            {
                throw HttpError.Unauthorized("Wrong username or password");
            }

            string savedPasswordHash = (await _hashRepository.Get(user.Id))?.PasswordHash;

            if (savedPasswordHash == null)
            {
                throw HttpError.InternalServerError("User has no password");
            }

            if (!HashHelpers.CheckPasswordWithHash(dto.Password, savedPasswordHash))
            {
                throw HttpError.Unauthorized("Wrong username or password");
            }

            string[]     roles  = user.CredentialLevel.GetAllPossibleRoles();
            List <Claim> claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, user.Name),
                new Claim(ClaimTypes.NameIdentifier, user.Name)
            };

            claims.AddRange(roles.Select(x => new Claim(ClaimTypes.Role, x)));

            var identity       = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var principal      = new ClaimsPrincipal(identity);
            var authProperties = new AuthenticationProperties
            {
                AllowRefresh = true,
                ExpiresUtc   = DateTimeOffset.Now.AddDays(1),
                IsPersistent = dto.RememberMe
            };

            await context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, authProperties);
        }