Bit of Technology

  • Archive
  • About Me
    • Advertise
    • Disclaimer
  • Speaking
  • Contact

AngularJS Authentication Using Azure Active Directory Authentication Library (ADAL)

December 2, 2014 By Taiseer Joudeh 54 Comments

Be Sociable, Share!

  • Tweet
  • Email
  • WhatsApp

In my previous post Secure ASP.NET Web API 2 using Azure Active Directory I’ve covered how to protect Web API end points using bearer tokens issued by Azure Active Directory, and how to build a desktop application which acts as a Client. This Client gets the access token from the Authorization Server (Azure Active Directory) then use this bearer access token to call a protected resource exits in our Resource Server (ASP.NET Web API).

Azure Active Directory Web Api

Initially I was looking to build the client application by using AngularJS (SPA) but I failed to do so because at the time of writing the previous post Azure Active Directory Authentication Library (ADAL) didn’t support OAuth 2.0 Implicit Grant which is the right OAuth grant that should be used when building applications running in browsers.

The live AngularJS demo application is hosted on Azure (User: ADAL@taiseerjoudeharamex.onmicrosoft.com/ Pass: AngularJS!!), the source code for this tutorial on GitHub.

So I had discussion with Vittorio Bertocci and Attila Hajdrik on twitter about this limitation in ADAL and Vittorio promised that this feature is coming soon, and yes ADAL now supports OAuth 2.0 Implicit Grant and integrating it with your AngularJS is very simple, I recommend you to watch Vittorio video introduction on Channel 9 before digging into this tutorial.

@attilah Azure AD does not support the implicit flow (yet) hence using it from JavaScript means doing hacks. Stay tuned tho!

— Vittorio (@vibronet) April 9, 2014

AngularJS Authentication Using Azure Active Directory Authentication Library (ADAL)

What is OAuth 2.0 Implicit Grant?

In simple words the implicit grant is optimized for public clients (can not store secrets) and those clients are built using JavaScript and they run in browsers. There is no client authentication happening here and the only factors should be presented to obtain an access token is the resource owner credentials and pre-registration for the redirection URI with the Authorization server. This redirect URI will be used to receive the access token issued by the Authorization server in a form of URI fragment.

What we’ll build in this tutorial?

In this tutorial we’ll build simple SPA application using AngularJS along with ADAL for JS which provides a very comprehensive abstraction for the Implicit Grant we described earlier. This SPA will communicate with a protected Resource Server (Web API) to get list of orders, and will request the access token from our Authorization Server (Azure Active Directory).

In order to follow along with this tutorial I’ve created a sample skeleton project which contains the basic code needed to run our AngularJS application and the Web API without adding any feature related to the security. So I recommend you to download it first so you can follow along with the steps below.

The NuGet packages I used in this project are:

1
2
3
4
Install-Package Microsoft.AspNet.WebApi -Version 5.2.2
Install-Package Microsoft.AspNet.WebApi.Owin -Version 5.2.2
Install-Package Microsoft.Owin.Host.SystemWeb -Version 3.0.0
Install-Package Microsoft.Owin.Security.ActiveDirectory -Version 3.0.0

Step 1: Register the Web API into Azure Active Directory

Open Azure Management Portal in order to register our Web API as an application in our Azure Active Directory, to do so and after your successful login to Azure Management Portal, click on “Active Directory” in the left hand navigation menu, choose your active directory tenant you want to register your Web API with, then select the “Applications” tab, then click on the add icon at bottom of the page. Once the modal window shows as the image below select “Add an application my organization is developing”.
Azure New App
Then a wizard of 2 steps will show up asking you to select the type of the app you want to add, in our case we are currently adding a Web API so select “Web Application and/or Web API”, then provide a name for the application, in my case I’ll call it “AngularJSAuthADAL”, then click next.
Azure App Name
In the second step as the image below we need to fill two things, the Sign-On URL which is usually will be your base URL for your Web API, so in my case it will be “http://localhost:10966”, and the second field APP ID URI will usually be filled with a URI that Azure AD can use for this app, it usually take the form of “http://<your_AD_tenant_name>/<your_app_friendly_name>” so we will replace this with the correct values for my app and will be filed as “http://taiseerjoudeharamex.onmicrosoft.com/AngularJSAuthADAL” then click OK.

