Nick
Nick

Reputation: 175

Chrome SameSite: Identity Server 4 (Code flow) + Web API Core 3.1 + Angular 8

Our application is the following:

Our application used to work perfectly prior to the Chrome SameSite Updates. Now, whenever we input the username password and login (Identity.Web - localhost:5555), the browser redirects to (Angular 8 - localhost:4200), then back directly to login page.

Before, there used to be an auth-callback, then login to dashboard.

You can find below our configuration:

Identity.Web (config.cs)

        var redirectUris = new List<string> { frontendUrl + "/auth-callback", frontendUrl + "/silent-refresh.html" };

        var allowedCorsOrigins = new List<string> { frontendUrl };

        var postLogoutRedirectUris = new List<string> { frontendUrl + "/signout-callback-oidc" };

        return new List<Client>
        {
           new Client
           {
                RequireConsent = false,
                ClientId = "angular_spa",
                ClientName = "Angular 4 Client",
                AllowedGrantTypes = GrantTypes.Code,
                RequirePkce = true,
                RequireClientSecret = false,
                AllowedScopes = new List<string> {"openid", "profile", "api1"},
                RedirectUris = redirectUris,
                PostLogoutRedirectUris = postLogoutRedirectUris,
                AllowedCorsOrigins = allowedCorsOrigins,
                AllowAccessTokensViaBrowser = true,

           }
        };

Identity.Web (Startup.cs)

 var settings = Configuration.GetSection(nameof(MongoDbSettings)).Get<MongoDbSettings>();

        var mongoDbContext = new MongoDbContext(settings.ConnectionString, settings.DatabaseName);

        services.AddIdentity<ApplicationUser, MongoIdentityRole>()
                .AddMongoDbStores<ApplicationUser, MongoIdentityRole, Guid>(mongoDbContext)
                .AddDefaultTokenProviders();

        services.Configure<MongoSettings>(options =>
        {
            options.ConnectionString = Configuration.GetSection("MongoDbSettings:ConnectionString").Value;
            options.DatabaseName = Configuration.GetSection("MongoDbSettings:DatabaseName").Value;
        });


        services.AddIdentityServer(options => { options.Events.RaiseSuccessEvents = true; })
                .AddDeveloperSigningCredential()
                .AddAspNetIdentity<ApplicationUser>()
                .AddProfileService<ProfileService>()
                .AddMongoRepository()
                .AddClients()
                .AddIdentityApiResources();

Web.Api (Startup.cs)

services.AddAuthentication()
                  .AddIdentityServerAuthentication("api1", options =>
                  {
                      options.Authority = Configuration.GetSection("IdentityServer:BaseUrl").Value;
                      options.RequireHttpsMetadata = false;
                      options.ApiName = "api1";
                      options.TokenRetriever = (request) =>
                      {
                          string token = TokenRetrieval.FromAuthorizationHeader().Invoke(request);
                          if (string.IsNullOrEmpty(token))
                          {
                              token = TokenRetrieval.FromQueryString().Invoke(request);
                          }
                          return token;
                      };
                  });

Note: Everything works perfectly in Firefox. We read this article, and applied what's there, but it didn't work.

Upvotes: 0

Views: 3303

Answers (3)

Anupam Maiti
Anupam Maiti

Reputation: 245

You will get below console warring in Google Chrome and your Identity server failed to redirect to Client App for Chrome version 80.

A cookie associated with a resource at was set with SameSite=None but without Secure. It has been blocked, as Chrome now only delivers cookies marked SameSite=None if they are also marked Secure. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5633521622188032.

To Fix this , you need to do changes mention in below link with additional changes mention below.

https://www.thinktecture.com/en/identity/samesite/prepare-your-identityserver/

NOTE : For .Net Core 2.2 , set SameSite = (SameSiteMode)(-1) , For .Net Core 3.0 or above , set SameSite = SameSiteMode.Unspecified

Also , for Chrome 80 version , add this extra condition -

 if ( userAgent.Contains("Chrome/8"))
            {
                return true;
            }

Upvotes: 4

Darren Street
Darren Street

Reputation: 1838

I had been getting the console messages for months, but google seem to have switched over to this requirement (for the UK) last night.

A cookie associated with a resource at http://localhost/ was set with `SameSite=None` but without `Secure`.

Powered up my app this morning and bang. Same issue as you. It worked in Firefox if i logged out of the IDsrv first.

As mentioned above there is a workaround and it works for .netCore 3.1. The links weren't that clear to me so I'd thought I step through the fix to help out.

  1. Open up your Identity server solution (in Visual Studio).

  2. Create a new folder called Extensions and a class within called "SameSiteCookiesServiceCollectionExtensions"

  3. Paste in this code from the link above... https://www.thinktecture.com/en/identity/samesite/prepare-your-identityserver/

  4. However, this isn't enough to make it work. In that class find the "DisallowsSameSiteNone" method and add the following to the bottom (before the closing return statment)

        var chromeVersion = GetChromeVersion(userAgent);
    
        if (chromeVersion >= 80)
        {
            return true;
        }
    
  5. then add the supporting method "chromeVersion"

    private static int GetChromeVersion(string userAgent)
    {
        try
        {
            var subStr = Convert.ToInt32(userAgent.Split("Chrome/")[1].Split('.')[0]);
            return subStr;
        }
        catch (Exception)
        {
            return 0;
        }
    }
    
  6. You are done with this file. Save it.

  7. In your startup.cs file (in the root of your project) add this statement in the configureServices method (I added mine before the AddIdentityServer options).

    services.ConfigureNonBreakingSameSiteCookies();

  8. and finally, in the Configure method add...

    app.UseCookiePolicy();

    app.UseAuthentication();

Build and try you app again. I hope this helps you out

Upvotes: 3

Mehrdad
Mehrdad

Reputation: 1731

Chrome browser has some things with 5555 port, change your Identity.Web port, I hope it works.

Upvotes: -1

Related Questions