当前启动:
services.AddHttpContextAccessor();
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
.AddOpenIdConnect(options =>
{
options.ClientId = "";
options.Authority = "";
options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");
options.ResponseType = OpenIdConnectResponseType.IdToken;
options.GetClaimsFromUserInfoEndpoint = true;
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.UseTokenLifetime = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true
};
options.SaveTokens = true;
options.Events = new OpenIdConnectEvents
{
OnRedirectToIdentityProvider = async (context) =>
{
context.ProtocolMessage.RedirectUri = "";
context.ProtocolMessage.PostLogoutRedirectUri = "";
await Task.CompletedTask;
},
OnTokenValidated = context =>
{
return Task.CompletedTask;
},
OnAuthorizationCodeReceived = (context) =>
{
Console.WriteLine("Token Received: " + context.TokenEndpointResponse.IdToken);
return Task.CompletedTask;
},
OnAuthenticationFailed = OnAuthenticationFailed
};
});
我已验证身份验证和授权是否按正确的顺序调用。
app.UseAuthentication();
app.UseAuthorization();
即使没有提到的中间件,当我仅依赖 [Authorize]
标签时,问题仍然存在。
app.Use(async (context, next) =>
{
var user = context.User;
if (user == null || user.Identity == null || !user.Identity.IsAuthenticated)
{
await context.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties
{
IsPersistent = false,
RedirectUri = ""
});
return;
}
await next();
});
问题的一个常见原因可能是使用
SameSite=none
cookie,除非您通过 https 运行,否则它不会粘住。以下 cookie 设置是最安全的,可能会解决您的问题。它们还允许您在开发人员工作站上使用 http URL。
services.AddAuthentication(options => {
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => {
options.Cookie.SameSite = SameSiteMode.Strict;
})
.AddOpenIdConnect(options => {
options.NonceCookie.SameSite = SameSiteMode.Strict;
options.CorrelationCookie.SameSite = SameSiteMode.Strict;
options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}