Azure App Properties

Step 2: Enable Implicit Grant for the Application

After our Web API has been added to Azure Active Directory apps, we need enable the implicit grant. To do so we need to change our Web API configuring using the application manifest. Basically the application manifest is a JSON file that represents our application identity configuration.

So as the image below and after you navigate to the app we’ve added click on “Manage Manifest” icon at the bottom of the page, then click on “Download Manifest”.

Download Manifest

Open the downloaded JSON application manifest file and change the value of “oauth2AllowImplicitFlow” node to “true“.  As well notice how the “replyUrls” array contains the URL which we want the token response returned to. You can read more about Web API configuration here.

After we apply this change, save the application manifest file locally then upload it again to your app using the “Upload Manifest” feature.

Step 3: Configure Web API to Accept Bearer Tokens Issued by Azure AD

Now and if you have downloaded the skeleton project right click on it and click on build to download the needed Nuget packages, if you want you can run the application and a nice SPA will be show up and the orders will be displayed as the image below because we didn’t configure the security part yet.

AngularJS Adal

Now open file “Startup.cs” and paste the code below:

1
2
3
4
5
6
7
8
9
        public void ConfigureOAuth(IAppBuilder app)
        {
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
               new WindowsAzureActiveDirectoryBearerAuthenticationOptions
               {
                   Audience = ConfigurationManager.AppSettings["ida:ClientID"],
                   Tenant = ConfigurationManager.AppSettings["ida:Tenant"]
               });
        }

Basically what we’ve implemented here is simple, we’ve configured the Web API authentication middleware to use “Windows Azure Active Directory Bearer Tokens” for the specified Active Directory “Tenant” and “Audience” (Client Id). Now any API controller lives in this API and attribute with [Authorize] attribute will only accept bearer tokens issued from this specified Active Directory Tenant, any other form of tokens will be rejected.

It is a good practice to store the values for your Audience, Tenant, Secrets, etc… in a configuration file and not to hard-code them, so open the web.config file and add 2 new “appSettings” as the snippet below, the value for the Client Id can be read your Azure App settings.

1
2
3
4
  <appSettings>
    <add key="ida:Tenant" value="taiseerjoudeharamex.onmicrosoft.com" />
    <add key="ida:ClientID" value="1725911b-ad8f-4295-8258-cf95ba9f7ea6" />
  </appSettings>

Step 4: Protect Orders Controller

Now open file “OrdersController” and attribute it with [Authorize] attribute, by doing this any GET request to the path “http://localhost:port/api/orders” will return status code 401 if no token provided in the Authorization header. When you apply this the orders view won’t return any data until we obtain a valid token. Orders controller code will look as the below snippet:

1
2
3
4
5
6
[Authorize]
[RoutePrefix("api/orders")]
public class OrdersController : ApiController
{
//Rest of code is here
}

Step 5: Download ADAL JavaScript Library

Now it is time to download and use ADAL JS library which will facilitates the AngularJS authentication using the Implicit grant, so after you download the file, open page “Index.html” and add reference to it at the end of the file as the code below:

1
2
3
<!-- 3rd party libraries -->
<!Other JS references here -->
<script src="scripts/adal.js"></script>

Step 6: Configure our AngularJS bootstrap file (app.js)

Now open file “app.js” where we’ll inject the ADAL dependencies into our AngularJS module “AngularAuthApp”, so after you open the file change the code in it as the below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
var app = angular.module('AngularAuthApp', ['ngRoute', 'AdalAngular']);
 
app.config(['$routeProvider', '$httpProvider', 'adalAuthenticationServiceProvider', function ($routeProvider, $httpProvider, adalAuthenticationServiceProvider) {
 
    $routeProvider.when("/home", {
        controller: "homeController",
        templateUrl: "/app/views/home.html"
    });
 
    $routeProvider.when("/orders", {
        controller: "ordersController",
        templateUrl: "/app/views/orders.html",
        requireADLogin: true
    });
 
    $routeProvider.when("/userclaims", {
        templateUrl: "/app/views/userclaims.html",
        requireADLogin: true
    });
 
    $routeProvider.otherwise({ redirectTo: "/home" });
 
    adalAuthenticationServiceProvider.init(
      {
          tenant: 'taiseerjoudeharamex.onmicrosoft.com',
          clientId: '1725911b-ad8f-4295-8258-cf95ba9f7ea6'
      }, $httpProvider);
 
}]);
var serviceBase = 'http://localhost:10966/';
app.constant('ngAuthSettings', {
    apiServiceBaseUri: serviceBase
});

