【发布时间】:2019-02-08 08:16:32
【问题描述】:
我已尝试将 windows 身份验证和 JWT 与 .NET Core 2.1 一起使用。
我有以下身份验证的启动设置:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = IISDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "Test",
ValidAudience = "Test",
IssuerSigningKey = JwtSecurityKey.Create("677efa87-aa4d-42d6-adc8-9f866e5f75f7")
};
options.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = OnAuthenticationFailed
};
});
IIS 设置:
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true,
..
}
我已尝试使用以下代码 sn-p 创建具有 Windows 身份验证的 JWT 令牌:
[Route("api/[controller]")]
[ApiController]
[Authorize(AuthenticationSchemes = "Windows")]
public class AuthController : ControllerBase
{
[HttpPost("token")]
public IActionResult Token()
{
//Setup claims
var claims = new[]
{
new Claim(ClaimTypes.Name, User.Identity.Name),
//Add additional claims
};
//Read signing symmetric key
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("677efa87-aa4d-42d6-adc8-9f866e5f75f7"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
//Create a token
var token = new JwtSecurityToken(
issuer: "Test",
audience: "Test",
claims: claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
//Return signed JWT token
return Ok(new
{
token = new JwtSecurityTokenHandler().WriteToken(token)
});
}
}
在另一个控制器中我只需要使用 JWT 身份验证:
[Route("api/[controller]")]
[ApiController]
[Authorize(AuthenticationSchemes = "Bearer")]
public class ProductController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
var userName = User.Identity.Name;
var claims = User.Claims.Select(x => new { x.Type, x.Value });
return Ok(new { userName, claims });
}
}
如果 JWT 令牌已过期,那么我正确收到了响应代码 401,但我仍然会在浏览器中看到用于放置凭据的对话框。
当我想创建 JWT 令牌并禁用负责显示带有凭据的浏览器对话框的响应时,如何仅为部分配置 Windows 身份验证?如何正确组合这些东西?
【问题讨论】:
-
我正在努力解决完全相同的问题。似乎问题在于,在使用 Windows 身份验证时,IIS 将始终将“协商,NTLM”添加到身份验证响应标头值中。如果您在应用程序的中间件中检查响应,您只会看到“WWW-Authenticate Bearer”,但如果您在浏览器中检查响应,它已变为“WWW-Authenticate Bearer, Negotiate, NTLM”。浏览器看到这个并像它应该的那样弹出登录。一旦响应通过您的应用程序,这似乎由 IIS 完成。
标签: authentication asp.net-core jwt windows-authentication