Last active
November 28, 2020 20:19
-
-
Save AbubakarSiddiq/285c08d71335d52262d0bb3b14c724d8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using BookStore.Data; | |
using BookStore.Models; | |
using Microsoft.AspNetCore.Identity; | |
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.IdentityModel.Tokens; | |
using System; | |
using System.Collections.Generic; | |
using System.IdentityModel.Tokens.Jwt; | |
using System.Linq; | |
using System.Security.Claims; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace BookStore.Controllers | |
{ | |
[Route("api/[controller]")] | |
public class AuthenticateController : Controller | |
{ | |
private UserManager<ApplicationUser> userManager; | |
public AuthenticateController(UserManager<ApplicationUser> userManager) | |
{ | |
this.userManager = userManager; | |
} | |
[HttpPost] | |
[Route("login")] | |
public async Task<IActionResult> Login([FromBody] LoginModel model) | |
{ | |
var user = await userManager.FindByNameAsync(model.Username); | |
if (user != null && await userManager.CheckPasswordAsync(user, model.Password)) | |
{ | |
var authClaims = new[] | |
{ | |
new Claim(JwtRegisteredClaimNames.Sub, user.UserName), | |
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) | |
}; | |
var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("7S79jvOkEdwoRqHx")); | |
var token = new JwtSecurityToken( | |
issuer: "https://dotnetdetail.net", | |
audience: "https://dotnetdetail.net", | |
expires: DateTime.Now.AddDays(5), | |
claims: authClaims, | |
signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256) | |
); | |
return Ok(new | |
{ | |
token = new JwtSecurityTokenHandler().WriteToken(token), | |
expiration = token.ValidTo | |
}); | |
} | |
return Unauthorized(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment