Implement API security baseline (sys_user, JWT, audit fields, transactions, unique constraints) and Web real login with 401 handling. Document setup and development workflows in root, WmsLite.Api, and WmsLite.Web README files. Co-authored-by: Cursor <cursoragent@cursor.com>
53 lines
1.7 KiB
C#
53 lines
1.7 KiB
C#
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
using Microsoft.Extensions.Options;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
using WmsLite.Api.Models;
|
|
|
|
namespace WmsLite.Api.Infrastructure.Auth;
|
|
|
|
public interface IJwtTokenService
|
|
{
|
|
(string Token, DateTime ExpiresAt) CreateToken(SysUser user);
|
|
}
|
|
|
|
public sealed class JwtTokenService : IJwtTokenService
|
|
{
|
|
private readonly JwtOptions _options;
|
|
|
|
public JwtTokenService(IOptions<JwtOptions> options)
|
|
{
|
|
_options = options.Value;
|
|
}
|
|
|
|
public (string Token, DateTime ExpiresAt) CreateToken(SysUser user)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(_options.Key))
|
|
{
|
|
throw new InvalidOperationException("Jwt:Key is not configured.");
|
|
}
|
|
|
|
var expires = DateTime.UtcNow.AddMinutes(_options.ExpiresMinutes <= 0 ? 480 : _options.ExpiresMinutes);
|
|
var claims = new List<Claim>
|
|
{
|
|
new(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
|
|
new(AuthClaimTypes.TenantId, user.TenantId),
|
|
new(AuthClaimTypes.OwnerCode, user.OwnerCode),
|
|
new(AuthClaimTypes.DisplayName, user.DisplayName ?? user.Username),
|
|
new(JwtRegisteredClaimNames.UniqueName, user.Username),
|
|
};
|
|
|
|
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.Key));
|
|
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
|
|
var token = new JwtSecurityToken(
|
|
issuer: _options.Issuer,
|
|
audience: _options.Audience,
|
|
claims: claims,
|
|
expires: expires,
|
|
signingCredentials: creds);
|
|
|
|
return (new JwtSecurityTokenHandler().WriteToken(token), expires);
|
|
}
|
|
}
|