top of page
Search

Token based Azure AD Authentication using Angular 7 and .Net Core Web API

In today’s world, every Web API application uses token based authentication and authorization to implement security in API layer. The API service prevents anonymous access to its resources from any device (Browser, Mobile, Tablet etc.) by enabling token based authentication and authorization using cloud based Azure AD Services. The token generated by AD Service always uses JWT as default token which is encrypted and cannot be tempered by hacker during the http request and response call. The JWT token contains claims to identify user's details with token expiry date time and tenant id. In this example, we are going to use Angular 7 as front-end client application and .Net Core Web API as back-end REST Service. In Azure AD we will register two Apps one for Angular and another for API application to allow Angular application to implicitly access Web API resources or endpoints without prompting user every time for AD authentication.

The authentication and authorization implementation has been divided into 4 categories as below:-

1. Angular Application AD implementation and settings

2. .Net Core REST API AD implementation and settings

3. Angular Azure app registration input settings

4. .Net Core REST API Azure app registration input settings

1. Angular Application AD implementation and settings

1. App.module.ts:- Edit the MsAdalAngular6Module.forRoot code inside imports property of @NgModule as below:-

MsAdalAngular6Module.forRoot({

tenant: '372ee9e0-9ce0-4033-a64a-c07073a91ecd',

clientId: 'e9906b20-2ced-4bf9-9efd-6256b42d00bb',

redirectUri: window.location.origin,

authority: 'https://login.microsoftonline.com/372ee9e0-9ce0-4033-a64a-c07073a91ecd/oauth2/authorize',

endpoints: {

'https://Meraar.onmicrosoft.com/APiApplication': 'bff75af7-b065-425c-a2fe-2117713debb9',

'https://graph.microsoft.com': 'https://graph.microsoft.com'

},

navigateToLoginRequestUrl: false,

cacheLocation: 'localStorage'

}),

Note: a. In this example clientid belongs to the Angular WebApplication App registered in AD and Endpoints contains the url name (https://Meraar.onmicrosoft.com/APiApplication) and clientId (bff75af7-b065-425c-a2fe-2117713debb9) of Web API app registered in azure AD. In this example backend registered app name is APIApplication and frontend app name is WebApplication.

b. The endpoints exact url name (https://Meraar.onmicrosoft.com/APiApplication) should be used in authentication. service.cs to get the valid access token from AD. The token will not get generated if wrong url is mentioned.

2. authentication.service.ts:- Add a method by name getAccessToken to get the access token for authorization with API.

getAccessToken()

{

var accessToken:string;

if (this.adalSvc.isAuthenticated)

{

// Will take care of id_token, access_token and refresh_token

var tokenresult = this.adalSvc.acquireToken('https://Meraar.onmicrosoft.com/APIApplication');

tokenresult.subscribe(token => {

// Get the access token here

accessToken = token;

console.log(accessToken);

},

err => {

console.log(err);

}

);

}

return accessToken;

}

3. test-api.service.ts:- For testing the web API authorization, have added a test service and method by name getEmployeeName for reference to get Employee Name object from REST web API. This method first acquires the access token from Azure AD and then call the Web API endpoint by passing bearer token through httpheader.

getEmployeeName(empid: string): Observable<HttpResponse<any>>

{

// Step 1 Get the token from AuthService

var accessToken = this.authService.getAccessToken();

// Step 2 Call Web API with token to access API method

var token = 'Bearer ' + accessToken;

let httpHeaders = new HttpHeaders({

'Authorization': token,

'Content-Type' : 'application/json'

});

return this.httpclient.get(apiurl, {headers:httpHeaders, observe: 'response', responseType:'text'});

}

4. welcome.component.ts:- Add below sample code in the constructor to call web api service to get Employee Name object:-

// Call Angular API service to get all name of employee

this.testapiService.getEmployeeName(“100”)

.subscribe(resp => {

this.typedata = resp.body;

console.log(this.typedata);

},

err => {

console.log(err);

}

);

5. welcome.component.html:- Add the below sample code to view the output of Employee name:-

h1 align="center">

<p>Welcome {{user}} into Employee Management Portal!</p>

<p>Employee name</p>

<p>{{empname}}</p>

</h1>

2. Web API REST Project Implementation and settings

1. Startup.cs:- To enable JWT access token support add the below code In ConfigureServices method:-

services.AddAuthentication(sharedOptions =>

{

sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;

sharedOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;

sharedOptions.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

})

.AddJwtBearer(x =>

{

x.RequireHttpsMetadata = false;

x.SaveToken = true;

x.TokenValidationParameters = new TokenValidationParameters

{

ValidateIssuer = true,

ValidIssuer = Configuration.GetSection("AzureAd:TenantId").Value,

ValidateAudience = true,

ValidAudience = Configuration.GetSection("AzureAd:clientId").Value, // API client id

};

x.Audience = Configuration.GetSection("AzureAd:clientId").Value; // API client id

x.Authority = "https://sts.windows.net/" + Configuration.GetSection("AzureAd:TenantId").Value; // With Tenant id

});

Note: In web API project appsettings.json file, kindly update the valid client id and tenant id of the app registered in azure AD. (In this example azure app name used is APIApplication)

3. Angular Azure App Registration input settings

1. Branding:- Home page URL should be a valid angular application url e.g. http://localhost:4200/

2. Authentication:- Redirect URL must be a valid angular application url e.g. http://localhost:4200/. If Redirect url is mentioned wrong than AD authentication response will display authentication error message while loading the home page.

3. API permissions:- Add a new permission to use Angular Web app by requesting for the implicit grant permissions. In this, API app will grant permissions to Web App during the consent process where users are given the opportunity to grant/deny access.

4. Menifest:- Edit and save oauth2AllowIdTokenImplicitFlow=true and oauth2AllowImplicitFlow=true to allow implicit authentication between both registered apps.

4. Web API Azure App Registration input settings

1. Branding:- Home page URL should be a valid api application url e.g. http://localhost:44363/

2. Authentication:- Redirect URL must be a valid api application url e.g. https://localhost:44363/signin-oidc. If Redirect url is mentioned wrong than JWT access token will not generated by Web API.

3. API permissions:- Permission should be granted to access to Azure Active Directory Graph API resources e.g. Directory Read All and User.Read etc.

Menifest:- Edit and save oauth2AllowIdTokenImplicitFlow=true and oauth2AllowImplicitFlow=true to allow implicit authentication between both registered apps.

0 views0 comments

Kommentare


bottom of page