Angular JS Token-based Authentication using Asp.net Identity and Asp.net web API

ASP.NET 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 your own providers.

In this tutorial, we will  build a Token-based Authentication using ASP.net identity ,ASP.net web API and AngularJS at front end

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 angularjs and asp.net and REST services

2

Securing our web application consists of two scenarios  Authentication and Authorisation

  1. Authentication

Authentication identifies the user. so the user must be registered before, using login and password or third party logins like Facebook, Twitter,
2.  Authorisation  talks about  Permission for authenticated users
– what is the user (authenticated) allowed to do ?
– What ressources can the user access ?

We will build our Back End service using ASP.NET WEB API, 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

BUILDING WEB API RESSOURCE SERVER AND AUTHORIZATION SERVER

  1.   CONFIGURE OAUTH AUTHORIZATION SERVER OPTIONS
  • Create an asp.net web api projet, and choose individual user accounts for authentication type
  • Expand App_Start folder and open file Startup.Auth.cs

4

  • TokenEndpointPath = new PathString(“/Token”),  mean that to get authenticated, clients muste call   url {domain}/TOKEN ( for example   http://localhost:9456/TOKEN)
  • AuthorizeEndpointPath = new PathString(“/api/Account/ExternalLogin”) is for external logins like facebook or twitter
  • AllowInsecureHttp = true : I will talk about https later in this tutorial
  • app.UseOAuthBearerTokens(OAuthOptions);   Enable the application to use bearer tokens to authenticate users

2.  CONFIGURE BEARER TOKEN ATHENTICATION

  • Expand App_Start folder and open file WebApiConfig.cs

5

  • config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

Allow us to use only bearer token

3.  BUILD RESSOURCE SERVER

Know lets create a get  product api method so as to retrieves some products (http://localhost:9456/api/Products)

13

BUILDING   ANGULARJS WEB CLIENT

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

14

  • app.js  

15

  • Common.services.js

16

  • UserProfile

  • LoginService

18

  • LoginController

19

20

21

  • ProductService

22

  • ProductController

23

  • Index.html

24

25

26

27

28

TESTING 

6

 

untitled6

 

7

 

8

 

9

 

10

 

10

11

 

 

12

Source Code is available here : https://github.com/logcorner/Angular-JS-Token-based-Authentication-using-Asp.net-Identity-and-Asp.net-web-API

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

  • Gerson

    Thank you for sharing your skills!

    • Sharlin

      Hello Gora,

      Thank you for your useful article.
      Could you please share source code for practicing? I hope it will help many developer.

    • tanujkhurana

      please provide source code ASAP.

  • tanujkhurana

    Superb Article..thanks for sharing these kind of valuable article

  • Nguyễn Hồ Hải Phước

    Could you please show the source code or at least the code of isLoggedIn() function ?

    • currentUser.js ==>
      (function () {
      “use strict”;

      angular
      .module(“common.services”)
      .factory(“currentUser”,
      currentUser)

      function currentUser() {
      var profile = {
      isLoggedIn: false,
      username: “”,
      token: “”
      };

      var setProfile = function (username, token) {
      profile.username = username;
      profile.token = token;
      profile.isLoggedIn = true;
      };

      var getProfile = function () {
      return profile;
      }

      return {
      setProfile: setProfile,
      getProfile: getProfile
      }
      }
      })();

      userAccount.js ==>

      (function () {
      “use strict”;

      angular
      .module(“common.services”)
      .factory(“userAccount”,
      [“$resource”,
      “appSettings”,
      userAccount])

      function userAccount($resource, appSettings) {
      return {
      registration: $resource(appSettings.serverPath + “/api/Account/Register”, null,
      {
      ‘registerUser’: { method: ‘POST’ }
      }),
      login: $resource(appSettings.serverPath + “/Token”, null,
      {
      ‘loginUser’: {
      method: ‘POST’,
      headers: { ‘Content-Type’: ‘application/x-www-form-urlencoded’ },
      transformRequest: function (data, headersGetter) {
      var str = [];
      for (var d in data)
      str.push(encodeURIComponent(d) + “=” +
      encodeURIComponent(data[d]));
      return str.join(“&”);
      }

      }
      })
      }
      }
      })();

      UserCtrl.js ==>
      (function () {
      “use strict”;

      angular
      .module(“userManagement”)
      .controller(“userCtrl”,
      [“userAccount”,
      “currentUser”,
      userCtrl]);

      function userCtrl(userAccount, currentUser) {
      var vm = this;
      vm.isLoggedIn = function () {
      return currentUser.getProfile().isLoggedIn;
      };
      vm.message = ”;
      vm.userData = {
      userName: ”,
      email: ”,
      password: ”,
      confirmPassword: ”
      };

      vm.registerUser = function () {
      vm.userData.confirmPassword = vm.userData.password;

      userAccount.registration.registerUser(vm.userData,
      function (data) {
      vm.confirmPassword = “”;
      vm.message = “… Registration successful”;
      vm.login();
      },
      function (response) {
      vm.isLoggedIn = false;
      vm.message = response.statusText + “rn”;
      if (response.data.exceptionMessage)
      vm.message += response.data.exceptionMessage;

      // Validation errors
      if (response.data.modelState) {
      for (var key in response.data.modelState) {
      vm.message += response.data.modelState[key] + “rn”;
      }
      }
      });
      }

      vm.login = function () {
      vm.userData.grant_type = “password”;
      vm.userData.userName = vm.userData.email;

      userAccount.login.loginUser(vm.userData,
      function (data) {
      vm.message = “”;
      vm.password = “”;
      currentUser.setProfile(vm.userData.userName, data.access_token);
      },
      function (response) {
      vm.password = “”;
      vm.message = response.statusText + “rn”;
      if (response.data.exceptionMessage)
      vm.message += response.data.exceptionMessage;

      if (response.data.error) {
      vm.message += response.data.error;
      }
      });
      }
      }
      })();

      • Nguyễn Hồ Hải Phước

        1. I think this piece of code is similar to the code in userProfile.js.
        2. I just want to know the code of this line https://uploads.disquscdn.com/images/9e16022ad53f6677da80dca3adcddac5b16081a0016b0c6c84a4e652b7bb9b15.png because I see it is wrapped.
        3. When I want to check whether it has already been logged in, do I need to check whether the token is expired or not or just check whether it is stored in session storage or not ?

        • I will publish the entire code next week

          var vm = this;
          vm.isLoggedIn = function () {
          return currentUser.getProfile().isLoggedIn;
          };
          regards

          • Walter Lockhart

            Excellent Gora. Looking forward to it.

  • Walter Lockhart

    Hi Gora LEYE,

    Would you please publish the source code to your excellent article:

    Angular JS Token-based Authentication using Asp.net Identity and Asp.net web API
    http://logcorner.com/angular-js-token-based-authentication-using-asp-net-identity-and-asp-net-web-api/

    Thank you for all your hard work.

    Kind Regards

    Walter

  • @@walterlockhart:disqus , @ng@nguynhhiphc:disqus
    Hi have updated it and publish here : https://github.com/logcorner/Angular-JS-Token-based-Authentication-using-Asp.net-Identity-and-Asp.net-web-API

    JWT Token Server , angular2client and angularJsClient
    Let me know
    regards

    • Walter Lockhart

      Thank you so much Gora.