· 7 years ago · Dec 12, 2018, 11:36 AM
1services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
2 .AddJwtBearer(options =>
3 {
4 options.TokenValidationParameters = new TokenValidationParameters
5 {
6 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])),
7 RequireExpirationTime = true,
8 ValidateLifetime = true,
9 ValidateAudience = false,
10 ValidateActor = false,
11 ValidateIssuer = false
12 };
13 });
14
15app.UseAuthentication();
16
17public class LoginRepository
18{
19 public LoginRepository()
20 {
21 //TODO: Dependency to MongoDB will be initialized here
22 }
23
24 public LoginStatus Authenticate(string username, string password)
25 {
26 LoginStatus loginStatus = new LoginStatus();
27 string secretKey = ConfigurationManager.AppSetting["Jwt:SecretKey"];
28 int tokenExpirationHours = int.Parse(ConfigurationManager.AppSetting["Jwt:TokenExpirationHours"]);
29 //TODO: Need to add the userID in the payload. UserID will come from Database
30 Dictionary<string, string> payload = new Dictionary<string, string>() {
31 { "UserName", username}
32 };
33
34 //TODO: Need to check the username and password in Database and then generate the token
35 loginStatus.Token = JwtTokenHelper.GenerateJwtToken(secretKey, payload, tokenExpirationHours);
36
37 return loginStatus;
38 }
39}
40
41public class JwtTokenHelper
42{
43 public static string GenerateJwtToken(string secretKey, IReadOnlyDictionary<string, string> payloadContents, int tokenExpirationHours)
44 {
45 JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
46 var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
47 var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
48
49 var payloadClaims = payloadContents.Select(c => new Claim(c.Key, c.Value));
50
51 var payload = new JwtPayload("", "", payloadClaims, DateTime.Now, DateTime.Now.AddHours(tokenExpirationHours));
52
53 var header = new JwtHeader(signingCredentials);
54 var securityToken = new JwtSecurityToken(header, payload);
55
56 return jwtSecurityTokenHandler.WriteToken(securityToken);
57 }
58 }
59
60namespace SampleAPI.Controllers
61{
62 [Authorize]
63 [Produces("application/json")]
64 [Route("api/Test")]
65 public class TestController : Controller
66 {
67 [HttpGet]
68 [Route("Testing")]
69 public IActionResult Testing()
70 {
71 return Ok("Yes");
72 }
73 }
74}