Passing JSON Web Tokens to Web API

Part I of this post talked about authenticating a user in an Angular Single Page Application and fetching the id_token. The app still needs to be integrated with the Web API. The following changes are required in order to make the Web API accept and use the JSON Web Token.

The Angular Single Page Application needs to be granted permission to access the Web API in Azure AD. Check the Configure a client application to access web APIs section of the Integrating applications with Azure Active Directory article for further details.

Startup.cs changes

Add the below lines of code to the corresponding methods in the Startup class.
ConfigureServices

services.AddAuthentication(options =>
{
	options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
	options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
	options.Audience = Configuration["AuthSettings:Audience"];
	options.Authority = Configuration["AuthSettings:Authority"];
});

Configure

app.UseAuthentication();

Make sure the above line comes before app.UseMvc();.

Controller

Decorate the API controller class with the Authorize attribute.

Application Settings

Add the below settings to the appsettings.json file. Audience is the client_id of the SPA.

"AuthSettings": {
    "Authority": "https://login.microsoftonline.com/<tenantid>.onmicrosoft.com",
    "Audience": "<Web app client_id>"
  }

Reading the Claim

The token contains claims and they can be used to authorize the user. I’m using the Email from the Claims to uniquely identity a user.

private string GetEmailIdFromClaims()
{
	var identity = User.Identity as ClaimsIdentity;
	if (identity != null)
		return identity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
	else
		return String.Empty;
}

Passing JWT token to Web API

The token needs to be passed in the Authorization header when a call to the Web API is made.

constructor(private http: Http,
private configurationService: ConfigurationService,
private authService: AuthService) {

let headers = new Headers();
headers.append('Authorization', `Bearer ${this.authService.getToken()}`);
let options = new RequestOptions({ headers: headers });

http.get(this.configurationService.serverSettings.serviceDeskAPIUrl + 'api/Tickets', options)
	.subscribe(result => {
	this.tickets = result.json() as Ticket[];
}, error => console.error(error));
}

Now the SPA and the Web API are setup to send and receive JWT tokens. Invoking a REST Http method will pass the token in the Authorization header. The Web API will validate the token and return the requested resource.

References

  • Authentication Scenarios for Azure AD
  • Azure-Samples/active-directory-angularjs-singlepageapp
  • Creating an Angular Single Page Application with Azure Active Directory and adal.js that uses an ASP.NET WebAPI
  • Using ADAL with Angular2
  • Leave a comment