ASP.NET Core 1.0:身份:用户授权失败:Identity.Application受到挑战

时间:2020-07-29 19:25:57

标签: asp.net-core asp.net-identity

我有一个使用Identity的ASP.NET Core Web应用程序。随机地,当用户登录并尝试导航到页面时,它将注销用户(在登录几秒钟内)并重定向到登录页面。我查看了应用程序日志,发现以下错误:

Request starting HTTP/1.1 GET http://****.com:900/Site/Payment/Edit  
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
  Authorization failed for user: . ====>user is null. 
warn: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
  Authorization failed for the request at filter ' 
  Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
  Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[12]
  AuthenticationScheme: Identity.Application was challenged.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
  Request finished in 0.5844ms 302
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
  Request starting HTTP/1.1 GET http://****.com:900/Site/Account/Login?                                              
                                                            ReturnUrl=%2FSite%2FPayment%2FEdit

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        
        services.AddSingleton(Configuration);

        // Add framework services.
        services.AddDbContext<ApplicationDbContext>();
        services.AddTransient<ETContextSeedData>();

        //services.AddIdentity<ApplicationUser, IdentityRole>()
        //    .AddEntityFrameworkStores<ApplicationDbContext>()
        //    .AddDefaultTokenProviders();


        services.AddIdentity<ApplicationUser, IdentityRole>(config =>
        {
            config.User.RequireUniqueEmail = true;
            config.Password.RequiredLength = 8;
            config.Cookies.ApplicationCookie.LoginPath = "/Account/Login";
            config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
            {
                OnRedirectToLogin = async ctx =>
                {
                    if (ctx.Request.Path.StartsWithSegments("/api") &&
                      ctx.Response.StatusCode == 200)
                    {
                        ctx.Response.StatusCode = 401;
                    }
                    else
                    {
                        ctx.Response.Redirect(ctx.RedirectUri);
                    }
                    await Task.Yield();
                }
            };
        })
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

        services.AddMvc(config =>
        {
            if (_env.IsProduction())
            {
                config.Filters.Add(new RequireHttpsAttribute());
            }
        })
        .AddJsonOptions(config =>
        {
            config.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        });
        
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

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

    }

我不确定是什么引起了问题。从日志来看,这似乎不是cookie过期的问题。感谢所有帮助,因为这会影响最终用户。

谢谢 NH

编辑:提琴手请求标头:

 GET http://****.com:900/Site/Contact HTTP/1.1
 Host: ****.com:900
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 Edg/84.0.522.44
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Referer: http://****com:900/site/Account/Summary
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Cookie: .AspNetCore.Antiforgery.n0bc8J6-yzQ=CfDJ8MSxrnt_ZSVBvpO65ZdTXCRU2n9b31789uDg2YldfqnnM1AVBH83rwOXqkdK0PLQb2HcXH9Q1srYL1RVRW_onZo1f9E0sxVjPT0_8IbPy1RLFgRWUXA3JvxjubkNfXbnIJrZHevLh294RiEJ3TLlqxI

    Response:
HTTP/1.1 302 Found
Content-Length: 0
Location: http://****.com:900/Site/Account/Login?  ReturnUrl=%2FSite%2FContact
Server: Kestrel
X-Powered-By: ASP.NET
Date: Thu, 30 Jul 2020 13:52:53 GMT

控制器代码: 私有只读字符串_externalCookieScheme; 私有只读UserManager _userManager;

    [HttpGet]
    [AllowAnonymous]
    public async Task<IActionResult> Login(string returnUrl = null)
    {
        // Clear the existing external cookie to ensure a clean login process
        await HttpContext.Authentication.SignOutAsync(_externalCookieScheme);

        ViewData["ReturnUrl"] = returnUrl;
        return View();
    }



    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;

        if (string.IsNullOrEmpty(returnUrl))
            returnUrl = Url.Action(nameof(Home), "Account");

        if (ModelState.IsValid)
        {
            var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: true);
            if (result.Succeeded)
            {
                var user = await _userManager.FindByEmailAsync(model.UserName);
                if (user != null && !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    return RedirectToAction("Email", "Verify");
                }
                _logger.LogInformation(1, "User logged in.");

                return RedirectToLocal(returnUrl);
            }
            if (result.RequiresTwoFactor)
            {
                return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            }
            if (result.IsLockedOut)
            {
                _logger.LogWarning(2, "User account locked out.");
                return View("Lockout");
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return View(model);
            }
        }
        return View(model);
    }

0 个答案:

没有答案