I am trying to Authenticate and Authorize a simple API using IdentityServer4
but getting an error in Swagger UI. IdentityServer4
is running at https://localhost:44311 while the API is running at https://localhost:44305. I am not sure, why CORS error is coming in my API while IdentityServer4
Admin API is working perfectly fine. There are no CORS errors in IdentityServer4
Admin API. Could you help me in figuring out this error?
Errors
Auth error TypeError: Failed to fetch
In Chrome browser Console, I am getting the following error:
Access to fetch at 'https://localhost:44311/connect/token' from origin
'https://localhost:44305' has been blocked by CORS policy: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the
requested resource. If an opaque response serves your needs, set the request's mode to
'no-cors' to fetch the resource with CORS disabled.
SampleController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Get.Caa.Security.IdentityServer.Configuration.Constants;
namespace Get.Caa.Security.IdentityServer.Api.Controllers
{
/// <summary>
/// Class
/// </summary>
[Authorize]
[Route("api/test")]
public class SampleController : ControllerBase
{
/// <summary>
/// Constructor
/// </summary>
public SampleController()
{
}
/// <summary>
/// Get Api
/// </summary>
/// <returns></returns>
[HttpGet()]
public IActionResult Get()
{
return Ok("IdentityServer4 authentication is working!!");
}
}
}
Program.cs
using Get.Caa.Security.IdentityServer.Extensions;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddIdentityServer(builder.Configuration, builder.Environment);
builder.Services.AddAuthorization();
builder.Services.AddControllers();
var app = builder.Build();
app.UseIdentityServer(builder.Configuration);
app.Run();
CodePudding user response:
If you are requesting tokens from JavaScript/Browser, then you need to be prepared to support CORS.
It is important to realize that you can configure CORS in IdentityServer as well in ASP.NET CORE.
What you need to do is to enable CORS in IdentityServer and follow the instructions here. https://docs.duendesoftware.com/identityserver/v6/tokens/cors/#client-based-cors-configuration
Configure CORS in IdentityServer for its endpoints and then you configure CORS separately if you have other APIS and endpoints in the same service.