3

I'm currently having an issue with attempts to get the access token from the IdentityServer4 instance which is containerized with the docker. What's strange, is that it works when I run the IdentityServer intance locally. I'm using the AspNetCoreIdentity template.

After I enter the login infomation, The application just redirects me to the login page. It happens on the Redirect(model.ReturnUrl) line with the ReturnUrl value being "/connect/authorize/callback?response_type=code&state&client_id=postman-api&scope=postman.api&redirect_uri=https%3A%2F%2Fwww.getpostman.com%2Foauth2%2Fcallback"

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(LoginInputModel model, string button)
    {
        var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
        ...
        if (ModelState.IsValid)
        {
            var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberLogin, lockoutOnFailure: true);
            if (result.Succeeded)
            {
                var user = await _userManager.FindByNameAsync(model.Username);
                await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, clientId: context?.ClientId));

                if (context != null)
                {
                    ...
                    return Redirect(model.ReturnUrl);
                }
             ...
    }

Here are the code and the configuration files:

  1. The client and apis configuration:

    public static IEnumerable<ApiResource> GetApis()
    {
        return new ApiResource[]
        {
            new ApiResource("basket.api", "Basket Api"),
            new ApiResource("postman.api", "Postman Test Resource")
        };
    }
    
    public static IEnumerable<Client> GetClients()
    {
        return new[]
        {
            new Client
            {
                ClientId = "postman-api",
                ClientName = "Postman client",
                AllowAccessTokensViaBrowser = true,
                RequireConsent = false,
                RedirectUris = {"https://www.getpostman.com/oauth2/callback"},
                PostLogoutRedirectUris = {"https://www.getpostman.com"},
                AllowedCorsOrigins = {"https://www.getpostman.com"},
                EnableLocalLogin = true,
    
                AllowedGrantTypes = GrantTypes.Code,
                ClientSecrets = { new Secret("SomeValue".Sha256()) },
    
                AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    "postman.api",
                    "basket.api"
                }
            }
        };
    }
    
  2. The dockerfile

FROM mcr.microsoft.com/dotnet/core/aspnet:2.1-stretch-slim AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/core/sdk:2.1-stretch AS build
WORKDIR /src
COPY ["Auth2.2/Auth2.2.csproj", "Auth2.2/"]
RUN dotnet restore "Auth2.2/Auth2.2.csproj"
COPY . .
WORKDIR "/src/Auth2.2"
RUN dotnet build "Auth2.2.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "Auth2.2.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Auth2.2.dll"]
  1. The IdentityServer docker configuration from the docker-compose file:
  auth2.2:
    image: ${DOCKER_REGISTRY-}auth22
    build:
      context: .
      dockerfile: Auth2.2/Dockerfile
    ports:
      - "5000:80"
  1. The values I use in Postman to get the access token

3 Answers 3

4

I was running into this problem as well, and was able to get it solved this afternoon. Hope this helps you too.

There was a recent update in Dec '19 to Chrome and Chromium that changed the allowed values for the SameSite cookie attribute. This created an incompatibility that was not allowing cookies to be stored properly in Postman, in my case due to versioning issues with .Net Core. A brief explanation is provided as the last comment in this thread here: https://community.getpostman.com/t/using-postman-to-test-identityserver4-oauth-authentication-code-flow/9524

What I did to fix this issue was:

1) Update the version of .net core used in my Identity Server. In my case, I was using .Net Core 2.0, which I updated to 2.2.8

2) Update my Cookie Policy Options in my startup.cs file:

