ASP.NET Core Razor Pages Cookie Authentication redirects to the login page after successful login











up vote
0
down vote

favorite












I followed the article Use cookie authentication without ASP.NET Core Identity and downloaded the sample from 2.x/Cookies.



Ran the sample in VS 2017. Opened the "contact" page as directed in the documentation and from code (that it is protected), signed in using the credentials authenticated in the code using simple string comparison, it signs in if debugged, which means it adds user principal with its claims in but redirects back to log-in page instead of the contact page.



ConfigureServices:



        services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AuthorizePage("/Contact");
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

#region snippet1
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => options.ExpireTimeSpan = new System.TimeSpan(0, 10, 0));
#endregion

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();


Configure



        if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();

// Call UseAuthentication before calling UseMVC.
#region snippet2
app.UseAuthentication();
#endregion

app.UseMvc();


Authentication



            #region snippet1
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.Email),
new Claim("FullName", user.FullName),
new Claim(ClaimTypes.Role, "Administrator"),
};

var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);

var authProperties = new AuthenticationProperties
{
AllowRefresh = true,
// Refreshing the authentication session should be allowed.

ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
// The time at which the authentication ticket expires. A
// value set here overrides the ExpireTimeSpan option of
// CookieAuthenticationOptions set with AddCookie.

IsPersistent = true,
// Whether the authentication session is persisted across
// multiple requests. Required when setting the
// ExpireTimeSpan option of CookieAuthenticationOptions
// set with AddCookie. Also required when setting
// ExpiresUtc.

//IssuedUtc = <DateTimeOffset>,
// The time at which the authentication ticket was issued.

//RedirectUri = <string>
// The full path or absolute URI to be used as an http
// redirect response value.
};

await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
#endregion


and then I redirect to the contacts page but brought back to the login page.