What we’ve implemented is the below:

  • We’ve injected the “AdalAngular” to our module “AngularAuthApp”.
  • The service “adalAuthenticationServiceProvider” is now available and injected into our App configuration.
  • We’ve set the property “requireADLogin” to “true” for any partial view requires authentication, by doing this if the user requested a protected view, a redirection to Azure AD tenant will take place and the user (resource owner) will be able to enter his AD credentials to authenticate.
  • Lastly, we’ve set the “tenant” and “clientId” values related to our AD Application.

Step 7: Add explicit Login and Logout feature to the SPA

The ADAL Js library provide us with explicit way to login/logout the user by calling “login” function, so to add this open file named “indexController.js” and replace the code existing with the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
'use strict';
app.controller('indexController', ['$scope', 'adalAuthenticationService', '$location', function ($scope, adalAuthenticationService, $location) {
 
    $scope.logOut = function () {
      
        adalAuthenticationService.logOut();
    }
 
    $scope.LogIn = function () {
 
        adalAuthenticationService.login();
    }
 
}]);

Step 8: Hide/Show links based on Authentication Status

For better user experience it will be nice if we hide the login link from the top menu when the user is already logged in, and to hide the logout link when the user is not logged in yet, to do so open file “index.html” and replace the menu items with code snippet below:

1
2
3
4
5
6
7
8
            <div class="collapse navbar-collapse" data-collapse="!navbarExpanded">
                <ul class="nav navbar-nav navbar-right">
                    <li data-ng-hide="!userInfo.isAuthenticated"><a href="#">Welcome {{userInfo.profile.given_name}}</a></li>
                    <li><a href="#/orders">View Orders</a></li>
                    <li data-ng-hide="!userInfo.isAuthenticated"><a href="" data-ng-click="logOut()">Logout</a></li>
                    <li data-ng-hide="userInfo.isAuthenticated"><a href="" data-ng-click="LogIn()">Login</a></li>
                </ul>
            </div>

Notice that we are depending on object named “userInfo” to read property named “isAuthenticated”, this object is set in the “$rootScope” in ADAL JS library so it is available globally in our AngularJS app.

By completing this step and if we tried to run the application and request the view “orders” or click on “login” link, we will be redirected to our Azure AD tenant to enter user credentials and have an access to the protected view, there is lot of abstraction happening here that needs to be clarified in the section below.

ADAL JavaScrip Flow

  • Once the anonymous user request protected view (view marked with requireADLogin = true ) or hit on login link explicitly, ADAL will trigger login directly as the code highlighted here.
  • The Login in ADAL library means building redirection URI to the configured Azure AD tenant we’ve defined in the “init” method in “app.js” file, the URI will contain random “state” and “nonce” to uniquely identify each request and prevent from any reply requests, as well the value for the “redirect_uri” is set the to current location of the page which should match the value we’ve defined once we registered the application, lastly the “response_type” is set to “id_token” so the authorization server should send back a JWT token contains claims about the user. The redirection URI will look as the below and code for building the redirection URI is highlighted here: 

1
https://login.windows.net/taiseerjoudeharamex.onmicrosoft.com/oauth2/authorize?response_type=id_token&client_id=1725911b-ad8f-4295-8258-cf95ba9f7ea6&redirect_uri=http%3A%2F%2Fngadal.azurewebsites.net%2F&state=9cce69d3-af36-4eb4-a882-4e9b7080e90d&x-client-SKU=Js&x-client-Ver=0.0.3&nonce=d4313f89-dc4f-4590-b7fd-9bbc2b340759

  • Now the Azure AD login page will show up for the user, then the user will be prompted to enter his AD credentials as the image blow, assuming he entered credentials correctly, a redirection will take place to the following URI containing the token as part of URI fragment not query string along with the same state and nonce specified by ADAL earlier.

