Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identity Server 4 - Allowed Origins configured and origin is not allowed

I have a SPA and API in the same project and I keep getting the following errors when I make a request to the API.

AllowedOrigins configured and origin http://localhost:5000 is not allowed
CorsPolicyService did not allow origin: http://localhost:5000

The path to the api is: http://localhost:5000. I made sure I have the origin specified in the ClientCorsOrigins table for the client and I also added a policy in my Startup.cs:

services.AddCors(options =>
            {
                options.AddPolicy("default", policy =>
                {
                    policy.WithOrigins("http://localhost:5000")
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                });
            });

I've checked the docs and configuration multiple times and I can't figure out why I'm having this issue when I have the origin specified in the ClientCorsOrigins table. I'm using Google Chrome.

like image 695
user2531854 Avatar asked Jul 13 '18 13:07

user2531854


1 Answers

You need to add a row/record into [dbo].[ClientCorsOrigin] table with your ClientId and Origin.

CorsPolicyProvider.cs has a check in line #62:

if (await corsPolicyService.IsOriginAllowedAsync(origin))

when it returns false, you have your "CorsPolicyService did not allow origin: http://localhost:5000" message in line #69.

I assume, you are using IdentityServer4.EntityFramework. Here is the IsOriginAllowedAsync method from CorsPolicyService.cs located in IdentityServer4.EntityFramework.Services namespace:

    /// <summary>
    /// Determines whether origin is allowed.
    /// </summary>
    /// <param name="origin">The origin.</param>
    /// <returns></returns>
    public Task<bool> IsOriginAllowedAsync(string origin)
    {
        // doing this here and not in the ctor because: https://github.com/aspnet/CORS/issues/105
        var dbContext = _context.HttpContext.RequestServices.GetRequiredService<IConfigurationDbContext>();

        var origins = dbContext.Clients.SelectMany(x => x.AllowedCorsOrigins.Select(y => y.Origin)).ToList();

        var distinctOrigins = origins.Where(x => x != null).Distinct();

        var isAllowed = distinctOrigins.Contains(origin, StringComparer.OrdinalIgnoreCase);

        _logger.LogDebug("Origin {origin} is allowed: {originAllowed}", origin, isAllowed);

        return Task.FromResult(isAllowed);
    }

Look at isAllowed, it is populated with data from AllowedCrossOrigins collection the content of which is stored in the [dbo].[ClientCorsOrigin] table.

So, please double check what you have in ClientCorsOrigin table.

like image 71
Antipod Avatar answered Oct 31 '22 03:10

Antipod