MSAL.js keeps returning the following errors:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://webapi.azurewebsites.net/api/order. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://webapi.azurewebsites.net/api/order. (Reason: CORS request did not succeed).
My Back-end is hosted in Azure and is also registered as a Web API in Azure Active Directory.
The Front-end has a proxy.conf.json and is registered in Azure Active Directory.
I successfully authenticate and receive ID and Access Tokens, when I try to access API (which require authentication, I receive these errors).
My proxy.conf.json looks like:
{
"/api/*": {
"target": "https://webapi.azurewebsites.net",
"secure": true,
"changeOrigin": true,
"pathRewrite": {
"^/api": ""
}
}
}
I created an access_as_user scope (api://[Application (client) ID]/access_as_user) and set it in the ProtectedResource in the SPA - Client App
export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration {
const protectedResourceMap = new Map<string, Array<string>>();
protectedResourceMap
.set(auth.resources.graphApi.resourceUri, auth.resources.graphApi.resourceScopes)
.set(auth.resources.Api.resourceUri, auth.resources.Api.resourceScopes);
return {
interactionType: InteractionType.Redirect,
protectedResourceMap
};
}
export function MSALGuardConfigFactory(): MsalGuardConfiguration {
return {
interactionType: InteractionType.Redirect,
authRequest: {
scopes: [...auth.resources.Api.resourceScopes]
}
};
}
Simply create a json file in the app-folder and Add import line in your app.module to access the json file
import * as auth from '../app/auth-config.json';
The content of auth json file looks similar to:
"resources": {
"graphApi": {
"resourceUri": "https://graph.microsoft.com/v1.0/users",
"resourceScopes": [ "User.Read", "openid", "profile" ]
},
"Api": {
"resourceUri": "https://webapi.azurewebsites.net",
"resourceScopes": [ "api://[Application (client) ID]/User.Read",
"api://[Application (client) ID]/access_as_user" ]
}
}