zeqk
7/10/2018 - 12:50 PM

Form Post ASP.NET Core

[AllowAnonymous]
        [HttpPost("[action]")]
        [ProducesResponseType(401)]
        public async Task<IActionResult> FormLogin([FromForm(Name = "username"), Required]string username, 
            [FromForm(Name = "password"), Required]string password,
            [FromForm(Name = "redirectToUrl"), Required]string redirectToUrl)
        {
            if (!ModelState.IsValid)
                throw new BadRequestException(ModelState);

            var user = await _userManager.FindByNameAsync(username);

            if (user == null)
            {
                ModelState.AddModelError(nameof(username), "El usuario no existe");
                throw new BadRequestException(ModelState);
            }

            var result = await _signInManager.PasswordSignInAsync(user, password, false, false);

            if (result.Succeeded)
            {
                var (accessToken, newRefreshToken) = _tokenStore.CreateTokens(user);

                var url = redirectToUrl.Replace("{accessToken}", accessToken).Replace("{refreshToken}", newRefreshToken);

                return Redirect(url);

            }
            return BadRequest();
            
        }