Skip to content

Commit aeebdec

Browse files
committed
Genrate JWT Token
1 parent a905879 commit aeebdec

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

MoviesApi/Controllers/AccountController.cs

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
using Microsoft.AspNetCore.Http;
22
using Microsoft.AspNetCore.Identity;
33
using Microsoft.AspNetCore.Mvc;
4+
using Microsoft.IdentityModel.Tokens;
5+
using System.IdentityModel.Tokens.Jwt;
6+
using System.Security.Claims;
7+
using System.Text;
48

59
namespace MoviesApi.Controllers
610
{
@@ -9,9 +13,11 @@ namespace MoviesApi.Controllers
913
public class AccountController : ControllerBase
1014
{
1115
private readonly UserManager<AppUser> _userManager;
12-
public AccountController(UserManager<AppUser> userManager)
16+
private readonly IConfiguration configuration;
17+
public AccountController(UserManager<AppUser> userManager, IConfiguration configuration)
1318
{
1419
_userManager = userManager;
20+
this.configuration = configuration;
1521
}
1622
[HttpPost("Register")]
1723
public async Task<IActionResult> RegisterNewUser(dtoNewUser dtouser)
@@ -50,7 +56,33 @@ public async Task<IActionResult> LogIn(dtoLogin dtolog)
5056
{
5157
if (await _userManager.CheckPasswordAsync(user, dtolog.password))
5258
{
53-
return Ok("Token");
59+
var claims = new List<Claim>();
60+
//claims.Add(new Claim("name", "value"));
61+
claims.Add(new Claim(ClaimTypes.Name, user.UserName));
62+
claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id));
63+
claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
64+
var roles = await _userManager.GetRolesAsync(user);
65+
foreach (var role in roles)
66+
{
67+
claims.Add(new Claim(ClaimTypes.Role, role.ToString()));
68+
}
69+
//signingCredentials
70+
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:SecretKey"]));
71+
var sc = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
72+
var token = new JwtSecurityToken(
73+
claims: claims,
74+
issuer: configuration["JWT:Issuer"],
75+
audience: configuration["JWT:Audience"],
76+
expires: DateTime.Now.AddHours(1),
77+
signingCredentials: sc
78+
);
79+
var _token = new
80+
{
81+
token = new JwtSecurityTokenHandler().WriteToken(token),
82+
expiration = token.ValidTo,
83+
};
84+
return Ok(_token);
85+
5486
}
5587
else
5688
{

MoviesApi/Program.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@
8787
app.UseSwaggerUI();
8888
}
8989

90+
app.UseAuthentication();
9091
app.UseHttpsRedirection();
9192

9293

0 commit comments

Comments
 (0)