1
https://ngadal.azurewebsites.net/#/id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImtyaU1QZG1Cdng2OHNrVDgtbVBBQjNCc2VlQSJ9.eyJhdWQiOiIxNzI1OTExYi1hZDhmLTQyOTUtODI1OC1jZjk1YmE5ZjdlYTYiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC8wODExZmIzMS05M2VkLTRmZWItYTAwOS1kNmUyN2RmYWMxN2IvIiwiaWF0IjoxNDE3NDgwMjc5LCJuYmYiOjE0MTc0ODAyNzksImV4cCI6MTQxNzQ4NDE3OSwidmVyIjoiMS4wIiwidGlkIjoiMDgxMWZiMzEtOTNlZC00ZmViLWEwMDktZDZlMjdkZmFjMTdiIiwiYW1yIjpbInB3ZCJdLCJvaWQiOiI2OTIyYTVlZi01YmMyLTRiYmEtYjI5Yy1kODc0YzQyYjg1OWQiLCJ1cG4iOiJIYW16YUB0YWlzZWVyam91ZGVoYXJhbWV4Lm9ubWljcm9zb2Z0LmNvbSIsInVuaXF1ZV9uYW1lIjoiSGFtemFAdGFpc2VlcmpvdWRlaGFyYW1leC5vbm1pY3Jvc29mdC5jb20iLCJzdWIiOiJxVWU4UUQ4SzdwOF9zTlI5WlhQYWcyOVFCeGZURlhKbTBaVzR0UDdYSEJNIiwiZmFtaWx5X25hbWUiOiJKb3VkZWgiLCJnaXZlbl9uYW1lIjoiSGFtemEiLCJub25jZSI6ImQ1NmEwNDJhLWQzM2YtNGYxYS05ZmYwLTFjMWE1ZDk3YzVmMSIsInB3ZF9leHAiOiI3NDMzNDg5IiwicHdkX3VybCI6Imh0dHBzOi8vcG9ydGFsLm1pY3Jvc29mdG9ubGluZS5jb20vQ2hhbmdlUGFzc3dvcmQuYXNweCJ9.efAp-95yMvhLu--8TfXYwozJsc09OTsB5bneH9bvGzko6uLZj0YloDTIrVtu_SU95hOBpFvma0FOeGmsqre6DBwaLTSJDD9wTYtqmoCGwpTy_cewpS78MJ9aR-IjWx5O6K8Nt90d4ujaco5T-o2EQ4ygPx5Z6vH-sLy8t9NDVER7HtlClhRwj2uDUF-kdihh7lv5w0U7TqHZUtLkBNL2l69yY5F0Jdj0q7m81gNps6nfqfa8aypgmztpPWDJAChvwsD5r58CyGVXPKSp_2CfK0kkWasP6fmLKKi5tGPvjg-wEb2j47UVIgO8v9xIkqg8RGqnZ1lboZKa2FlCs-Jnrw&state=6ac680d1-8b3b-452a-97d2-3deddb4016fc&session_state=2d48f965-e026-4c08-9d38-2cce49ee72cb

Azure AD Login

Note: You can extract the JSON Web token manually and debug it using JWT debugging tool to explore the claims inside it.

  • Now once ADAL JS library receives this call back, it will go and extract the token from the hash fragment, try to decode this token to get user profile and other claims from it (i.e. token expiry), then store the token along with decoded claims in HTML 5 local storage so the token will not vanish if you closed the browser or do full refresh (F5) for your AngularJS application, the implementation is very similar to what we’ve covered earlier in AngularJS authentication post.
  • To be able to access the protected API end points, we need to send the token in the “Authorization” header using bearer scheme, the ADAL JS provides an AngularJS interceptor which is responsible to add the Authorization header to each XHR request if there is token stored in the localStorage, these is very similar to the interceptor we’ve added before in our AngularJS Authentication post.
  • If the user decided to “logout” from the system, then ADAL JS clears all the stored data in the HTML 5 local storage, so no token stored locally, then it issue redirect to the URI: https://login.windows.net/{tenantid}/oauth2/logout which will be responsible to clear the clear any session cookies created by Azure AD tenant, but remember that logging out from the system will not invalidate your token, if you extracted the token manually then it will remain valid until it expires, usually after 1 hour of the issuing time.
  • ADAL JS provides a nice way to renew the token without using grant_type = refresh_token, it tries to renew the token silently by using a hidden iframe which communicates with Azure AD tenant asking for a new token if there is a valid session established by the AD tenant.

