【发布时间】:2022-08-19 18:03:35
【问题描述】:
我正在构建一些 blazor wasm 应用程序 我必须使用 windows autch,因为它仅适用于企业用户。 所以我有
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
我有一些用户控制器负责获取用户名。 现在我想保护整个api所以用户不能使用我的api(因为他们是域认证的),只有这个WASM应该能够在开发中使用这个api和swagger。
对此的最佳做法是什么? jwt 也?只是为了 api 保护而不是纯粹的用户身份验证?
我确实生成了一些 jwt
[HttpGet]
[Authorize]
[Route(\"GetUser\")]
public UserModel GetUser()
{
string? login = httpContextAccessor!.HttpContext!.User?.Identity?.Name?.Replace(\"domain\\\\\", \"\");
return new UserModel{ UserName=login , JWT = CreateJWT(login)};
}
private string? CreateJWT(string? userName)
{
if (userName == null) return null;
var secretkey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(this.appSettings.JWTSettings!.Secret!));
var credentials = new SigningCredentials(secretkey, SecurityAlgorithms.HmacSha256);
var claims = new[]
{
new Claim(ClaimTypes.Name, userName),
new Claim(JwtRegisteredClaimNames.Sub, userName)
};
var token = new JwtSecurityToken(issuer: \"xxx\", audience: \"xxx\", claims: claims, expires: DateTime.Now.AddMinutes(int.Parse(this.appSettings.JWTSettings.ExpireTime!)), signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
但是如何强制 api 也检查这个 jwt 呢? 我试过了
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = true,
ValidAudience = \"xxx\",
ValidateIssuer = true,
ValidIssuer = \"xxx\",
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(a.JWTSettings.Secret!))
};
});
但这并没有改变任何东西。应用程序可以有两次builder.Services.AddAuthentication 吗?
如果没有,那么我需要构建一些自定义中间件吗? 还是有更好的解决方案?
谢谢并恭祝安康
标签: c# authentication jwt blazor webassembly