コード例 #1
0
ファイル: UserService.cs プロジェクト: Boorys/TIU
        public AuthenticateDto Authenticate(string username, string password)
        {
            var users = userRepository.getAllUsers().Result;
            var user  = users.SingleOrDefault(x => x.UserName == username && x.Password == password);

            if (user == null)
            {
                return(null);
            }
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.UserId.ToString()),
                    new Claim(ClaimTypes.Role, user.Role)
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            AuthenticateDto userDto = new AuthenticateDto();

            userDto.Token = tokenHandler.WriteToken(token);
            userDto.Role  = user.Role;

            return(userDto);
        }
コード例 #2
0
ファイル: AccountController.cs プロジェクト: pacmad/Theatre-2
        //POST : /api/Account/Authenticate
        public async Task <IActionResult> Authenticate(AuthenticateDto dto)
        {
            var user = await _userManager.FindByNameAsync(dto.UserName);

            if (user != null && await _userManager.CheckPasswordAsync(user, dto.Password))
            {
                var roles = await _userManager.GetRolesAsync(user);

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim("UserId", user.Id.ToString()),
                        new Claim("UserName", user.UserName),
                        new Claim("Email", user.Email),
                        new Claim("role", roles.First()),
                    }),
                    Expires            = DateTime.Now.AddHours(Convert.ToInt32(_configuration["ApplicationSettings:JWT_ExpireHours"])),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["ApplicationSettings:JWT_Secret"])), SecurityAlgorithms.HmacSha256Signature)
                };
                var tokenHandler  = new JwtSecurityTokenHandler();
                var securityToken = tokenHandler.CreateToken(tokenDescriptor);
                var token         = tokenHandler.WriteToken(securityToken);

                return(Ok(new { token }));
            }
            else
            {
                return(BadRequest(new { message = "Wrong username or password." }));
            }
        }
コード例 #3
0
        [Microsoft.AspNetCore.Mvc.HttpPost("Authenticate")]//("authenticate")]
        public IActionResult Authenticate(AuthenticateDto authModel)
        {
            var user = _userService.Authenticate(authModel.Email, authModel.Password);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            IdentityModelEventSource.ShowPII = true;
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            // return basic user info and authentication token
            return(Ok(new
            {
                Id = user.Id,
                Username = user.Email,
                FirstName = user.Name,
                Token = tokenString
            }));
        }
コード例 #4
0
        public async Task <IActionResult> Authenticate([FromBody] AuthenticateDto model)
        {
            try
            {
                var payload = await GoogleJsonWebSignature.ValidateAsync(model.GoogleToken).ConfigureAwait(false);

                if (payload == null)
                {
                    return(Unauthorized());
                }

                var user = await _userService.Authenticate(payload.Email).ConfigureAwait(false);

                if (user == null)
                {
                    return(BadRequest(new { message = "User unidentified" }));
                }

                UserOutputDto userDto = _mapper.Map <UserOutputDto>(user);

                return(Ok(userDto));
            }
            catch (InvalidJwtException ex)
            {
                return(Unauthorized(new { message = ex.Message }));
            }
        }
コード例 #5
0
        public async Task <AuthenticateResponseDto> Authenticate(AuthenticateDto model)
        {
            var user = await _context.Users.SingleOrDefaultAsync(x => x.Email == model.Email);

            if (user is null)
            {
                throw new LaprTrackrException(LaprTrackrStatusCodes.NotFound, "Email or password not match.");
            }

            if (!BCrypt.Net.BCrypt.EnhancedVerify(model.Password, user.Password))
            {
                throw new LaprTrackrException(LaprTrackrStatusCodes.NotFound, "Email or password not match.");
            }

            var(token, refreshToken) = GenerateJSONWebToken(user);
            var authenticateResponseDto = new AuthenticateResponseDto
            {
                Token        = token,
                RefreshToken = refreshToken,
                User         = user
            };

            await SaveRefreshToken(user, token, refreshToken);

            return(authenticateResponseDto);
        }
