aspnet / Security

[Archived] Middleware for security and authorization of web apps. Project moved to https://github.com/aspnet/AspNetCore
Apache License 2.0
1.27k stars 600 forks source link

Multiple refresh for authentication on server #1898

Closed justlearntutors closed 5 years ago

justlearntutors commented 5 years ago

Authentication works on localhost. I have to refresh the site 1-4 times on remote server, when I login and logout. We use await HttpContext.SignInAsync and HttpContext.SignOutAsync. Working website is www.justlearn.com.

Is this a Bug or Feature request?:

Bug

Steps to reproduce (preferably a link to a GitHub repo with a repro project):

Startup:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.LoginPath = "/login";
options.LogoutPath = "/logout";
options.ExpireTimeSpan = TimeSpan.FromDays(7);
options.AccessDeniedPath = "/login";
});

  services.AddMvc();
}

HomeController.cs

[Route("/login")]
public async Task<IActionResult> Login(string Name)
{
      ClaimsIdentity identity = new ClaimsIdentity("user");
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, 1)); //0
identity.AddClaim(new Claim(ClaimTypes.Role, "S")); //1
identity.AddClaim(new Claim("2", Name)); //2
ClaimsPrincipal principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return Redirect("/");
}

Version of Microsoft.AspNetCore.Mvc or Microsoft.AspNetCore.App or Microsoft.AspNetCore.All:

Microsoft.AspNetCore.Mvc

mkArtakMSFT commented 5 years ago

Thanks for contacting us, @justlearntutors. Can you please provide more details about your scenario as it's not so clear what problem you're facing. Also, please provide a minimalistic repro project (ideally as a repo in GitHub) so we can investigate this further.

justlearntutors commented 5 years ago

I updated the server from asp.net core 2.0 to 2.1 and use redis server to save the session data. Some users are still having problems with the authentication.

mkArtakMSFT commented 5 years ago

Thanks @justlearntutors. @javier, can you please look into this? Thanks!

justlearntutors commented 5 years ago

During one refresh, I was logged out. I loaded the page two times, and I was logged on another user. The website is https://www.justlearn.com.

javiercn commented 5 years ago

@haok

justlearntutors commented 5 years ago

The bug still exists. If I restart the web site from iis, the authentication is working.

justlearntutors commented 5 years ago

The cookie doesn't change. .AspNetCore.Cookies has the same value. After a refresh, the user is not logged in. After a new refresh, the user is logged in.

HaoK commented 5 years ago

We would need a repro to investigate, but if they cookie doesn't change, then you wouldn't get a new user, the user comes from that cookie value, so after a sign in call, you should see the response contain a new cookie.

justlearntutors commented 5 years ago

I see a response with a new cookie after a sign in call always. The cookie does never change. Sometimes, the authentication is not working. It seems like the server is not reading the cookie.

When I restart the application pool, the authentication is working fine.

If the application pool run for <4 hours, the authentication is becoming buggy.

justlearntutors commented 5 years ago

Video with example. https://drive.google.com/file/d/1zxsp-N_PeuQSPGgXWB75MNJDSgsBsnN3/view

justlearntutors commented 5 years ago

How can I troubleshoot the issue?

justlearntutors commented 5 years ago

The issue is session. View video: https://www.youtube.com/watch?v=cLUuDNxeYYw

justlearntutors commented 5 years ago

What is the default IOTimeout for session? https://docs.microsoft.com/de-de/dotnet/api/microsoft.aspnetcore.builder.sessionoptions.iotimeout?view=aspnetcore-2.1

Eilon commented 5 years ago

@justlearntutors thanks for sharing the videos, we will take a look and let you know what we find.

justlearntutors commented 5 years ago

https://stackoverflow.com/questions/39588718/how-to-keep-user-login-in-to-system-and-logout-only-after-user-clicks-on-logout

