1
+ using System ;
2
+ using System . Collections . Generic ;
3
+ using System . IdentityModel . Tokens . Jwt ;
4
+ using System . Linq ;
5
+ using System . Security . Claims ;
6
+ using System . Text ;
7
+ using Microsoft . Extensions . Options ;
8
+ using Microsoft . IdentityModel . Tokens ;
9
+ using WebApi . Entities ;
10
+ using WebApi . Helpers ;
11
+
12
+ namespace WebApi . Services
13
+ {
14
+ public interface IUserService
15
+ {
16
+ User Authenticate ( string username , string password ) ;
17
+ IEnumerable < User > GetAll ( ) ;
18
+ }
19
+
20
+ public class UserService : IUserService
21
+ {
22
+ // users hardcoded for simplicity, store in a db with hashed passwords in production applications
23
+ private List < User > _users = new List < User >
24
+ {
25
+ new User { Id = 1 , FirstName = "Test" , LastName = "User" , Username = "test" , Password = "test" }
26
+ } ;
27
+
28
+ private readonly AppSettings _appSettings ;
29
+
30
+ public UserService ( IOptions < AppSettings > appSettings )
31
+ {
32
+ _appSettings = appSettings . Value ;
33
+ }
34
+
35
+ public User Authenticate ( string username , string password )
36
+ {
37
+ var user = _users . SingleOrDefault ( x => x . Username == username && x . Password == password ) ;
38
+
39
+ // return null if user not found
40
+ if ( user == null )
41
+ return null ;
42
+
43
+ // authentication successful so generate jwt token
44
+ var tokenHandler = new JwtSecurityTokenHandler ( ) ;
45
+ var key = Encoding . ASCII . GetBytes ( _appSettings . Secret ) ;
46
+ var tokenDescriptor = new SecurityTokenDescriptor
47
+ {
48
+ Subject = new ClaimsIdentity ( new Claim [ ]
49
+ {
50
+ new Claim ( ClaimTypes . Name , user . Id . ToString ( ) )
51
+ } ) ,
52
+ Expires = DateTime . UtcNow . AddDays ( 7 ) ,
53
+ SigningCredentials = new SigningCredentials ( new SymmetricSecurityKey ( key ) , SecurityAlgorithms . HmacSha256Signature )
54
+ } ;
55
+ var token = tokenHandler . CreateToken ( tokenDescriptor ) ;
56
+ user . Token = tokenHandler . WriteToken ( token ) ;
57
+
58
+ // remove password before returning
59
+ user . Password = null ;
60
+
61
+ return user ;
62
+ }
63
+
64
+ public IEnumerable < User > GetAll ( )
65
+ {
66
+ // return users without passwords
67
+ return _users . Select ( x => {
68
+ x . Password = null ;
69
+ return x ;
70
+ } ) ;
71
+ }
72
+ }
73
+ }
0 commit comments