Aspnet身份安全戳验证始终返回false

时间:2018-07-10 05:13:26

标签: c# asp.net-core asp.net-identity asp.net-core-2.0 asp.net-core-identity

我正在尝试在单页面Web应用程序中使用Aspnet Identity,该应用程序使用Web api与服务器进行通信。我正在尝试配置安全性戳验证以注销用户(如果他们从另一台计算机登录)。我的配置如下-

Startup.cs

public void ConfigureServices(IServiceCollection services)
{

.....

services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddDefaultTokenProviders();

services.Configure<SecurityStampValidatorOptions>(options =>
{
    options.ValidationInterval = TimeSpan.FromSeconds(10);
});

services.AddAuthentication().Services
.ConfigureApplicationCookie(options =>
{
    options.Cookie.Name = ".appdomain";
    options.Cookie.HttpOnly = true;
    options.SlidingExpiration = true;
    options.Events.OnRedirectToAccessDenied = context => {
        context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
        return Task.CompletedTask;
    };
    options.Events.OnRedirectToLogin = context => {
        context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
        return Task.CompletedTask;
    };
});

...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
        {
            HotModuleReplacement = true
        });
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");

        routes.MapSpaFallbackRoute(
            name: "spa-fallback",
            defaults: new { controller = "Home", action = "Index" });
    });
}

我的登录方法

[HttpPost]
[Route("Login")]
[AllowAnonymous]
public async Task<JsonRecord> Login([FromBody] Login login)
{
    ApplicationUser user = await _userManager.FindByIdAsync(login.Username);
    if (user != null)
    {
        var success = _directoryService.ValidateUser(login.Username, login.Password);
        if (success)
        {
            await _userManager.UpdateSecurityStampAsync(user);
            await _signInManager.SignInAsync(user, false);
            return WrapJsonRecord(true, null, user);
        }
    }
    return WrapJsonRecord(false, "Username/password invalid");
}

但是,即使用户没有从其他任何地方登录,10秒后的任何请求也会返回401。

我正在使用自定义UserStore和数据库,并定位.NET Framework 4.6.2

如果任何人都可以告诉我我在做什么错,那将是很大的帮助。

0 个答案:

没有答案