I had the same problem and I was really confused because without any reason user was redirected to login page means that he wasn't authorized. I had changed the timeout to more than 8 hours but nothing was changed. After reading many pages such as Aspnet unexpected logout or frequent-unexpected-user-logoff I found that something is wrong with the machine key and after checking machine key in web.config file I could detect the problem with machine key. By changing the machine key and make it the same with others in Owin section everything is working well.

HaoK commented 5 years ago

Cool so the issue was one of your machine keys was not the same as the rest of your machines?

justlearntutors commented 5 years ago

The issue is still there. I copied the answer from Stackoverflow. Have not tried to change the machine key yet. Do you have any ideas for solution?

justlearntutors commented 5 years ago

I use 1 server for entire website. The session data is stored in remote redis.

justlearntutors commented 5 years ago

Are there any updates?

justlearntutors commented 5 years ago

Will Asp.net core 2.2 solve the bug?

justlearntutors commented 5 years ago

I think that the bug is aspnet/Session. I tried to save data using HttpContext.Session.SetString("test", "343"). When I view a page, string TestData = HttpContext.Session.GetString("test"). Displayed 343. When authentication was not working, displayed empty.

justlearntutors commented 5 years ago

Is the order correct?

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        // app.UseBrowserLink();
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseCookiePolicy();

    app.UseAuthentication();

    app.UseSession();

    app.UseResponseCompression();

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

@Tratcher does authentication affect session at all?

After watching the vids, did you rename the application cookie to be jluserid or is that your own custom thing?

What's your ConfigureServices look like?

Tratcher commented 5 years ago

Auth and session have no connection.

justlearntutors commented 5 years ago

"After watching the vids, did you rename the application cookie to be jluserid or is that your own custom thing?"

"What's your ConfigureServices look like?"

public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization(options => options.ResourcesPath = "Resources");

    services.AddMvc();

    services.AddSession(options =>
    {
        options.IdleTimeout = System.TimeSpan.FromHours(6);
    });

    services.AddDistributedRedisCache(options =>
    {
        options.Configuration = "PRIVATE.c1.us-west-2-2.ec2.cloud.redislabs.com:PRIVATE,password=PRIVATE,abortConnect=False";
    });

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
    {
        options.LoginPath = "/signup";
        options.LogoutPath = "/logout";
        options.ExpireTimeSpan = TimeSpan.FromDays(1);
        options.AccessDeniedPath = "/login";
    });

    services.AddAntiforgery();

    services.AddResponseCompression(options =>
    {
        options.EnableForHttps = true;
    });
}

"Auth and session have no connection."

HaoK commented 5 years ago

Everything looks fine there, at this point we really need a minimal repro that we can actually run ourselves to debug the behavior, but its likely something else that's causing unexpected users to show up in your cookies.

The authentication logic is pretty straight forward, it just decodes the cookie it gets and sets the result into HttpContext.User.

But If you are seeing weird behavior with your session, maybe you are getting incorrect cached data which might explain seeing mismatched stuff in some responses.

justlearntutors commented 5 years ago

Unexpected users have not been a problem for <3 weeks.

Auth and session is working randomly. When auth and session is not working, I refresh the page multiple times. Sometimes it works and sometimes it does not work.

I tried to use a redis server from Azure. It did not solve the problem. I tried to use in-memory storage. It did not solve the problem.

How can I look into app.UseSession?

justlearntutors commented 5 years ago

I use a web farm for the website

justlearntutors commented 5 years ago

Session and auth does not use the DistributedRedisCache?

justlearntutors commented 5 years ago

I used RedGate reflector to look into Microsoft.AspNetCore.Session.dll. It used MachineKey for the session. How can I set the machinekey?

Tratcher commented 5 years ago

Web Farm instructions: https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/web-farm?view=aspnetcore-2.1

justlearntutors commented 5 years ago

I added the codes below to ConfigureServices.

services.AddDataProtection()
.SetApplicationName("PRIVATE")
.PersistKeysToFileSystem(new DirectoryInfo(@"PRIVATE"))
.DisableAutomaticKeyGeneration();

The authentication and session data has been working perfectly.

HaoK commented 5 years ago

Cool sounds like you have got everything working now