Error: Access to XMLHttpRequest at 'http://somedevserver.com/SomePage?id=abc' (redirected from 'https://localhost:44359/api/Verification/signin') from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
I have enabled CORS policy in Verification service and hence the call from localhost:4200 goes to Verification/signin method.
The logic inside Verification/signin created URL http://somedevserver.com/SomePage?id=abc successfully and tries to performs a redirection.
The redirection is done using following code:
[Route("signin")]
public async Task<ActionResult<ApiResponse>> Signin([FromBody] ApiQuery request)
{
ApiResponse response = await Mediator.Send(request);
return RedirectPermanent(response.SomeEndpoint);
}
Redirection happens successfully in SoapUI when I tested Verification/signin method. However, when I integrate the Verification/signin method in Angular app, the redirection fails due to CORS issue.
Do I need to set any headers inside Verification/signin method before the redirection is performed and/or inside localhost:4200 when the web api call is made?
somedevserver.com/SomePage?id=abc -> .Net application
Verification/signin -> .Net Core 5.0 Web Api
localhost:4200 -> Angular 11 App
I have managed to resolved the pre-flight OPTION request issue by adding code in Global.asax.cs -> Application_BeginRequest
method. Now all the pre-flight request are successful, however, the browser still don't redirect.
I can see the HTML coming up in F12 -> Response tab however the redirection is not happening.
Do I need to add any special headers before return RedirectPermanent(response.SomeEndpoint);
I think the real issue is by design. Server redirections are not applicable to Single Pages Apps.
For my understanding you have 2 applications:
The entire Angular application is loaded on first browse and runs on a browser: every route is managed client side. The only way to contact the server is via apis.
In this context redirecting an api XHR background request does not trigger a browser redirect.
You can achieve your goal returning an api http error like this on backend side:
401 Unauthorized
{
"code": 401,
"message": "Unauthorized",
"details": "You need to login"
}
Than you can manage this "standard" http errors with an Angular AuthGuard like described here https://stackoverflow.com/a/38968963/3120219