Ejemplo n.º 1
0
        public async Task <IActionResult> Token([FromBody] vm.Login model, [FromServices] IOptions <JwtOptions> options)
        {
            if (ModelState.IsValid)
            {
                var user = await userManager.FindByNameAsync(model.Username);

                if (user != null)
                {
                    if (await userManager.CheckPasswordAsync(user, model.Password))
                    {
                        var claims = new List <Claim>()
                        {
                            new Claim(ClaimTypes.Name, user.UserName)
                        };
                        foreach (var role in await userManager.GetRolesAsync(user))
                        {
                            claims.Add(new Claim(ClaimTypes.Role, role));
                        }
                        var jwt   = options.Value;
                        var token = new JwtSecurityToken(
                            issuer: jwt.Issuer,
                            audience: jwt.Audience,
                            claims: claims,
                            notBefore: DateTime.Now,
                            expires: jwt.Expires,
                            signingCredentials: jwt.Credentials);

                        var result = new JwtSecurityTokenHandler().WriteToken(token);
                        return(Ok(result));
                    }
                }
            }
            return(BadRequest());
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> Login(vm.Login model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;

            if (ModelState.IsValid)
            {
                var result = await signInManager.PasswordSignInAsync(
                    model.Username,
                    model.Password,
                    isPersistent : true,
                    lockoutOnFailure : false);

                if (result.Succeeded)
                {
                    return(LocalRedirect(returnUrl ?? defaultRedirect));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Login failed.");
                }
            }
            return(View(model));
        }