コード例 #1
0
        public async Task <IActionResult> Login([FromBody] UserLoginDTO userDTO)
        {
            var user = await _jwtAuthService.Login(userDTO.Username, userDTO.Password);

            if (user == null)
            {
                return(BadRequest("Invalid username or password!"));
            }

            var token = _jwtAuthService.CreateToken(user);

            return(Ok(new { token, user = new UserDTO {
                                Id = user.Id, Name = user.FullName
                            } }));
        }
コード例 #2
0
        public async Task <IActionResult> AuthenticateAsync([FromBody] AuthenticatePostBindingModel model, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            AppUser appUser = await _myUserManager.FindByEmailAsync(model.Email);

            if (appUser != null)
            {
                var result = await _signInManager.CheckPasswordSignInAsync(appUser, model.Password, false);

                if (result.Succeeded)
                {
                    string tokenString = _jwtAuthService.CreateToken(appUser.Id.ToString(), 24);
                    appUser.Token        = tokenString;
                    appUser.PasswordHash = null;
                    return(Ok(appUser));
                }
                else
                {
                    throw new Exception("Wrong password or username please try again."); // wrong password
                }
            }
            throw new Exception($"{model.Email} has not been registered, please register first.");
        }