【发布时间】:2018-12-30 22:21:47
【问题描述】:
我在我的应用程序中使用 cookie 和不记名身份验证。但我有奇怪的行为,我无法解释。
我确实有自定义中间件,我在其中向 Context.Items 添加了一些必需的数据。这一切都很好,但在那个中间件中,如果它的承载用户是空的,但当它的 cookie 时它就可以了。
services
.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(OAuthValidationDefaults.AuthenticationScheme,
CookieAuthenticationDefaults.AuthenticationScheme,
"Identity.Application")
.RequireAuthenticatedUser()
.Build();
});
//CookieAuthenticationDefaults.AuthenticationScheme
services.AddAuthentication()
.AddExternalAuthProviders(Configuration)
.AddFlymarkOpenIdConnectServer()
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.LoginPath = "/Identity/Account/LogIn";
options.SlidingExpiration = true;
options.Events.OnRedirectToLogin = OnRedirectToLogin;
})
.AddOAuthValidation(OAuthValidationDefaults.AuthenticationScheme,
o=>o.Events.OnCreateTicket = OnCreateTicket);
services.ConfigureApplicationCookie(config =>
{
config.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = OnRedirectToLogin
};
});
我在 CreateTicket 上使用的临时解决了我的问题
private async Task OnCreateTicket(CreateTicketContext arg)
{
if (arg.HttpContext.Items[FlymarkWeb.CurrentUserKey] == null && arg.Identity.IsAuthenticated)
{
var db= (FlymarkContext) arg.HttpContext.RequestServices.GetService(typeof(FlymarkContext));
arg.HttpContext.Items[FlymarkWeb.CurrentUserKey] =
await db.Users.FirstOrDefaultAsync(u => u.Id == arg.Identity.GetUserId());
}
}
和中间件
public async Task Invoke(HttpContext httpContext, FlymarkContext context, DomainService _sourceDomainService)
{
if (httpContext.Items[FlymarkWeb.CurrentUserKey] == null)
{
httpContext.Items[FlymarkWeb.CurrentUserKey] = httpContext.User.Identity.IsAuthenticated
? await context.Users.FirstOrDefaultAsync(u => u.Id == httpContext.User.GetUserId())
: null;
}
....
}
所以我的问题是为什么 cookie 和 oauth 不同?为什么如果它的 cookie 我可以访问中间件中的用户而它的 oauth 我不能?
【问题讨论】:
标签: asp.net-core oauth middleware