【发布时间】:2018-06-04 01:17:13
【问题描述】:
我正在从 MVC 转向 SPA + API 方法,以开发我正在制作的新应用程序,并且面临一些我似乎无法找到答案的问题。
我在 .Net Core 2 中有一个 Web API,它使用 Identity 作为其用户存储。我通过发布 JWT 令牌来保护 API,我的 SPA 在向我的控制器发出的每个请求中作为不记名令牌发送这些令牌。发行代码为:
private async Task<object> GenerateJwtTokenAsync(ApplicationUser user)
{
var roles = await _userManager.GetRolesAsync(user);
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.NameIdentifier, user.Id)
};
claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expires = DateTime.Now.AddDays(Convert.ToDouble(_configuration["JwtExpireDays"]));
var token = new JwtSecurityToken(
_configuration["JwtIssuer"],
_configuration["JwtIssuer"],
claims,
expires: expires,
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
我的问题是:获取在控制器中处理请求所需的用户信息的最佳做法是什么?
当我获得 JWT 令牌时,我有用户信息,但是关于用户的扩展信息,例如他们为哪家公司工作,在我的 SQL 数据库中。
// GET: api/Agreements
[HttpGet]
public async Task<IEnumerable<Agreement>> GetAgreementsAsync()
{
var user = await _userManager.GetUserAsync(HttpContext.User);
return _context.Agreements.Where(x => x.CompanyId == user.CompanyId);
}
我是否需要再次访问数据库以获取有关每个请求的信息?此信息是否应该放在 JWT 令牌中,在这种情况下,您应该在哪个字段中放置“自定义”信息?
【问题讨论】:
标签: c# asp.net-core asp.net-core-2.0 asp.net-core-identity