The live AngularJS demo application is hosted on Azure (ADAL@taiseerjoudeharamex.onmicrosoft.com/AngularJS!!), the source code for this tutorial on GitHub.

Conclusion

ADAL JS library really simplifies adding OAuth 2.0 Implicit grant to your SPA, it is still on developer preview release so testing it out and providing feedback will be great to enhance it.

If you have any comments or enhancement on this tutorial please drop me comment. Thanks for taking the time to read the post!

Follow me on Twitter @tjoudeh

References

  • ADAL JavaScript and AngularJS – Deep Dive by Vittorio Bertocci.
  • Azure Active Directory Library for JS.
  • Azure Active Directory Samples – Single Page Application.

Be Sociable, Share!

  • Tweet
  • Email
  • WhatsApp

Related Posts

  • Integrate Azure AD B2C with ASP.NET MVC Web App – Part 3
  • Secure ASP.NET Web API 2 using Azure AD B2C – Part 2
  • Azure Active Directory B2C Overview and Policies Management – Part 1
  • ASP.NET Web API Claims Authorization with ASP.NET Identity 2.1 – Part 5
  • ASP.NET Identity 2.1 Roles Based Authorization with ASP.NET Web API – Part 4

Filed Under: AngularJS, ASP.Net Web API, Azure, Owin, Web API Security, Web API Tutorial Tagged With: AngularJS, API, OAuth, Tutorial, Web API, Web API Security

