Angular JS Token Based Authentication using Asp.net Core Web API 2.0 and JSON Web Token

ASP.NET Core Identity is designed to enable us to easily use a number of different storage providers for our ASP.NET applications. We can use the supplied identity providers that are included with the .NET Framework, or we can implement our own providers.

In this tutorial, we will  build a Token-Based Authentication using ASP.NET Core Identity , ASP.NET Core Web API and Angular JS

With Token-Based Authentication, the client application is not dependent on a specific authentication mechanism. The token is generated by the server and the Web API have some APIs to understand, validate the token and perform the authentication. This approach provides Loose Coupling between client and the Web API.

this toturial is not for beginners, to follow it, you must understand Angular2 and Asp.NET REST Services

2

Securing our web application consists of two scenarios  :  Authentication and Authorization

1.   Authentication identifies the user. So the user must be registered first, using login and password or third party logins like Facebook, Twitter, etc…
     2.  Authorization  talks about  permission for authenticated users
– What is the user (authenticated) allowed to do ?
– What ressources can the user access ?

We have build our back end service using ASP.NET WEB API Core, web api provides an internal authorization server using OWIN MIDDLEWARE

The authorization server and the authentication filter are both called into an OWIN middleware component that handles  OAuth2
3

This article is the third part of a series of 4 articles

  1. Token Based Authentication using Asp.net Core Web Api
  2. Asp.Net Core Web Api Integration testing using EntityFrameworkCore LocalDb and XUnit2
  3. Angular Token Based Authentication using Asp.net Core Web API and JSON Web Token
  4. Angular JS Token based Authentication using Asp.net Core Web API and JSON Web Token

BUILDING WEB API RESSOURCE SERVER AND AUTHORIZATION SERVER

In the first part Token Based Authentication using Asp.net Core Web API,  I talked about how to configure an ASP.NET Web API  Core Token Based Authentication using JWT.  So in this tutorial I will talk about an Angular2 client that connect to the  Web Api Authorization server using a JWT Token

BUILDING ANGULAR2 WEB CLIENT

Create an ASP.NET Empty WebSite  and structure it as follow

Package.config

Package.config defines some dependencies , so use nuget package manager  to restore them

nuget

index.html

lets include  *.css files on header section

lets include  *.js files at the end of body  section

Index.html is the entry point of our SPA application, Use the directive ng-app to auto-bootstrap our AngularJS application.

We can specify an AngularJS module to be used as the root module for the application. This module will be loaded into the $injector when the application is bootstrapped. It should contain the application code needed or have dependencies on other modules that will contain the code.   

Our root angular module is appmodule,  we specify it in index.html by  <body ng-app=”appmodule”…….

app.js

In app.js file  we inject common.services as a dependency

common.service.js

Lets create a common.service.js file

Here, we implement common functionalities such as error handling, serverPath to call API, (http://localhost:58834/api is the API endpoint)

userCtrl.js

In userCtrl.js file Ininject login.services and userProfile as a dependencies: userProfile to store user data and login.service to call api

I define some functions :

  • vm.isLoggedIn :  to verify if the user is logged in  :  sessionStorage.getItem(‘accessToken’) != null
  • vm.registerUser : register a new user. it uses loginservice.register
  • vm.login : log in user. it uses loginservice.login
  • vm.logout : logout user. it uses userProfile to clear  user data

in index.html view I reference  userCtrl as  ng-controller=”userCtrl as vm”

So if user is loggedIn I display  userLoginView

else I display  productListView

userLoginView.html

UserLoginView  defines the login form and the register form and uses userCtrl :

  • ng-click=”vm.registerUser()”  handles  registerUser function of userCtrl.
  • ng-click=”vm.login()”  handles  login function of userCtrl.

 

loginService.js

  • register function :  register a new to database
  • login function : log an existing user and returns a valid token

userProfile.js

userProfile : after succesfull login , store user informations like userName, token and claims to sessionStorage. 

If the user logout, I clear  user informations  from session

ProductListCtrl.js

productService.js

To get products, user must be logged in first, so user must retrive a token, and send the token with the getProduct request

var authHeaders = userProfile.getAuthHeaders();

var response = $http({
url: appSettings.serverPath + “/api/product”,
method: “GET”,
headers: authHeaders
});

productListView.html

SEE IT IN ACTION

Open Package Manager Console and run update-database command to generate database

This is the generated database on localdb

Configure Startup multiple project : TokenAuthWebApiCore.Server and AngularJSClient

Run F5

 

Soure code is available here  https://github.com/logcorner/Angular-JS-Token-Based-Authentication-using-Asp.net-Core-Web-API-2.0-and-JSON-Web-Token

Gora LEYE

I'm a microsoft most valuable professional (MVP) .NET Architect and Technical Expert skills located in Paris (FRANCE). The purpose of this blog is mainly to post general .NET tips and tricks, www.masterconduite.com Gora LEYE