Open Closed

No 'Access-Control-Allow-Origin' header for Angular Application with Backend Deployed on Docker #800


User avatar
0
Mohammad created

Hello

I have deployed the backend abp applications using docker containers. When I try to run Abp Angular Application, It shows

Access to XMLHttpRequest at 'http://localhost:51533/api/abp/application-configuration' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Thanks

Check the docs before asking a question: https://docs.abp.io/en/commercial/latest/ Check the samples, to see the basic tasks: https://docs.abp.io/en/commercial/latest/samples/index The exact solution to your question may have been answered before, please use the search on the homepage.

  • ABP Framework version: v4.0.2
  • UI type: Angular
  • DB provider: EF Core
  • Tiered (MVC) or Identity Server Seperated (Angular): yes / no
  • Exception message and stack trace:
  • Steps to reproduce the issue:

20 Answer(s)
  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    Did you use the correct appsettings.json?

    CorsOrigins is configured with http://localhost:4200

    You can also check the application logs.There may be other error messages in the logs.

  • User Avatar
    0
    Mohammad created
    "App": { "CorsOrigins": "http://localhost:4200,https://localhost:44374,http://localhost:4201" },`
    

    I am using this function in the configureservices. I also have the cors setup in database.

    private void ConfigureCors(ServiceConfigurationContext context, IConfiguration configuration)
            {
                context.Services.AddCors(options =>
                {
                    options.AddPolicy(DefaultCorsPolicyName, builder =>
                    {
                        builder
                            .WithOrigins(
                                configuration["App:CorsOrigins"]
                                    .Split(",", StringSplitOptions.RemoveEmptyEntries)
                                    .Select(o => o.RemovePostFix("/"))
                                    .ToArray()
                            )
                            .WithAbpExposedHeaders()
                            .SetIsOriginAllowedToAllowWildcardSubdomains()
                            .AllowAnyHeader()
                            .AllowAnyMethod()
                            .AllowCredentials();
                    });
                });
            }
    

    Also the Auth Server after login doesn't redirect back to the angular application

    The entire application works perfectly when run through visual studio.

  • User Avatar
    0
    gterdem created
    Senior .NET Developer

    Can you share your running containers via docker ps command results. Also, can you try to exec into your backend container to check the logs under Logs folder and share the error logs?

  • User Avatar
    0
    Mohammad created

    Hello @gterdem

    I have started to get another issue. The Angular app keeps reloading with the below URL after login to the Identity Server.

    http://localhost:4200/?code=A8F1C4F953EF8900F6A62C7D16BA79F3F521EB9ED81A830F7B40E6C1A17C81D2&scope=openid%20profile%20BackendAdminAppGateway%20IdentityService%20SaasManagementService%20IntelligenceService&state=eWMwMmlYekhLclFFQnhWNUtuVW9mYXUwV3JKaFJ6eHk3MmNxc3lwSzNVdGtZ&session_state=IYqsHUIrvGi6j0VkVacwDV3tOeRRWhIw3IL4JZkrlPI.63123765C9DB6819C530237F93BC9AAD

    I am getting this error on the gateway IDX20803: Unable to obtain configuration from: 'System.String'.

    {
      "_index": "msdemo-log-2021.01",
      "_type": "_doc",
      "_id": "H9eV_3YByTuNQQ71svrw",
      "_version": 1,
      "_score": null,
      "_source": {
        "@timestamp": "2021-01-14T06:29:29.3050748+00:00",
        "level": "Information",
        "messageTemplate": "{AuthenticationScheme} was not authenticated. Failure message: {FailureMessage}",
        "message": "\"Bearer\" was not authenticated. Failure message: \"IDX20803: Unable to obtain configuration from: 'System.String'.\"",
        "fields": {
          "AuthenticationScheme": "Bearer",
          "FailureMessage": "IDX20803: Unable to obtain configuration from: 'System.String'.",
          "EventId": {
            "Id": 7,
            "Name": "AuthenticationSchemeNotAuthenticatedWithFailure"
          },
          "SourceContext": "IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler",
          "RequestId": "0HM5OAG96UDBF:0000001E",
          "RequestPath": "/api/abp/application-configuration",
          "ConnectionId": "0HM5OAG96UDBF",
          "Application": "BackendAdminAppGateway"
        }
      },
      "fields": {
        "@timestamp": [
          "2021-01-14T06:29:29.305Z"
        ]
      },
      "highlight": {
        "fields.Application.keyword": [
          "@kibana-highlighted-field@BackendAdminAppGateway@/kibana-highlighted-field@"
        ]
      },
      "sort": [
        1610605769305
      ]
    }
    
  • User Avatar
    0
    gterdem created
    Senior .NET Developer

    It seems you have a problem reaching Authentication Server and it seems related with reading settings from related file since "IDX20803: Unable to obtain configuration from: 'System.String'."" does seem an appsettings error.

    Check both environment.ts and authserver appsettings that you don't have any typing mistakes.

  • User Avatar
    0
    Mohammad created

    The app settings files are correct.

    Can you check it remotely if that possible.

    Thank You.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi

    IDX20803: Unable to obtain configuration from: 'System.String'.

    It seems that the API cannot get the info of Identity Server(https://YourIdentityServer/.well-known/openid-configuration).

    Can you check if the API in the container can access Identity Server?

  • User Avatar
    0
    Mohammad created

    Hi @maliming

    I have installed ssl for the localhost.

    The apis are unable to access identity server over https inside the container. Is there a way to install a ssl certificate inside the docker container?

  • User Avatar
    0
    gterdem created
    Senior .NET Developer

    Hello @Mohammad,

    You need to create self-signed certificate and mount it when running the containers.

    You can check here for more info.

  • User Avatar
    0
    Mohammad created

    Hello @gterdem

    I have followed this document. The dev certs only work for localhost.

    The communication between containers is the problem since they use the service name as the url.

    If you could share any article or documentation for hosting abp microservices with ssl support in docker containers that would be helpful.

    thanks

  • User Avatar
    0
    gterdem created
    Senior .NET Developer

    This is related with DevOps and varies on your prod environtment and orchestration. You only need identityServer to be publicly facing https. Try forwarding headers.

  • User Avatar
    0
    Mohammad created

    So Far I have followed all the suggestions provided above

    1. You need to create self-signed certificate and mount it when running the containers. - the Auth Server has a valid certificate.
    2. http://YourIdentityServer/.well-known/openid-configuration - I made a CURL call from docker cli and the apis can fetch the openid configuration

    This is the error i am getting in the logs

    SELECT i."Id", i."ConcurrencyStamp", i."CreationTime", i."CreatorId", i."DeleterId", i."DeletionTime", i."Description", i."DisplayName", i."Emphasize", i."Enabled", i."ExtraProperties", i."IsDeleted", i."LastModificationTime", i."LastModifierId", i."Name", i."Required", i."ShowInDiscoveryDocument"
    FROM "IdentityServerIdentityResources" AS i
    WHERE @__ef_filter__p_0 OR NOT (i."IsDeleted")
    ORDER BY i."Id"
    
    Failed executing DbCommand ("1"ms) [Parameters=["@__ef_filter__p_0='?' (DbType = Boolean)"], CommandType='Text', CommandTimeout='30']"
    ""SELECT i.\"Id\", i.\"ConcurrencyStamp\", i.\"CreationTime\", i.\"CreatorId\", i.\"DeleterId\", i.\"DeletionTime\", i.\"Description\", i.\"DisplayName\", i.\"Emphasize\", i.\"Enabled\", i.\"ExtraProperties\", i.\"IsDeleted\", i.\"LastModificationTime\", i.\"LastModifierId\", i.\"Name\", i.\"Required\", i.\"ShowInDiscoveryDocument\"
    FROM \"IdentityServerIdentityResources\" AS i
    WHERE @__ef_filter__p_0 OR NOT (i.\"IsDeleted\")
    ORDER BY i.\"Id\""
    

    But the problem of angular application redirecting infinitely after login still persists.

    It would be helpful if you can connect remotely and provide assistance.

    Thank You

  • User Avatar
    0
    gterdem created
    Senior .NET Developer

    Can it be related with chrome bug? You can check related solution in this article.

  • User Avatar
    0
    Mohammad created

    Hi @gterdem

    I tried the solution from that article it didnt work.

    I added options.TokenValidationParameters.ValidateIssuer = false; for all my microservices now it works.

    Is it a valid fix and is it applicable for production deployment?

    context.Services.AddAuthentication("Bearer")
                    .AddJwtBearer(options =>
                    {
                        options.Authority = configuration["AuthServer:Authority"];
                        options.Audience = configuration["AuthServer:ApiName"];
                        options.RequireHttpsMetadata = false;
                        options.TokenValidationParameters.ValidateIssuer = false;
                    });
    
  • User Avatar
    0
    gterdem created
    Senior .NET Developer

    I added options.TokenValidationParameters.ValidateIssuer = false; for all my microservices now it works.

    It's probably because you updated issuer before removing the old cookies/tokens. Validating issuer should work with clean cookies. Even if you don't validate the issuer, if you are using microservices behind the reverse proxy and not facing public world; i don't think it should be a problem.

  • User Avatar
    0
    jhan created

    I'm having exactly the same issue here.

    v4.2.0 Module Template Solution

    Everything runs well when I launch 3 projects (IdentityServer, HttpApi and Blazor) from VS.

    I could manage to run IdentityServer and HttpApi on Docker but Blazor. so those two projects are running on docker and Blazor running form VS.

    I got exactly the same type error above.

    Access to XMLHttpRequest at 'https://localhost:44326/connect/userinfo' from origin 'https://localhost:44307' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. blazor.webassembly.js:1

    System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'System.String'. at Microsoft.IdentityModel.Protocols.ConfigurationManager1.GetConfigurationAsync(CancellationToken cancel) at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() [16:16:31 ERR] Connection id "0HM68BS83K3PH", Request id "0HM68BS83K3PH:0000000B": An unhandled exception was thrown by the application. System.InvalidOperationException: IDX20803: Unable to obtain configuration from: 'System.String'. at Microsoft.IdentityModel.Protocols.ConfigurationManager1.GetConfigurationAsync(CancellationToken cancel) at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync() at Microsoft.AspNetCore.Authentication.AuthenticationHandler1.AuthenticateAsync() at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme) at Microsoft.AspNetCore.Builder.ApplicationBuilderAbpJwtTokenMiddlewareExtension.<>c__DisplayClass0_0.<<UseJwtTokenMiddleware>b__0>d.MoveNext() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Volo.Abp.AspNetCore.Tracing.AbpCorrelationIdMiddleware.InvokeAsync(HttpContext context, RequestDelegate next) at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass6_1.<<UseMiddlewareInterface>b__1>d.MoveNext() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication1 application)

    I tired using options.TokenValidationParameters.ValidateIssuer = false; but does not help

    It would be nice if the template solution have docker settings by default.

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi @jhan

    https://support.abp.io/QA/Questions/800#answer-e1773abc-14d3-565e-57c3-39fa15e777ca

  • User Avatar
    0
    jhan created

    @maliming

    I ran IdentityServer on docker container and can access the configuration from my browser. https://localhost:44326/.well-known/openid-configuration (I created self-signed certificate and mount it)

    When HttpApi runs on the same docker container, I can authorise through swagger page. but I cannot when HttpApi runs from VS.

    I read that the cors settings in IdentityServer only workes for the service running on the same container for localhost. but somethin weird is that when I remove the cors settings in IdentityServer, the blazor page does not even open.

    I think that menas that some part works with cors setting, but some part does not with IdentityServer running on Docker.

    I also tried adding below code in IdentityServer, but does not work.

    Configure<IdentityServerOptions>(option => { option.IssuerUri = "https://127.0.0.1:44326/"; //DNS and IP });

    https://stackoverflow.com/questions/44481538/identity-server-4-and-docker

  • User Avatar
    0
    maliming created
    Support Team Fullstack Developer

    hi jhan

    If you can provide simple steps to reproduce the problem, I can check it further.

  • User Avatar
    0
    ServiceBot created
    Support Team Automatic process manager

    This question has been automatically marked as stale because it has not had recent activity.

Made with ❤️ on ABP v9.1.0-preview. Updated on December 10, 2024, 06:38