-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAccountController.cs
61 lines (51 loc) · 2.37 KB
/
AccountController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using AspNetCoreDashboard.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
namespace AspNetCoreDashboard.Controllers {
public class AccountController : Controller {
// use hard-coded credentials
private List<Person> people = new List<Person> {
new Person { Login="admin@gmail.com", Password="12345", Role = "admin" },
new Person { Login="user@gmail.com", Password="55555", Role = "user" }
};
[HttpPost("/token")]
public IActionResult Token(string username, string password) {
var identity = GetIdentity(username, password);
if (identity == null) {
return BadRequest(new { errorText = "Invalid username or password." });
}
var now = DateTime.UtcNow;
var jwt = new JwtSecurityToken(
issuer: AuthOptions.ISSUER,
audience: AuthOptions.AUDIENCE,
notBefore: now,
claims: identity.Claims,
expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)),
signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);
var response = new {
access_token = encodedJwt,
username = identity.Name
};
return Json(response);
}
private ClaimsIdentity GetIdentity(string username, string password) {
var person = people.FirstOrDefault(x => x.Login == username && x.Password == password);
if (person != null) {
var claims = new List<Claim> {
new Claim(ClaimsIdentity.DefaultNameClaimType, person.Login),
new Claim(ClaimsIdentity.DefaultRoleClaimType, person.Role)
};
var claimsIdentity = new ClaimsIdentity(claims, "Token",
ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
return claimsIdentity;
}
return null;
}
}
}