简体   繁体   中英

Angular call login microsoft api

I have an angular application that requires calling the microsoft oatuh2/token API to retrieve a token to call a specific API. I make a direct http client call because I don't want the Microsft login page:

const urlToken = 'https://login.microsoftonline.com/{TENANTID}/oauth2/v2.0/token';

const bodyToken = new HttpParams()
.set('client_id', '{client_id}')
.set('scope', 'https://search.azure.com/.default')
.set('client_secret', '{client_secret}')
.set('grant_type', 'client_credentials'); 

this.httpClient.post(urlToken, bodyToken.toString(),
{
  headers: new HttpHeaders()
    .set('Content-Type', 'application/x-www-form-urlencoded')

}).subscribe((res) => {
  console.log(res);
}) 

But this call is returning a CORS error. How to call this endpoint via my Angular front or via a Do.net API located in a private area

you don't want the Microsft login page --> using client credential flow to authorize your request to call graph api --> you must use a daemon app to call this endpoint --> client credential sample here.

Or referring to asp.net core code like below:

using Microsoft.Graph;
using Azure.Identity;

var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenant_name.onmicrosoft.com";
var clientId = "aad_app_id";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
                tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var res = await graphClient.Users["example@example.com"].Request().GetAsync();

Cors issue is because you have to use MSAL(microsoft authentication library) to do the authentication and authorization. And this is why Angular app is not able to authenticate without a sign in page. You have to do it in daemon app so that it can authenticate on behalf an application instead of a user.

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