share|improve this question


























    up vote
    0
    down vote

    favorite












    I followed the article Use cookie authentication without ASP.NET Core Identity and downloaded the sample from 2.x/Cookies.



    Ran the sample in VS 2017. Opened the "contact" page as directed in the documentation and from code (that it is protected), signed in using the credentials authenticated in the code using simple string comparison, it signs in if debugged, which means it adds user principal with its claims in but redirects back to log-in page instead of the contact page.



    ConfigureServices:



            services.Configure<CookiePolicyOptions>(options =>
    {
    options.CheckConsentNeeded = context => true;
    options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddMvc()
    .AddRazorPagesOptions(options =>
    {
    options.Conventions.AuthorizePage("/Contact");
    })
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    #region snippet1
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options => options.ExpireTimeSpan = new System.TimeSpan(0, 10, 0));
    #endregion

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();


    Configure



            if (env.IsDevelopment())
    {
    app.UseDeveloperExceptionPage();
    app.UseDatabaseErrorPage();
    }
    else
    {
    app.UseExceptionHandler("/Error");
    app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();

    // Call UseAuthentication before calling UseMVC.
    #region snippet2
    app.UseAuthentication();
    #endregion

    app.UseMvc();


    Authentication



                #region snippet1
    var claims = new List<Claim>
    {
    new Claim(ClaimTypes.Name, user.Email),
    new Claim("FullName", user.FullName),
    new Claim(ClaimTypes.Role, "Administrator"),
    };

    var claimsIdentity = new ClaimsIdentity(
    claims, CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);

    var authProperties = new AuthenticationProperties
    {
    AllowRefresh = true,
    // Refreshing the authentication session should be allowed.

    ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
    // The time at which the authentication ticket expires. A
    // value set here overrides the ExpireTimeSpan option of
    // CookieAuthenticationOptions set with AddCookie.

    IsPersistent = true,
    // Whether the authentication session is persisted across
    // multiple requests. Required when setting the
    // ExpireTimeSpan option of CookieAuthenticationOptions
    // set with AddCookie. Also required when setting
    // ExpiresUtc.

    //IssuedUtc = <DateTimeOffset>,
    // The time at which the authentication ticket was issued.

    //RedirectUri = <string>
    // The full path or absolute URI to be used as an http
    // redirect response value.
    };

    await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity),
    authProperties);
    #endregion


    and then I redirect to the contacts page but brought back to the login page.










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I followed the article Use cookie authentication without ASP.NET Core Identity and downloaded the sample from 2.x/Cookies.



      Ran the sample in VS 2017. Opened the "contact" page as directed in the documentation and from code (that it is protected), signed in using the credentials authenticated in the code using simple string comparison, it signs in if debugged, which means it adds user principal with its claims in but redirects back to log-in page instead of the contact page.



      ConfigureServices:



              services.Configure<CookiePolicyOptions>(options =>
      {
      options.CheckConsentNeeded = context => true;
      options.MinimumSameSitePolicy = SameSiteMode.None;
      });

      services.AddMvc()
      .AddRazorPagesOptions(options =>
      {
      options.Conventions.AuthorizePage("/Contact");
      })
      .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

      #region snippet1
      services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
      .AddCookie(options => options.ExpireTimeSpan = new System.TimeSpan(0, 10, 0));
      #endregion

      services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();


      Configure



              if (env.IsDevelopment())
      {
      app.UseDeveloperExceptionPage();
      app.UseDatabaseErrorPage();
      }
      else
      {
      app.UseExceptionHandler("/Error");
      app.UseHsts();
      }

      app.UseHttpsRedirection();
      app.UseStaticFiles();
      app.UseCookiePolicy();

      // Call UseAuthentication before calling UseMVC.
      #region snippet2
      app.UseAuthentication();
      #endregion

      app.UseMvc();


      Authentication



                  #region snippet1
      var claims = new List<Claim>
      {
      new Claim(ClaimTypes.Name, user.Email),
      new Claim("FullName", user.FullName),
      new Claim(ClaimTypes.Role, "Administrator"),
      };

      var claimsIdentity = new ClaimsIdentity(
      claims, CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);

      var authProperties = new AuthenticationProperties
      {
      AllowRefresh = true,
      // Refreshing the authentication session should be allowed.

      ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
      // The time at which the authentication ticket expires. A
      // value set here overrides the ExpireTimeSpan option of
      // CookieAuthenticationOptions set with AddCookie.

      IsPersistent = true,
      // Whether the authentication session is persisted across
      // multiple requests. Required when setting the
      // ExpireTimeSpan option of CookieAuthenticationOptions
      // set with AddCookie. Also required when setting
      // ExpiresUtc.

      //IssuedUtc = <DateTimeOffset>,
      // The time at which the authentication ticket was issued.

      //RedirectUri = <string>
      // The full path or absolute URI to be used as an http
      // redirect response value.
      };

      await HttpContext.SignInAsync(
      CookieAuthenticationDefaults.AuthenticationScheme,
      new ClaimsPrincipal(claimsIdentity),
      authProperties);
      #endregion


      and then I redirect to the contacts page but brought back to the login page.










      share|improve this question













      I followed the article Use cookie authentication without ASP.NET Core Identity and downloaded the sample from 2.x/Cookies.



      Ran the sample in VS 2017. Opened the "contact" page as directed in the documentation and from code (that it is protected), signed in using the credentials authenticated in the code using simple string comparison, it signs in if debugged, which means it adds user principal with its claims in but redirects back to log-in page instead of the contact page.



      ConfigureServices:



              services.Configure<CookiePolicyOptions>(options =>
      {
      options.CheckConsentNeeded = context => true;
      options.MinimumSameSitePolicy = SameSiteMode.None;
      });

      services.AddMvc()
      .AddRazorPagesOptions(options =>
      {
      options.Conventions.AuthorizePage("/Contact");
      })
      .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

      #region snippet1
      services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
      .AddCookie(options => options.ExpireTimeSpan = new System.TimeSpan(0, 10, 0));
      #endregion

      services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();


      Configure



              if (env.IsDevelopment())
      {
      app.UseDeveloperExceptionPage();
      app.UseDatabaseErrorPage();
      }
      else
      {
      app.UseExceptionHandler("/Error");
      app.UseHsts();
      }

      app.UseHttpsRedirection();
      app.UseStaticFiles();
      app.UseCookiePolicy();

      // Call UseAuthentication before calling UseMVC.
      #region snippet2
      app.UseAuthentication();
      #endregion

      app.UseMvc();


      Authentication



                  #region snippet1
      var claims = new List<Claim>
      {
      new Claim(ClaimTypes.Name, user.Email),
      new Claim("FullName", user.FullName),
      new Claim(ClaimTypes.Role, "Administrator"),
      };

      var claimsIdentity = new ClaimsIdentity(
      claims, CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);

      var authProperties = new AuthenticationProperties
      {
      AllowRefresh = true,
      // Refreshing the authentication session should be allowed.

      ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
      // The time at which the authentication ticket expires. A
      // value set here overrides the ExpireTimeSpan option of
      // CookieAuthenticationOptions set with AddCookie.

      IsPersistent = true,
      // Whether the authentication session is persisted across
      // multiple requests. Required when setting the
      // ExpireTimeSpan option of CookieAuthenticationOptions
      // set with AddCookie. Also required when setting
      // ExpiresUtc.

      //IssuedUtc = <DateTimeOffset>,
      // The time at which the authentication ticket was issued.

      //RedirectUri = <string>
      // The full path or absolute URI to be used as an http
      // redirect response value.
      };

      await HttpContext.SignInAsync(
      CookieAuthenticationDefaults.AuthenticationScheme,
      new ClaimsPrincipal(claimsIdentity),
      authProperties);
      #endregion


      and then I redirect to the contacts page but brought back to the login page.







      cookies asp.net-core razor-pages cookie-authentication






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked yesterday









      Muhammad Nouman

      185




      185
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          After making a test with this project, I could reproduce your issue with Chrome, it works with Edge.



          For making it work with Chrome, you could turn to launchSettings.json and change the sslPort for iisExpress to 44344 instead of 0.






          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














             

            draft saved


            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53372573%2fasp-net-core-razor-pages-cookie-authentication-redirects-to-the-login-page-after%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote



            accepted










            After making a test with this project, I could reproduce your issue with Chrome, it works with Edge.



            For making it work with Chrome, you could turn to launchSettings.json and change the sslPort for iisExpress to 44344 instead of 0.






            share|improve this answer

























              up vote
              1
              down vote



              accepted










              After making a test with this project, I could reproduce your issue with Chrome, it works with Edge.



              For making it work with Chrome, you could turn to launchSettings.json and change the sslPort for iisExpress to 44344 instead of 0.






              share|improve this answer























                up vote
                1
                down vote



                accepted







                up vote
                1
                down vote



                accepted






                After making a test with this project, I could reproduce your issue with Chrome, it works with Edge.



                For making it work with Chrome, you could turn to launchSettings.json and change the sslPort for iisExpress to 44344 instead of 0.






                share|improve this answer












                After making a test with this project, I could reproduce your issue with Chrome, it works with Edge.



                For making it work with Chrome, you could turn to launchSettings.json and change the sslPort for iisExpress to 44344 instead of 0.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered yesterday









                Tao Zhou

                3,71721026




                3,71721026






























                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53372573%2fasp-net-core-razor-pages-cookie-authentication-redirects-to-the-login-page-after%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    'app-layout' is not a known element: how to share Component with different Modules

                    android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                    WPF add header to Image with URL pettitions [duplicate]