Comments

  1. Binjie Zhao says

    January 9, 2015 at 7:54 pm

    Hi

    I wonder if you have got an example to show how an Angular SPA access a CORS enabled web api by adal.js? I’ve read your blog and Vittorio’s blog, the sample you both blogged about are very similar, only deal with SPA access it’s own API service. I need a sample to show how SPA access other API service through adal.js.

    Thanks.

    Reply
    • Taiseer Joudeh says

      January 11, 2015 at 9:25 am

      Hi Binjie,
      Well allowing CORS is something you want to do on the server (API), so for your API part you need to follow step number step 10 & 11 from this post to enable CORS and accept XHR requests from any origin.

      Reply
      • Binjie Zhao says

        January 12, 2015 at 1:29 pm

        Thanks Taiseer. I will have a read.

        Reply
      • Anurag Kansal says

        September 26, 2015 at 11:05 am

        Hi Taiseer,
        Thanks for your work! I am also trying to implement a CORS scenario. But I am facing difficulty with Step 10. It requires us to implement the ‘SimpleAuthorizationServerProvider’ which in turn uses the ‘AuthRepository’ and ‘IdentityUser’ classes which we have not implemented.

        Kindly suggest.

        Regards,
        Anurag

        Reply
  2. Hayden says

    January 16, 2015 at 10:39 pm

    HI Taiseer,

    Any idea when this will move out of preview and be an official release?

    Reply
    • Taiseer Joudeh says

      January 17, 2015 at 8:35 pm

      Hi Haydan, to be honest no, but you can drop @vibronet a message for clear details.

      Reply
  3. Dane Vinson says

    January 25, 2015 at 9:26 am

    Once again Taiseer, excellent work.

    Reply
    • Taiseer Joudeh says

      January 25, 2015 at 9:39 am

      Great it was useful Dane 🙂 Happy to help!

      Reply
  4. jonwik says

    January 30, 2015 at 12:34 pm

    Superb article!

    Can’t get this to work on IE 11 but works perfectly on Chrome. Maby a question without any an answer but any ideas about known bugs for this browser?

    Reply
    • Taiseer Joudeh says

      January 30, 2015 at 1:14 pm

      Hi Joans,
      Thanks for your comment, well IE 11 should support localstorage where you save the access token and some other data returned by Azure AD. Is there any specific error? Try to fire f12 and monitor the errors section.

      Reply
  5. Dane Vinson says

    February 6, 2015 at 2:42 am

    I have this all working great using an AAD I set up for a locally hosted application. When I was done with the initial testing phase I updated my AAD application to reference a real Azure Web Site and then created a second AAD application to use when testing locally. I updated my local web.config with the client ID of my new test AAD application and updated the clientId property in the adalAuthenticationServiceProvider call in my Angular configuration step. Now when I log in (running locally) I get an error from the AAD authentication and clearly in the error is the old clientId. I’ve performed a findstr search for that clientId value in my entire solution and it comes back empty. I tried clearing browser history/cookies as well with no luck. Any idea where the client is getting the previous clientId from?

    Reply
    • Taiseer Joudeh says

      February 6, 2015 at 11:49 pm

      You have updated the only 2 places where you store the client id, I guess there is issue with localstorage caching, can you try to run it in Chrome incognito mode?

      Reply
      • Dane Vinson says

        February 6, 2015 at 11:53 pm

        Thanks Taiseer. When I came back to it this morning it suddenly started working. Seems it may have been some sort of caching issue.

        Reply
  6. Shane Oborn says

    February 10, 2015 at 6:44 pm

    Is it possible to use the ADAL JS library to manage tokens with any authorization server that implements the implicit grant flow? Or will this library only work with Azure AD?

    Reply
    • Taiseer Joudeh says

      February 11, 2015 at 11:33 pm

      I doubt it will work but to double check you can ask @vibronet

      Reply
  7. BC says

    February 14, 2015 at 2:31 pm

    Thanks for a great post…is it possible to do AngularJS Authentication Using Azure Active Directory Authentication Library in a Multi Tenant environment? If so, could you provide details or an updated post. Thanks again

    Reply
    • Taiseer Joudeh says

      February 16, 2015 at 10:12 am

      Hi BC,
      I’m not 100% sure but I guess not, you can be sure by contacting @vibronet on twitter.

      Reply
    • Eric says

      March 7, 2017 at 10:08 pm

      @BC did you find an answer for your question? thanks

      Reply
  8. Giorgio says

    February 27, 2015 at 2:37 pm

    Is it possible to use the same library for SPA without AngularJS (I am using Durandal)?

    Reply
    • Taiseer Joudeh says

      February 28, 2015 at 12:01 pm

      Hi Giorgio,
      I believe this library is intended for AngularJS only, but you can make your own wrappers.

      Reply
  9. Huan Ho says

    April 28, 2015 at 2:09 am

    Great post Taiseer! Do you know if there’s a way to preserve a query string parameter (i.e. redirect_url) after the call back from Azure AD.

    For example:
    1) User tries to access: http://www.domain.com/#/protected_resource.
    2) Gets redirected to: http://www.domain.com/#/login?redirect_url=protected_resource
    3) User successfully logs in via Azure AD
    4) Azure AD redirects back to http://www.domain.com, but redirect_url is no lost

    I basically want to store the original url (from step 1) and redirect the user to this after he/she logs in.

    Thanks in advance!

    Reply
    • Taiseer Joudeh says

      April 29, 2015 at 6:50 pm

      Hi Huan,
      I understand the scenario but I do not have answer right now, I need to try it out, if I find something useful I will get back to you.

      Reply
      • Huan Ho says

        May 3, 2015 at 7:01 am

        Thanks, Taiseer. I’ll dig around as well and let you know if I find a solution.

        Reply
  10. Hemant says

    May 26, 2015 at 5:33 pm

    I am trying to use ui-router and breeze.js for my Angular App. I am successful in signing in into SPA but not able to forward the auth token to WebAPI. I used the requireADLogin:true in states of ui.router but not any help. I do not see the token going to WebAPI.

    Reply
    • Taiseer Joudeh says

      May 29, 2015 at 8:25 am

      I do not have an answer for this now, I didn’t check the updates on ADAL recently but does it support now UI-router or traditional route provider only? If the second then I doubt it will work.

      Reply
  11. GR says

    June 1, 2015 at 1:00 am

    I need to add a role claim to the adal token from another database. How can this be done?

    Reply
    • Taiseer Joudeh says

      June 3, 2015 at 2:37 am

      Interesting question, to be honest I dont have answer to this now.

      Reply
      • Ronald Wildenberg says

        February 2, 2016 at 4:47 pm

        As it happens, I just wrote a blogpost describing a similar scenario (http://itq.nl/combining-adal-js-with-role-based-security-in-asp-net-web-api/). In my case the ‘database’ from which I retrieve role information is Azure AD but the idea is the same.

        Reply
        • Taiseer Joudeh says

          February 3, 2016 at 1:55 am

          Thanks for sharing this Ronald, I will take a look on the post soon.

          Reply
  12. Joe N. says

    June 7, 2015 at 1:12 pm

    You write •To be able to access the protected API end points, we need to send the token in the “Authorization” header using bearer scheme,

    But for this you would need access_token, not id_token

    Or am I missing something?

    Reply
    • Taiseer Joudeh says

      June 8, 2015 at 12:19 am

      You are correct, if you want to access protected end point then you use the access token.

      Reply
      • Joe N. says

        June 8, 2015 at 9:50 am

        ADAL login returns only the id_token. How do I receive the access_token?

        Reply
        • Michael H says

          August 13, 2015 at 1:05 pm

          We hit the same problem. It looks like the whole chain is setup and hard-coded to use the flow with id_token, so you can’t get the access_token.

          Reply
          • Joe N. says

            August 16, 2015 at 9:32 am

            In theory – the acquireToken method should do that. Apparently something is missing – I filled it in and am hoping to submit a pull request soon, I’m having some issue with github at the moment, as soon as I do I’ll try to share it back here.

            You can follow my repo so you’ll see when I resolve the issue and you’ll be able to download immediately. https://github.com/jnfsmile/azure-activedirectory-library-for-js

  13. Evan says

    June 23, 2015 at 11:31 pm

    The demo site forced me to change the password – it is now AngularJS!!!

    Note the extra exclamation point.

    Reply
    • Taiseer Joudeh says

      June 30, 2015 at 12:39 am

      Thanks for the heads up, I should turn this off as users keep changing password for this account 🙂

      Reply
      • Winicius says

        July 14, 2015 at 9:06 pm

        It is possible usage account demo?

        Reply
        • Taiseer Joudeh says

          July 15, 2015 at 12:49 am

          I guess yes, until the password has been changed.

          Reply
          • Ben Meredith says

            September 30, 2015 at 7:36 pm

            Just a heads up, I changed the password back to AngularJS!! since it expired again.

          • Taiseer Joudeh says

            October 3, 2015 at 6:13 pm

            Thanks Ben 🙂 I forgot what was the password, thanks for setting it back!

  14. J.R. Neumeier says

    July 13, 2015 at 1:35 am

    I get multiple “The returned id_token is not parseable.” console errors from

    “AuthenticationContext.prototype._logstatus = function (msg) {
    if (console) {
    console.log(msg);
    }
    };”
    when running the application.

    Any ideas? 🙁

    Reply
  15. danhibbert says

    August 8, 2015 at 11:27 pm

    Hi Taiseer – thanks for this blog entry – it’s getting me started on an interesting journey! I’ve followed the steps and have got the authentication with AAD working. However, when I make the call to web api, it is returning a 401 unauthorised. The request header has a Authorization : Bearer token and the startup auth is set up as per the blog entry. Am I missing something obvious?

    Reply
  16. nguyener says

    September 15, 2015 at 8:51 am

    Hi Taiseer,
    I noticed that in the ConfigureOAuth method, you wrote
    Audience = ConfigurationManager.AppSettings[“ida:ClientID”],
    In another post (https://bitoftech.net/2014/09/12/secure-asp-net-web-api-2-azure-active-directory-owin-middleware-adal/) it is:
    Audience = ConfigurationManager.AppSettings[“Audience”],

    Does it matter whether “Audience” is the client id or application url?

    Reply
    • Taiseer Joudeh says

      September 18, 2015 at 2:49 pm

      Hi, not it should be the same.

      Reply
  17. Erikk Ross says

    December 23, 2015 at 6:53 pm

    I was able to get this to work when the Web API and SPA are in the same solution and both have the same the same URL. But when I tried separating the Web API and the SPA into two different sites, I get a 401 Unauthorized message when calling the API from the SPA. Is it possible to separate the two?

    Reply
    • Taiseer Joudeh says

      December 24, 2015 at 12:41 am

      Hi Erikk, yes you can do this, and I’m doing this on this post. Make sure it is not CORS issue that you need to enable it on the Api side.

      Reply
  18. Thibault says

    January 20, 2016 at 4:12 pm

    Hello,
    thank you Taiseer for this great post.
    I am seeking some help here though.

    I am using adal.js with angular. Everything work as expected except the token refreshing.
    Indeed, if after 1 hour I do anything that issues an XHR to a protected resource then no more token is sent along with the request and I get stuck with a 401.
    Shouldn’t be the token renewed silently by the hidden iframe?
    Note that if I move to another state/view which has the RequierADLogin set to true then it aquires a new token and all is good.

    Any ideas to get through this?

    best,

    Reply
    • Joe N. says

      January 25, 2016 at 10:52 am

      Hi, see my comment above (https://bitoftech.net/2014/12/02/angularjs-authentication-using-azure-active-directory-authentication-library-adal/#comment-64438)

      I’ve made a pull request but it’s still pending

      Reply
      • Thibault says

        January 25, 2016 at 1:09 pm

        Thank you Joe.
        I solved my problem. By looking at the code of angular-adal.js I figured out that the “endpoints” parameter shouldn’t be optional in order to trigger the iFrame mechanism. Hence, adding endpoints: “api/v1”: “my_client_id” into the adalAuthenticationServiceProvider.init method solved the problem.

        Reply
        • Nikhil Pratap says

          November 16, 2016 at 3:46 am

          How exactly did you solve this issue. I’m still getting 401 after 1 hour. The iframe mechanism is not working for me.

          Reply
  19. Tina Pulley says

    July 17, 2016 at 10:40 am

    Having read this I thought it was really informative. I appreciate you finding the time and effort to put this article together.
    I once again find myself spending way too
    much time both reading and posting comments. But so what,
    it was still worth it!

    Reply
    • Taiseer Joudeh says

      July 18, 2016 at 5:00 pm

      Thanks Tine for your comment. Appreciated 🙂

      Reply
  20. Ariel Plon says

    July 28, 2017 at 2:48 pm

    Once again….GREAT POST!!!! Thank you for sharing and making such easy to follow and usefull tutorials.

    We need to develop a WebAPI as backend wth Angular 1.x in the frontend, that allows both internal AAD Users, and External users, for which we would like to use the AAD B2C. Is there any way to “mix and match” AAD with AAD B2C?

    If not, is there any other way to authenticate External users with External identity providers?

    Best regards

    Reply

Trackbacks

  1. online store terms of services says:
    August 16, 2017 at 12:02 pm

    online store terms of services

    AngularJS Authentication Using Azure Active Directory Authentication Library (ADAL) – Bit of Technology

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About Taiseer

Husband, Father, Consultant @ MSFT, Life Time Learner... Read More…

Buy me a coffeeBuy me a coffee

Recent Posts

  • Integrate Azure AD B2C with ASP.NET MVC Web App – Part 3
  • Secure ASP.NET Web API 2 using Azure AD B2C – Part 2
  • Azure Active Directory B2C Overview and Policies Management – Part 1
  • ASP.NET Web API Claims Authorization with ASP.NET Identity 2.1 – Part 5
  • ASP.NET Identity 2.1 Roles Based Authorization with ASP.NET Web API – Part 4

Blog Archives

Recent Posts

  • Integrate Azure AD B2C with ASP.NET MVC Web App – Part 3
  • Secure ASP.NET Web API 2 using Azure AD B2C – Part 2
  • Azure Active Directory B2C Overview and Policies Management – Part 1
  • ASP.NET Web API Claims Authorization with ASP.NET Identity 2.1 – Part 5
  • ASP.NET Identity 2.1 Roles Based Authorization with ASP.NET Web API – Part 4

Tags

AJAX AngularJS API API Versioning ASP.NET Authentication Autherization Server Azure Active Directory B2C Azure AD B2C basic authentication C# CacheCow Client Side Templating Code First Dependency Injection Entity Framework ETag Foursquare API HTTP Caching HTTP Verbs IMDB API IoC Javascript jQuery JSON JSON Web Tokens JWT Model Factory Ninject OAuth OData Pagination Resources Association Resource Server REST RESTful Single Page Applications SPA Token Authentication Tutorial Web API Web API 2 Web API Security Web Service wordpress.com

Search

Copyright © 2019 · eleven40 Pro Theme on Genesis Framework · WordPress · Log in

loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.