ASP.Net CORE 2.2 MVC-在IIS中托管时出现Cookie身份验证问题

时间:2019-10-16 00:31:57

标签: cookie-authentication asp.net-core-mvc-2.1

这让我发疯。我使用asp.net core 2.2 MVC使用基于cookie的身份验证设置了简单的登录名。本地一切正常,但是当我部署到IIS时,我的状态为302

i)http://xxxxx/Account/LoginAsync->这是使用表单的表单发布       标签助手   ii)http://xxxxx/Home/Index->这是成功后的重定向URL       登录

这是代码。

  public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
            options.Secure = CookieSecurePolicy.Always;
            options.HttpOnly = HttpOnlyPolicy.Always;
        });
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
        {
            // options.Cookie.IsEssential = true;

            options.Cookie.HttpOnly = true;
            options.Cookie.SecurePolicy = CookieSecurePolicy.None;

            options.Cookie.Name = "myDomain.myAccount.AuthCookie";
            options.AccessDeniedPath = "/Account/Login";
            options.LoginPath = "/Account/Login";
            options.LogoutPath = "/Account/Logout";

            options.Cookie.SameSite = SameSiteMode.None;
            options.ExpireTimeSpan = TimeSpan.FromSeconds(1000);
            options.SlidingExpiration = true;
        });

        services.AddMvc(options =>
        {
            //  options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());

            var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
            options.Filters.Add(new AuthorizeFilter(policy));
            //options.Filters.Add(new AuthorizeFilter());

        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddHttpContextAccessor();

        services.AddCors();
    }

    [AllowAnonymous]
    [HttpPost]
    public async Task<IActionResult> LoginAsync(LoginModel loginRequestViewModal, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            if (loginRequestViewModal.UserName == "ab" && loginRequestViewModal.Password == "ab")
            {
                var claims = new List<Claim> {
                new Claim(ClaimTypes.Name,  loginRequestViewModal.UserName),
                new Claim(ClaimTypes.Email, "test@test.com"),
                new Claim(ClaimTypes.DateOfBirth, DateTime.Now.ToShortDateString()),
                new Claim("FullName","abc def")
            };

                var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var authProperties = new AuthenticationProperties();
                authProperties.IsPersistent = loginRequestViewModal.RememberMe;
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);

                if (!string.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl))
                {
                    return Redirect(returnUrl);
                }
                return RedirectToAction("index", "Home");
            }
            else
            {
                ViewData["ErrorMesage"] = "Invalid Credentials!! Either username or password is wrong.";
                ModelState.AddModelError(string.Empty, "Invalid Credentials!! Either username or password is wrong.");
            }
        }

        return View("Login");
    }

重定向后的视图为

    [Authorize]
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }

有人可以在这里帮我吗。它在本地工作正常。但是,当我在IIS中部署并使用有效的凭据进行测试时,它始终具有302重定向。错误的登录凭据将导致控制器出现适当的Model错误。

我是否缺少IIS中的设置?或者是因为我在设置Cookie之后执行了RedirectResult吗?

0 个答案:

没有答案