Enable CORS for Azure Rest webapi application

2020-02-16 05:30发布

I have simple jQuery page that makes calls to azure restful API to get the status of VMs. I'm facing a problem that it's complaining about Cross-Origin Resource Sharing and I can't find where to set that for the Web app/API I have.

I'm using client credentials grant to get the token https://docs.microsoft.com/en-us/azure/active-directory/develop/v1-oauth2-client-creds-grant-flow

I have finished my testing and when I tried to do the calls from jQuery/JS I got the CORS problem.

My setup involved: From Azure portal, I used App registrations to register an app of type "Web app/API", give it a homepage address "this is where it lives", created a key.

Using

POST https://login.microsoftonline.com/<tenant id>/oauth2/token
grant_type=client_credentials
client_id=application id
client_secret=application key
resource=https://management.core.windows.net/

Am I missing any missing anything? my search keeps leading me to Azure hosted apps

2条回答
放荡不羁爱自由
2楼-- · 2020-02-16 05:49

Okay, here is how to do it in short:

  1. Add Function App (charge per request)
  2. Open the Newly created function app
  3. In Proxies, select that from the right list
  4. Give it a name, route template will be your new endpoint URL, backend URL is your login endpoint eg: https://login.microsoftonline.com//oauth2/token
  5. After that, back to your function app, select the platform feature tab, Select CORS, delete all of them and enter your application URL or simply a *

You can be more specific with these, but this is enough to get the token. And all the other endpoint didn't have CORS problem.

Good luck.

查看更多
Animai°情兽
3楼-- · 2020-02-16 06:01

You cannot use a client secret from front-end Javascript. Your client secret will be public, it's basically your app's password.

Client credentials grant is for back-end applications.

You need to use e.g. the implicit grant flow with ADAL.JS/MSAL.JS to acquire tokens. Your front-end app also should be registered as Native since it is a public client.

Here is a sample app: https://github.com/Azure-Samples/active-directory-javascript-singlepageapp-dotnet-webapi

Oh, and the CORS error comes from Azure AD's token endpoint. You cannot do anything about it.

查看更多
登录 后发表回答