简体   繁体   中英

Azure Service principal authentication for API App

I've build a simple API App with a REST Service. Now I've enabled principal authentication in Azure App Service. I'm able to get my bearer token by C# code:

public static AuthenticationResult GetS2SAccessTokenForProdMSA()
{
        return GetS2SAccessToken(authority, resource, clientId, clientSecret);
}

static AuthenticationResult GetS2SAccessToken(string authority, string resource, string clientId, string clientSecret)
{
        var clientCredential = new ClientCredential(clientId, clientSecret);
        AuthenticationContext context = new AuthenticationContext(authority, false);
        AuthenticationResult authenticationResult = context.AcquireTokenAsync(resource, clientCredential).Result;
        return authenticationResult;
}

If I want to get my bearer token by JavaScript, eg:

$.ajax({
    url: 'https://login.microsoftonline.com/1640e15a-2d4c-4903-8b89-a00c52ac3c17/oauth2/token',
    type: 'POST',
    crossOrigin: true,
    data: 'resource=https://foobar' +
                '&client_id=68b9a002-d6f9-4732-9c9c-893b2c60ba42' +
                '&client_secret=<secret>' +
                '&grant_type=client_credentials',
    contentType: 'application/x-www-form-urlencoded',
    success: function (returndata) {
        alert(formData);
    },
    error: function (errordata) {
        alert(errordata.statusText);
    }
});

I get an error in Chrome saying:

No 'Access-Control-Allow-Origin' header is present on the requested resource

But in Fiddler I can see the successful answer with my bearer token (same error in Firefox, but not in IE 11).

Why is it not possible to request the token by an AJAX request?

Am I missing something?

Cheers

You can't acquire the token from front-end with client credentials.

Instead you must use the Implicit Grant Flow to get the access token in a fragment after a redirect, or pass it to the front-end from the backend of your app.

Here you can find an example AngularJS app: https://github.com/Azure-Samples/active-directory-angularjs-singlepageapp .

Another alternative is to just not call APIs from the front-end, but call them from your back-end.

The reason for the error is that Azure AD does not allow CORS .

By the way, never put your client secret in the front-end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM