You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ASPNetCoreBlazorLearningWBS/AspNetCoreApi/Services/JWTAuthenticationService.cs

49 lines
1.6 KiB

11 months ago
using AspNetCoreApi.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace AspNetCoreApi.Services
{
public class JWTAuthenticationService
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly string _key = "ThisIsMyMyJWTKey1234!ThisIsMyMyJWTKey1234!";
public JWTAuthenticationService(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task<string> Authenticate(string username, string password)
{
var user = await _userManager.FindByNameAsync(username);
if (user == null)
return null;
if (await _userManager.CheckPasswordAsync(user, password) == false)
return null;
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.UTF8.GetBytes(_key);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.NameIdentifier, user.Id)
}),
Expires = DateTime.UtcNow.AddHours(0.5),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}
}