コード例 #6
0
        public async Task <IActionResult> Authenticate([FromBody] AuthenticateDto authenticateDto)
        {
            var user = await _userService.AuthenticateAsync(authenticateDto.Username, authenticateDto.Password);

            if (user is null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(type: ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return(Ok(new
            {
                user.Id,
                user.Username,
                user.FirstName,
                user.LastName,
                Token = tokenString
            }));
        }
コード例 #7
0
        public IActionResult Authenticate([FromBody] AuthenticateDto model)
        {
            var user = _userService.Authenticate(model.Username, model.Password);

            // return null if user not found
            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            // authentication successful so generate jwt token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token   = tokenHandler.CreateToken(tokenDescriptor);
            var userDto = _mapper.Map <UserDto>(user);

            userDto.Token = tokenHandler.WriteToken(token);

            return(Ok(userDto));
        }
コード例 #8
0
        public (string token, User user) Authenticate(AuthenticateDto dto)
        {
            if (!dto.IsValid())
            {
                NotifyValidationError(dto);
                return(string.Empty, null);
            }

            var user = _userRepository.GetByEmail(dto.Email);

            if (user == null)
            {
                NotifyError(DomainError.UserNotFound);
                return(string.Empty, null);
            }

            if (user.Password != dto.Password.Encrypt())
            {
                NotifyError(DomainError.InvalidPassoword);
                return(string.Empty, null);
            }

            var token = _tokenEncoder.Encoder(user);

            return(token, user);
        }
コード例 #9
0
        public IActionResult Authenticate([FromBody] AuthenticateDto authenticateDto)
        {
            var user = _authenticationService.Authenticate(authenticateDto.Name, authenticateDto.GoogleId);

            if (user == null)
            {
                return(BadRequest("Login failed"));
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            // return basic user info (without password) and token to store client side
            return(Ok(new AuthenticateResponse
            {
                GoogleId = user.GoogleId,
                Name = user.Name,
                GivenName = user.GivenName,
                Email = user.Email,
                Picture = user.Picture,
                Token = tokenString
            }));
        }
コード例 #10
0
        public async Task <IActionResult> AuthenticateAsync([FromBody] AuthenticateDto model)
        {
            try
            {
                // Verify that the pin is correct for the provided employeeCardId.
                var authenticated = await this.EmployeeRepository.VerifyPinAsync(model.EmployeeCardId, model.Pin);

                if (!authenticated)
                {
                    return(this.Unauthorized());
                }

                // Fetch the employee from the database.
                var employee = await this.EmployeeRepository.FindEmployeeByEmployeeCardIdAsync(model.EmployeeCardId);

                // Create a JWT for this employee.
                var token = this.JwtRepository.Create(employee);

                // Return the JWT.
                return(this.Ok(token));
            }
            catch (Exception ex)
            {
                this.Logger.LogError(ex, "Error when AuthenticateAsync for employeeCardId {0}", model.EmployeeCardId);
                return(this.StatusCode(500));
            }
        }
コード例 #11
0
        public async Task TestAuthenticate()
        {
            try
            {
                AuthenticateDto dto = new AuthenticateDto()
                {
                    Email    = "*****@*****.**",
                    Password = "******"
                };

                OkObjectResult result = await _usersController.AuthenticateAsync(dto) as OkObjectResult;

                BsonDocument elements = result.Value.ToBsonDocument();
                Assert.AreEqual("60848ae8fb71edf2a7ebf846", elements.GetValue("_id").ToString());
                Assert.AreEqual(dto.Email, elements.GetValue("Email").ToString());
                Assert.NotNull(elements.GetValue("Token"));

                dto.Email = "nonExistentEmail";
                var response = await _usersController.AuthenticateAsync(dto);

                Assert.IsInstanceOf <BadRequestObjectResult>(response, "Email or password is incorrect");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #12
0
        public IActionResult Authenticate([FromBody] AuthenticateDto model)
        {
            var bruger = _userService.Authenticate(model.Emailadresse, model.Password);

            if (bruger == null)
            {
                return(BadRequest(new { message = "Email eller password er forkert" }));
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, bruger.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            // return basic user info and authentication token
            return(Ok(new
            {
                bruger.Id,
                bruger.Emailadresse,
                bruger.Navn,
                Token = tokenString
            }));
        }
コード例 #13
0
        public IActionResult Authenticate([FromBody] AuthenticateDto authenticateDto)
        {
            var currentUser = _userService.Authenticate(authenticateDto.Email, authenticateDto.Password);

            if (currentUser is null)
            {
                return(BadRequest(new { message = "Email or password is incorrect" }));
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.NameIdentifier, currentUser.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var securityToken   = tokenHandler.CreateToken(tokenDescriptor);
            var serializedToken = tokenHandler.WriteToken(securityToken);

            var authenticatedUserDto = _mapper.Map <AuthenticatedUserDto>(currentUser);

            authenticatedUserDto.Token = serializedToken;

            // return basic user info and authentication token
            return(Ok(authenticatedUserDto));
        }
コード例 #14
0
        public void UserDto_is_not_valid(AuthenticateDto dto, string message)
        {
            var result = dto.IsValid();

            result.Should().BeFalse();
            dto.ValidationResult.Errors.Should().NotBeNullOrEmpty();
            dto.ValidationResult.Errors.First().ErrorMessage.Should().Be(message);
        }
コード例 #15
0
        public IActionResult Login([FromBody] AuthenticateDto model)
        {
            var user = App.Instance().UserService.Authenticate(model.Username, model.Password, Encoding.ASCII.GetBytes(_appSettings.Secret));

            if (user == null)
            {
                return(Forbid());
            }
            return(Ok(user));
        }
コード例 #16
0
        /// <summary>
        /// provide authorization token
        /// </summary>

        public string GetToken(AuthenticateDto authenticateDto)
        {
            if (string.IsNullOrEmpty(authenticateDto.UserName) && authenticateDto.Password == "123")
            {
                var token = GenerateToken(authenticateDto);
                return(token);
            }

            return(string.Empty);
        }
コード例 #17
0
ファイル: UsersController.cs プロジェクト: oliko20/HR
        public async Task <bool> Authenticate([FromBody] AuthenticateDto itemDto)
        {
            var user = await _userDao.GetByEmailAsync(itemDto.Email);

            if (user is null)
            {
                return(false);
            }
            return(user.Password == Cripto.Encript(itemDto.Password));
        }
コード例 #18
0
        public async Task <IActionResult> Authenticate([FromBody] AuthenticateDto authenticate)
        {
            var user = await _authService.Authenticate(authenticate.UserName, authenticate.Password);

            if (user == null)
            {
                return(BadRequest(new { message = "UserName or Passoword is incorrect!" }));
            }

            return(Ok(user));
        }
コード例 #19
0
        /// <summary>
        /// 使用者驗證
        /// </summary>
        /// <param name="dto"></param>
        public string Authenticate(AuthenticateDto dto)
        {
            var user = _users.SingleOrDefault(x => x.Account == dto.Account && x.Password == dto.Password);

            if (user == null)
            {
                throw new AuthenticationException("帳號或密碼輸入錯誤!!");
            }

            return(_authenticationService.GenerateJwtToke(user));
        }
コード例 #20
0
        public async Task <IActionResult> Authenticate([FromForm] AuthenticateDto userParam)
        {
            var result = await _userService.AuthenticateAsync(userParam.UserName, userParam.Password);

            if (result.Item1 == null)
            {
                return(BadRequest(new { message = result.Item2 }));
            }

            return(Ok(result.Item1));
        }
コード例 #21
0
        public IActionResult Authenticate(AuthenticateDto data)
        {
            var response = _userService.Authenticate(data.Email, data.Password);

            if (response == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            return(Ok(response));
        }
コード例 #22
0
        public async Task <ActionResult <CurrentUserDto> > Authenticate([FromBody] AuthenticateDto userDto)
        {
            var user = await _userService.Authenticate(userDto.Username, userDto.Password);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            return(Ok(user));
        }
コード例 #23
0
        public ServiceResult <UserDto> Authenticate(AuthenticateDto auth)
        {
            var authenticatedUser = _context.Users.FirstOrDefault(u => u.UserName == auth.UserName && u.Password == auth.Password);

            if (authenticatedUser == null)
            {
                return(GetFailedResult <UserDto>(auth, new ErrorMessage {
                    Text = "User Authentication Failed"
                }));
            }

            return(GetSuccessResult(auth, _mapper.Map <UserDto> (authenticatedUser)));
        }
コード例 #24
0
ファイル: UserController.cs プロジェクト: naza1/NetCore3Mysql
        public async Task <IActionResult> Authenticate([FromBody] AuthenticateDto model)
        {
            var result = await _userService.Authenticate(model.Username, model.Password);

            if (!result.Success)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            var jsonJwt = GenerateToken(result.Entity.Id);

            // return basic user info and authentication token
            return(Ok(jsonJwt));
        }
コード例 #25
0
        public async Task <ActionResult <UserAuthenticatedDto> > Authenticate([FromBody] AuthenticateDto model)
        {
            //var claimsIdentity = this.User.Identity as ClaimsIdentity;
            //var userId = claimsIdentity.FindFirst(ClaimTypes.Name)?.Value;
            var authenticateUserModel = _mapper.Map <AuthenticateUserModel>(model);
            var user = await _userLogic.Authenticate(authenticateUserModel);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            return(Ok(user));
        }
コード例 #26
0
        public void UserDto_is_valid()
        {
            var dto = new AuthenticateDto
            {
                Email    = "*****@*****.**",
                Password = "******",
            };

            var result = dto.IsValid();

            result.Should().BeTrue();

            dto.ValidationResult.Errors.Should().BeNullOrEmpty();
        }
コード例 #27
0
        public async Task AuthenticateAsync_should_return_401_when_authentication_fails()
        {
            // Arrange
            var controller = new EmployeesController(this.Fixture.EmployeeRepository, this.Fixture.JwtRepository, this.Logger);
            var model      = new AuthenticateDto {
                EmployeeCardId = this.Fixture.InvalidId, Pin = "1234"
            };

            // Act
            var response = await controller.AuthenticateAsync(model);

            // Assert
            var result = Assert.IsType <UnauthorizedResult>(response);
        }
コード例 #28
0
        public async Task <IActionResult> Authenticate([FromBody] AuthenticateDto model)
        {
            var user = await _userService.Authenticate(model.Username, model.Password);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            var userAuthenticated = _jwtTokenService.GenerateToken(user);


            return(Ok(userAuthenticated));
        }
コード例 #29
0
        public async Task <ActionResult> Login(string id, LoginModel model)
        {
            if (ModelState.IsValid)
            {
                IDictionary <string, object> env = Request.GetOwinContext().Environment;

                AuthenticateDto authenticateResult = await _mediator.Send(new AuthenticateCommand
                {
                    Domain   = model.Domain,
                    UserName = model.UserName,
                    Password = model.Password
                });

                if (authenticateResult.AccountStatus == Wdc.DirectoryLib.Types.AccountStatus.Success)
                {
                    List <Claim> claims = new List <Claim>();
                    if (authenticateResult.User.JpegPhoto != null)
                    {
                        claims.Add(new Claim(Common.Constants.DtClaimTypes.UserImage, Convert.ToBase64String(authenticateResult.User.JpegPhoto)));
                    }

                    claims.Add(new Claim(IdentityServer3Constants.ClaimTypes.GivenName, $"{authenticateResult.User.DisplayName }"));
                    claims.Add(new Claim(IdentityServer3Constants.ClaimTypes.Email, $"{ authenticateResult.User.UserPrincipalName}"));
                    claims.Add(new Claim(DtClaimTypes.Department, $"{ authenticateResult.User.Department}"));

                    env.IssueLoginCookie(new IdentityServer3.Core.Models.AuthenticatedLogin
                    {
                        AuthenticationMethod = CookieAuthenticationDefaults.AuthenticationType,
                        Subject         = authenticateResult.User.DisplayName,
                        Name            = authenticateResult.User.SamAccountName,
                        Claims          = claims,
                        PersistentLogin = true
                    });

                    ClaimsPrincipal user = (ClaimsPrincipal)User;
                    IdentityServer3.Core.Models.SignInMessage msg = env.GetSignInMessage(id);
                    string returnUrl = msg.ReturnUrl;
                    env.RemovePartialLoginCookie();

                    return(Redirect(returnUrl));
                }
                else
                {
                    ModelState.AddModelError("", authenticateResult.Message);
                }
            }
            model.AvailableDomains = GetDomains();
            return(View(model));
        }
コード例 #30
0
        public async Task <AuthenticateDto> Authenticate()
        {
            LambdaLogger.Log($"Entering: Authenticate()");

            AuthenticateDto response = null;

            try
            {
                string url = $"{TCGConstants.BASE_URL}/token";

                StringContent content = new StringContent(TCGConstants.AUTH_STRING);

                using (var httpClient = new HttpClient())
                {
                    HttpResponseMessage httpResponse = await httpClient.PostAsync(url, content);

                    LambdaLogger.Log($"Http Response: {JsonConvert.SerializeObject(httpResponse)}");

                    if (httpResponse != null)
                    {
                        if (httpResponse.IsSuccessStatusCode)
                        {
                            response = JsonConvert.DeserializeObject <AuthenticateDto>(await httpResponse.Content.ReadAsStringAsync());

                            LambdaLogger.Log($"Authentication Response: {JsonConvert.SerializeObject(response)}");

                            if (response != null)
                            {
                                await S3Helper.CreateFile(new S3CreateFileRequest
                                {
                                    FilePath = MTGServiceConstants.AuthenticateJsonFilepath,
                                    Content  = JsonConvert.SerializeObject(response)
                                });
                            }
                        }
                    }
                };
            }
            catch (Exception exp)
            {
                LambdaLogger.Log($"Exception: {exp}");
                throw;
            }

            LambdaLogger.Log($"Leaving: {JsonConvert.SerializeObject(response)}");

            return(response);
        }