经过大量挖掘和研究,我能够创建一个解决方案(.Net Core 2)。
您必须在配置服务中添加 Cookie 身份验证,所有这些都应如下所示:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(cfg =>
{
//standard settings
})
.AddCookie(AuthTypes.CLIENT_AUTHENTICATION_TYPE, cfg =>
{
//cookie settings; the most important is following event:
cfg.Events.OnValidatePrincipal = (CookieValidatePrincipalContext ctx) =>
{
ClaimsPrincipal mainUser = ctx.HttpContext.User; //get ClaimsPrincipal from JwtBearer
ClaimsPrincipal cookieUser = ctx.Principal; //get ClaimsPrincipal read from Cookie
Debug.Assert(mainUser.Identities.Count() == 1);
//now we have to add ClaimsIdentity to main ClaimsPrincipal (from JwtBearer). We add only those absent in main ClaimsPrincipal (here is simplified solution)
var claimsToAdd = cookieUser.Identities.Where(id => id.AuthenticationType != mainUser.Identities.ElementAt(0).AuthenticationType);
mainUser.AddIdentities(claimsToAdd);
return Task.CompletedTask;
};
}
);
AuthTypes.CLIENT_AUTHENTICATION_TYPE - 它只是带有您的身份验证类型名称的字符串。
接下来我们必须稍后在 ConfigureServices 中配置默认策略过滤器(基本配置):
services.AddMvc(config =>
{
var defaultPolicy = new AuthorizationPolicyBuilder(new[] { JwtBearerDefaults.AuthenticationScheme, AuthTypes.CLIENT_AUTHENTICATION_TYPE })
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(defaultPolicy));
});
这里重要的是在 AuthorizationPolicyBuilder 中传递这个数组。
现在 Authorization 会考虑 JwtBearer,但也会读取 cookie。
现在如何设置 cookie。这可以是额外的登录过程(您在控制器级别进行):
var authProps = new AuthenticationProperties
{
IsPersistent = true,
IssuedUtc = DateTimeOffset.Now
};
await HttpContext.SignInAsync(AuthTypes.CLIENT_AUTHENTICATION_TYPE, User, authProps);
User 这里只是带有附加 ClaimsIdentities 的 ClaimsPrincipal。
这就是所有人:)