Setting up CORS in Identity Server
When you're using Identity Server, it's very likely that sooner or later you will have the need to setup CORS to allow communication to take place securely between different domains. Thanks to it's heavy use of standardized interfaces, this is trivial in Identity Server.
Solution
The first step is to create a class that inherits from ICorsPolicyService interface provided by Identity Server. Please note that you will be making a database call every time IsOriginAllowedAsync method gets invoked. The code shown below is modified to show you a simple implementation but this would be a good place to use some form of caching methodology (e.g. Redis, NCache).
public class CorsPolicyProvider : ICorsPolicyService
{
private readonly IDbContext _dbContext;
public CorsPolicyProvider(IDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<bool> IsOriginAllowedAsync(string origin)
{
var corsOrigins = await _dbContext.AllowedCorsOrigins.ToListAsync().ConfigureAwait(false);
return corsOrigins.Any(corsOrigin => corsOrigin.Origin.Equals(origin, StringComparison.InvariantCultureIgnoreCase));
}
}
Now, the second and final step is to register ICorsPolicyService inteface and the type that you implemented. It's a good idea to tell Identity Server that this service will be singleton as it doesn't need to be re-created.
//configure factory
var factory = new IdentityServerServiceFactory();
//register CORS policy service
factory.CorsPolicyService = new Registration<ICorsPolicyService, CorsPolicyProvider> { Mode = RegistrationMode.Singleton };