【发布时间】:2019-09-11 23:56:40
【问题描述】:
我正在尝试使用 ASP.NET Core 2.2 构建自定义(ish)身份验证。我在几个地方看到过这个问题,但是,我还没有看到我得到的结果。
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(options =>
{
options.LoginPath = "/Account/Login";
options.LogoutPath = "/Account/Login";
options.AccessDeniedPath = "/Account/Login";
options.ExpireTimeSpan = new TimeSpan(0, 60, 0);
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
登录代码:
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim("UserId", userId.ToString()));
//userId is set above
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
var authProperties = new AuthenticationProperties
{
IsPersistent = true,
};
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), authProperties);
结果:
处理请求时发生未处理的异常。 InvalidOperationException:未注册登录身份验证处理程序。您是否忘记调用 AddAuthentication().AddCookies("Cookies",...)?
无论我在 Startup 中添加什么选项,都会出现该错误。 奇怪的是,我尝试使用 Microsoft Docs 站点中的代码(与我当前使用的代码相似/完全相同?与我当前使用的代码),以及来自另一个自定义应用程序的代码(有效)和每次,我都会遇到同样的错误。
更新:
不确定这是否有帮助或阻碍,但我偶然发现了其他东西。似乎如果我向 startup.cs 添加其他内容,它们也将无法正确配置。比如我加了Session:
services.AddSession()
和
app.UseSession()
在他们各自的方法中,我收到一条与 Session 未在中间件管道中设置一致的错误消息(错误消息:InvalidOperationException: Session has not been configured for this application or request.)
以前有人见过这种行为吗??
【问题讨论】:
-
这真的没有意义。如果您调用
AddCookie(),则不应出现该错误消息,如您的代码所示。 – 你从哪里调用你的代码,在哪里?而HttpContext是从哪里来的? -
@poke 我同意 100% 这没有意义。该代码是在 Index 方法中从
HomeController调用的,因此几乎是第一件事(它做了一些事情来从从外部传递的奇怪的 token-y 对象从 db 中收集用户信息资源)。HttpContext来自Microsoft.AspNetCore.Mvc -
@SlackerCoder 我用 ASP.NET Core
2.2.401尝试了你的代码,但对我来说效果很好。有没有重现的demo? -
您确定要检查授权 (
UseAuthorization)之前 HSTS / http 重定向代码吗?典型的模板将其放置在静态中间件之后、之前或之后(取决于您是否也想通过登录来保护静态文件)。拥有UseAuthorization首先意味着您希望用户被授权,即使他来自http(因此使用不安全的连接)。通常您希望将来将用户重定向到 http 或强制浏览器使用 https(通过 hsts) -
@TSeng 是的,抱歉,这是试图为这个问题提出一个随机解决方案的尝试(到目前为止我没有做任何工作,正如 poke 和 itminus 指出的那样,这真的应该工作)。它应该在下面,我只是在发布此示例之前没有将其移回。不过感谢您指出,我可能会忘记将其移回!
标签: c# asp.net-core