superwalnut
superwalnut

Reputation: 319

how to implement authentications using Azure Active Directory for Web API and angular app

I am trying to pass Azure Active Directory credentials from an Angular 2 app to an ASP.NET Core 2.0 Web API so that the Web API can react based on the user's properties and permissions.

If I authenticate at the Angular app, how do I pass the credentials to the API to authenticate?

If I am using OpenIdConnect, it requires to enter username & password at a Microsoft url.

Upvotes: 1

Views: 328

Answers (2)

Sam
Sam

Reputation: 63

I solved this problem by registrating my api and setting it up in angular with microsoft-adal-angular6 package, the link contains information about how to set it up. And in your api you need to add this code:

in startup.cs and than in ConfigureServices :

        // THIS IS THE IMPORT PART OF CODE
        services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
            .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));

And in startup.cs Configure add :

app.UseAuthentication();

And now in appsettings.json add this :

"AzureAd": {
"Instance": "YOUR AZURE LOGIN LINK",
"Domain": "YOUR AZURE LOGIN DOMAIN LINK",
"TenantId": "YOUR AZURE AD",
"ClientId": "APPLICATION ID",
"CallbackPath": "localhost:xxxx/home"

}

Upvotes: 0

Martin Brandl
Martin Brandl

Reputation: 59001

First you have to register two applications in your Azure Active Directory

  • Your UI (Angular)
  • Your API (ASP.NET Core 2.0)

You have to allow the UI to access the API on behalf of the user. Also don't forget to enable implicit flow for the UI application since it is a SPA.

For the authentication in the UI I can recommend the OpenID certified angular-oauth2-oidc NPM module from Manfred Steyer. The package has a cool feature where you don't need to manually add the bearer token to each request against the API. You can instead specify the URLs that needs the access token within the configuration:

OAuthModule.forRoot({
    resourceServer: {
        allowedUrls: ['http://YourApi.com/'],
        sendAccessToken: true
    }
})

Upvotes: 1

Related Questions