Reputation: 1
CORS Issue with Ajax
When calling a .NET Core controller action with the Authorize attribute client side from an AJAX call a CORS issue occurs:
Error:
Access to XMLHttpRequest at 'https://login.microsoftonline.com/..........' (redirected from 'https://localhost:44352/home/getdata?id=1) from origin 'https://localhost:44352' 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.
this is very specific to only AJAX request.
Upvotes: 0
Views: 543
Reputation: 3857
A possibly incomplete answer based on the information as provided:
If the first authorized call being made to your ASP NET Core backend controller is via a non-interactive AJAX call and there has not been any previous direct loading of an authorized resource in the user's browser (even via an iframe or something), the call is failing because the user hasn't been prompted to interactively complete the authorization flow.
You can try adding a basic "/login" endpoint that has an authorize tag on it and returns something as simple an Ok
or NoContent
response.
[HttpGet("login")]
[Authorize]
public IActionResult Login()
{
return Ok("logged in");
}
Your UI client needs to navigate the user to that page directly before trying to access your data endpoint via AJAX - could be an iframe, pop-up, modal, whatever. This should allow the browser to complete the authorization flow via AAD first, after which subsequent AJAX calls will be authorized (until session expiry).
Upvotes: 1