1
1
using Microsoft . AspNetCore . Http ;
2
2
using Microsoft . AspNetCore . Identity ;
3
3
using Microsoft . AspNetCore . Mvc ;
4
+ using Microsoft . IdentityModel . Tokens ;
5
+ using System . IdentityModel . Tokens . Jwt ;
6
+ using System . Security . Claims ;
7
+ using System . Text ;
4
8
5
9
namespace MoviesApi . Controllers
6
10
{
@@ -9,9 +13,11 @@ namespace MoviesApi.Controllers
9
13
public class AccountController : ControllerBase
10
14
{
11
15
private readonly UserManager < AppUser > _userManager ;
12
- public AccountController ( UserManager < AppUser > userManager )
16
+ private readonly IConfiguration configuration ;
17
+ public AccountController ( UserManager < AppUser > userManager , IConfiguration configuration )
13
18
{
14
19
_userManager = userManager ;
20
+ this . configuration = configuration ;
15
21
}
16
22
[ HttpPost ( "Register" ) ]
17
23
public async Task < IActionResult > RegisterNewUser ( dtoNewUser dtouser )
@@ -50,7 +56,33 @@ public async Task<IActionResult> LogIn(dtoLogin dtolog)
50
56
{
51
57
if ( await _userManager . CheckPasswordAsync ( user , dtolog . password ) )
52
58
{
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
+
54
86
}
55
87
else
56
88
{
0 commit comments