//Setup samesite cookie handling
    private void CheckSameSite(HttpContext httpContext, CookieOptions options)
    {
        if (options.SameSite == SameSiteMode.None)
        {
            var userAgent = httpContext.Request.Headers["User-Agent"].ToString();
            if (DisallowsSameSiteNone(userAgent))
            {
                //.net core >3.0 should change value to SameSiteMode.Unspecified
                options.SameSite = (SameSiteMode)(-1);
            }
        }
    }

    private static bool DisallowsSameSiteNone(string userAgent)
    {
        // Cover all iOS based browsers here. This includes:
        //   - Safari on iOS 12 for iPhone, iPod Touch, iPad
        //   - WkWebview on iOS 12 for iPhone, iPod Touch, iPad
        //   - Chrome on iOS 12 for iPhone, iPod Touch, iPad
        // All of which are broken by SameSite=None, because they use the
        // iOS networking stack.
        // Notes from Thinktecture:
        // Regarding https://caniuse.com/#search=samesite iOS versions lower
        // than 12 are not supporting SameSite at all. Starting with version 13
        // unknown values are NOT treated as strict anymore. Therefore we only
        // need to check version 12.
        if (userAgent.Contains("CPU iPhone OS 12")
           || userAgent.Contains("iPad; CPU OS 12"))
        {
            return true;
        }

        // Cover Mac OS X based browsers that use the Mac OS networking stack.
        // This includes:
        //   - Safari on Mac OS X.
        // This does not include:
        //   - Chrome on Mac OS X
        // because they do not use the Mac OS networking stack.
        // Notes from Thinktecture: 
        // Regarding https://caniuse.com/#search=samesite MacOS X versions lower
        // than 10.14 are not supporting SameSite at all. Starting with version
        // 10.15 unknown values are NOT treated as strict anymore. Therefore we
        // only need to check version 10.14.
        if (userAgent.Contains("Safari")
           && userAgent.Contains("Macintosh; Intel Mac OS X 10_14")
           && userAgent.Contains("Version/"))
        {
            return true;
        }

        // Cover Chrome 50-69, because some versions are broken by SameSite=None
        // and none in this range require it.
        // Note: this covers some pre-Chromium Edge versions,
        // but pre-Chromium Edge does not require SameSite=None.
        // Notes from Thinktecture:
        // We can not validate this assumption, but we trust Microsofts
        // evaluation. And overall not sending a SameSite value equals to the same
        // behavior as SameSite=None for these old versions anyways.
        if (userAgent.Contains("Chrome/5") || userAgent.Contains("Chrome/6"))
        {
            return true;
        }

        return false;
    }

    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        ...
        //set cookie policies
        services.Configure<CookiePolicyOptions>(options =>
        {
            //.net core >3.0 should change value to SameSiteMode.Unspecified
            options.MinimumSameSitePolicy = (SameSiteMode)(-1);
            options.OnAppendCookie = cookieContext =>
                CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
            options.OnDeleteCookie = cookieContext =>
                CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
        });
        ...
    }

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        //set cookie policy before authentication/authorization setup
        app.UseCookiePolicy();

        //use identity and identityserver to serve tokens
        app.UseAuthentication();
        app.UseIdentityServer();
        ...
    }

3) Redeploy my site to Azure.

This allowed me to connect with Postman to receive tokens. Hopefully you've already resolved your issue by now, and hopefully this will help someone else as lost as I was for several days trying to figure out what was wrong.

More info can be found at these resources:
https://community.getpostman.com/t/using-postman-to-test-identityserver4-oauth-authentication-code-flow/9524
https://devblogs.microsoft.com/aspnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/
https://learn.microsoft.com/en-us/aspnet/core/security/samesite?view=aspnetcore-3.1

1
  • Thanks a lot for this! This worked for me using 3.1, at first i had to set SameSite to Unspecified and still didn't work. I tried None and it worked.
    – sshanzel
    May 7, 2020 at 16:47
1

The above answer helped me a lot, this article helped me to solve this issue
But what worked for me to just set always

options.SameSite = SameSiteMode.Unspecified;
0

I had the same problem, IdentityServer4 running on Kubernetes (K8s) redirects to the login page after /connect/authorize/callback

If you are running your IdentityServer4 on K8s and you have a proxy like Nginx with Ingress controller, then the proxy may use HTTP internally.

Check how to configure ASP.NET Core to work with proxy servers and load balancers https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-3.1

Also check here https://github.com/IdentityServer/IdentityServer4/issues/1299 to see how others fixed this problem using a middleware like

app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

or

app.Use(async (context, next) =>
{
   context.Request.Scheme = "https";
   await next.Invoke();
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.