Windows 身份验证不接受凭据
Windows Authentication does not accept credentials
我有一个 Identity Server(ASP.NET Core 2 with Identity Server 4 2.0.0)配置为使用 Kestrel 和 IISIntegration,在 launchSettings.json 上启用了匿名和 Windows 身份验证.我还像这样配置了 IISOptions:
services.Configure<IISOptions>(iis =>
{
iis.AutomaticAuthentication = false;
iis.AuthenticationDisplayName = "Windows";
});
services.AddAuthentication();
services.AddCors()
.AddMvc();
services.AddIdentityServer(); // with AspNetIdentity configured
app.UseAuthentication()
.UseIdentityServer()
.UseStaticFiles()
.UseCors(options => options.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin())
.UseMvcWithDefaultRoute();
我有这个客户端(还有 ASP.NET Core 2,同时启用了 Windows 和匿名身份验证,运行 在 Kestrel 上与 IISIntegration)
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddOpenIdConnect(config =>
{
config.Authority = "http://localhost:5000";
config.RequireHttpsMetadata = false;
config.ClientId = "MyClientId";
config.ClientSecret = "MyClientSecret";
config.SaveTokens = true;
config.GetClaimsFromUserInfoEndpoint = true;
});
services.AddMvc();
身份服务器在 http://localhost:5000 and the client on http://localhost:2040 上 运行。
当我启动客户端时,它会正确显示 Identity Server 的登录屏幕,但在单击 Windows 身份验证时,只会不断询问凭据。我已经查看了两个应用程序的输出 Window 并且两边都没有出现异常。我已尝试将 Identity Server 部署到 IIS 服务器(启用 Windows 身份验证且其池 运行 在 NETWORK SERVICE 下)并且重现了相同的行为。
我终于明白了。我遵循了不支持 Windows 身份验证的 Combined_AspNetIdentity_and_EntityFrameworkStorage
快速入门。从 4_ImplicitFlowAuthenticationWithExternal 快速入门复制相关代码解决了这个问题。
为简单起见,这里是允许 Windows 身份验证的快速入门代码,已修改为使用 Identity
作为用户存储:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLogin(string provider, string returnUrl = null)
{
var props = new AuthenticationProperties()
{
RedirectUri = Url.Action("ExternalLoginCallback"),
Items =
{
{ "returnUrl", returnUrl },
{ "scheme", AccountOptions.WindowsAuthenticationSchemeName }
}
};
// I only care about Windows as an external provider
var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName);
if (result?.Principal is WindowsPrincipal wp)
{
var id = new ClaimsIdentity(provider);
id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.Identity.Name));
id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name));
await HttpContext.SignInAsync(
IdentityServerConstants.ExternalCookieAuthenticationScheme,
new ClaimsPrincipal(id),
props);
return Redirect(props.RedirectUri);
}
else
{
return Challenge(AccountOptions.WindowsAuthenticationSchemeName);
}
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback()
{
var result = await HttpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);
if (result?.Succeeded != true)
{
throw new Exception("External authentication error");
}
var externalUser = result.Principal;
var claims = externalUser.Claims.ToList();
var userIdClaim = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject);
if (userIdClaim == null)
{
userIdClaim = claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
}
if (userIdClaim == null)
{
throw new Exception("Unknown userid");
}
claims.Remove(userIdClaim);
string provider = result.Properties.Items["scheme"];
string userId = userIdClaim.Value;
var additionalClaims = new List<Claim>();
// I changed this to use Identity as a user store
var user = await userManager.FindByNameAsync(userId);
if (user == null)
{
user = new ApplicationUser
{
UserName = userId
};
var creationResult = await userManager.CreateAsync(user);
if (!creationResult.Succeeded)
{
throw new Exception($"Could not create new user: {creationResult.Errors.FirstOrDefault()?.Description}");
}
}
else
{
additionalClaims.AddRange(await userManager.GetClaimsAsync(user));
}
var sid = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId);
if (sid != null)
{
additionalClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value));
}
AuthenticationProperties props = null;
string id_token = result.Properties.GetTokenValue("id_token");
if (id_token != null)
{
props = new AuthenticationProperties();
props.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = id_token } });
}
await HttpContext.SignInAsync(user.Id, user.UserName, provider, props, additionalClaims.ToArray());
await HttpContext.SignOutAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);
string returnUrl = result.Properties.Items["returnUrl"];
if (_interaction.IsValidReturnUrl(returnUrl) || Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return Redirect("~/");
}
我有一个 Identity Server(ASP.NET Core 2 with Identity Server 4 2.0.0)配置为使用 Kestrel 和 IISIntegration,在 launchSettings.json 上启用了匿名和 Windows 身份验证.我还像这样配置了 IISOptions:
services.Configure<IISOptions>(iis =>
{
iis.AutomaticAuthentication = false;
iis.AuthenticationDisplayName = "Windows";
});
services.AddAuthentication();
services.AddCors()
.AddMvc();
services.AddIdentityServer(); // with AspNetIdentity configured
app.UseAuthentication()
.UseIdentityServer()
.UseStaticFiles()
.UseCors(options => options.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin())
.UseMvcWithDefaultRoute();
我有这个客户端(还有 ASP.NET Core 2,同时启用了 Windows 和匿名身份验证,运行 在 Kestrel 上与 IISIntegration)
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddOpenIdConnect(config =>
{
config.Authority = "http://localhost:5000";
config.RequireHttpsMetadata = false;
config.ClientId = "MyClientId";
config.ClientSecret = "MyClientSecret";
config.SaveTokens = true;
config.GetClaimsFromUserInfoEndpoint = true;
});
services.AddMvc();
身份服务器在 http://localhost:5000 and the client on http://localhost:2040 上 运行。
当我启动客户端时,它会正确显示 Identity Server 的登录屏幕,但在单击 Windows 身份验证时,只会不断询问凭据。我已经查看了两个应用程序的输出 Window 并且两边都没有出现异常。我已尝试将 Identity Server 部署到 IIS 服务器(启用 Windows 身份验证且其池 运行 在 NETWORK SERVICE 下)并且重现了相同的行为。
我终于明白了。我遵循了不支持 Windows 身份验证的 Combined_AspNetIdentity_and_EntityFrameworkStorage
快速入门。从 4_ImplicitFlowAuthenticationWithExternal 快速入门复制相关代码解决了这个问题。
为简单起见,这里是允许 Windows 身份验证的快速入门代码,已修改为使用 Identity
作为用户存储:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLogin(string provider, string returnUrl = null)
{
var props = new AuthenticationProperties()
{
RedirectUri = Url.Action("ExternalLoginCallback"),
Items =
{
{ "returnUrl", returnUrl },
{ "scheme", AccountOptions.WindowsAuthenticationSchemeName }
}
};
// I only care about Windows as an external provider
var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName);
if (result?.Principal is WindowsPrincipal wp)
{
var id = new ClaimsIdentity(provider);
id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.Identity.Name));
id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name));
await HttpContext.SignInAsync(
IdentityServerConstants.ExternalCookieAuthenticationScheme,
new ClaimsPrincipal(id),
props);
return Redirect(props.RedirectUri);
}
else
{
return Challenge(AccountOptions.WindowsAuthenticationSchemeName);
}
}
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback()
{
var result = await HttpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);
if (result?.Succeeded != true)
{
throw new Exception("External authentication error");
}
var externalUser = result.Principal;
var claims = externalUser.Claims.ToList();
var userIdClaim = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Subject);
if (userIdClaim == null)
{
userIdClaim = claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);
}
if (userIdClaim == null)
{
throw new Exception("Unknown userid");
}
claims.Remove(userIdClaim);
string provider = result.Properties.Items["scheme"];
string userId = userIdClaim.Value;
var additionalClaims = new List<Claim>();
// I changed this to use Identity as a user store
var user = await userManager.FindByNameAsync(userId);
if (user == null)
{
user = new ApplicationUser
{
UserName = userId
};
var creationResult = await userManager.CreateAsync(user);
if (!creationResult.Succeeded)
{
throw new Exception($"Could not create new user: {creationResult.Errors.FirstOrDefault()?.Description}");
}
}
else
{
additionalClaims.AddRange(await userManager.GetClaimsAsync(user));
}
var sid = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId);
if (sid != null)
{
additionalClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value));
}
AuthenticationProperties props = null;
string id_token = result.Properties.GetTokenValue("id_token");
if (id_token != null)
{
props = new AuthenticationProperties();
props.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = id_token } });
}
await HttpContext.SignInAsync(user.Id, user.UserName, provider, props, additionalClaims.ToArray());
await HttpContext.SignOutAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme);
string returnUrl = result.Properties.Items["returnUrl"];
if (_interaction.IsValidReturnUrl(returnUrl) || Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return Redirect("~/");
}