Giter Site home page Giter Site logo

adal-angular4's Introduction

adal-angular4

Build status npm version


Angular 4+ Adal wrapper package. Can be used to authenticate Angular applications against Azure Active Directory v1 endpoint.


Change Log

4.0.9

  • Upgraded to Gulp version 4. Build options are now:
gulp watch    - watch for file changes do the build task
gulp build    - clean the dist directory and build the project
gulp commit   - bump version and add and commit files to git (for maintainers only)
gulp publish  - publish new npm version (for maintainers only)

4.0.1

  • Updated to support latest version of adal-angular. Major version updated because of potentially breaking changes.

3.0.7

  • Added an automatic login token refresh feature. It will refresh tokens at application load if there is a valid sign-in token. It will also refresh the login token 5 minutes before it expires.

3.0.1

  • Updated to Angular 6, cleaned up files. THIS IS A BREAKING VERSION!

2.0.0

  • Updated to Angular 5, cleaned up files. THIS IS A BREAKING VERSION!

1.1.11

  • Fixed a bug where the valid scenario of refreshing an id_token is not handled - thanks to @alan-g-chen.

1.1.4

  • Hash is now removed from url after login

1.0.1

  • Added HTTP Interceptor for Angular 4.3.0+
  • Updated all packages to newest versions

Update and Build Instructions

git clone https://github.com/benbaran/adal-angular4.git

npm install -g @angular/cli@latest gulp@latest

del .\package-lock.json

ng update --all --force

npm install [email protected]

gulp build

NPM Publish Instructions (For Maintainers Only)

git clone https://github.com/benbaran/adal-angular4.git

npm install -g @angular/cli@latest gulp@latest

del .\package-lock.json

ng update --all --force

npm install [email protected]

gulp publish

Usage ( tested with Angular 8)

First install the package ( ex using npm )

npm i adal-angular4

Implement ADAL authentication:

app.module.ts

Open your Angular root module, usually app.module.ts Add the following import

/*Authentication*/
import { AdalService, AdalGuard, AdalInterceptor } from 'adal-angular4';
import { HTTP_INTERCEPTORS } from '@angular/common/http';

Update your @NgModule providers section with the following line:

providers: [AdalService, AdalGuard, {provide: HTTP_INTERCEPTORS, useClass: AdalInterceptor, multi: true }

It should look something like this:

@NgModule({
  declarations: [
    AppComponent,
    ...
  ],
  imports: [
    ...
  ],
  providers: [AdalService, AdalGuard, {provide: HTTP_INTERCEPTORS, useClass: AdalInterceptor, multi: true }, ... ],
  bootstrap: [AppComponent]
})

environment.ts

inside your environment.ts file add your config, this file is created for you when u use the Angular CLI

Usually can be found here: src ├── environements └── environment.ts └── environment.prod.ts

export const environment = {
  production: false,
  config: {
    tenant: 'tenant.onmicrosoft.com',
    clientId: 'app registration id',
    endpoints: {
      'http://localhost:4200/': 'the id'
    }
  }
};

app.component.ts

Then import the following into your root component usually app.component.ts

import { environment } from '../environments/environment';
import { AdalService } from 'adal-angular4';

Init the adal lib by adding the following lines to your constructor or OnInit

export class AppComponent implements {
    constructor(private adalService: AdalService) {
        this.adalService.init(environment.config);
        this.adalService.handleWindowCallback();
    }
}

app-routing.module.ts

You can protect routes by adding the authguard to you route

import the following inside your routing module file usually app-routing.module.ts

import { AdalGuard } from 'adal-angular4';

ex:

const routes: Routes = [
  {
    path: '',
    component: YourComponent,
    canActivate: [AdalGuard]
  }
];

Login / Logout

You can call the login and logout function with the following code.

AdalService needs to be imported in your file

import { AdalService } from 'adal-angular4';
/*Dont forget to initialize*/
constructor(private adalService: AdalService)

Login:

this.adalService.login();

Logout:

this.adalService.logOut();

Check if user is allready authenticated, if not login

Checking if user has allready logged in if not do something

AdalService needs to be imported in your file

import { AdalService } from 'adal-angular4';
/*Dont forget to initialize*/
constructor(private adalService: AdalService)
if (this.adalService.userInfo.authenticated) {
    /*All good*/
} else {
    /*No good*/
}

Using Azure AD Role based Authentication

This section is optional, the library works without these settings aswell.

Setup for Role based authentication in your Angular application:

Steps to do in Azure

Go to you app registration, the same one you used the clientId from inside your environments file. And add your custom roles inside the app manifest:

"appRoles": [
    {
      "allowedMemberTypes": [
        "User"
      ],
      "description": "your user description",
      "displayName": "UserRole",
      "id": "generate a unique guid",
      "isEnabled": true,
      "value": "UserRole"
    },
    {
      "allowedMemberTypes": [
        "User"
      ],
      "description": "your admin description",
      "displayName": "AdminRole",
      "id": "generate a unique guid",
      "isEnabled": true,
      "value": "AdminRole"
    }
  ]

Once these roles have been created you can assign them to users:

Open the registration for local directory, this can be found on the overview page on the right side 'Managed application in local directory: -your app registration name-' On this page go to 'Users and groups' and click 'Add user'

Now add the user that needs to be able to access the application and assign a role to the user.

The last step in Azure is activating the User assignment required property in the 'Properties' tab. When you enable this option only users that are assigned a role can login to the application.

Steps in Angular

In order to protect a certain route to be accessed only by authenticated users with a certain role: Update the

app-routing.module.ts

with the following data attribute

const routes: Routes = [
  {
    path: '',
    component: YourComponent,
    canActivate: [AdalGuard],
    data: { expectedRole: 'AdminRole' }
  }
];

expectedRole can be any of the custom Roles you created in App manifest (appRoles) for your app registration in Azure.

adal-angular4's People

Contributors

alan-g-chen avatar batkotnac avatar benbaran avatar benbaran-journeycare avatar chase-swanson avatar creativeacer avatar dependabot[bot] avatar filipows avatar garbanas avatar geerzo avatar ollief87 avatar stuarthallows avatar yeya avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

adal-angular4's Issues

Unable to fetch Roles defined in Application Manifest

Hi Ben,
I am using adal-angular4 for authenticating my Application against Azure AD. I am able to succeed in Authentication. However when I tried to Authorize my Angular Components using the Roles defined in Azure Manifest I am not able to get the same. Can you please guide me how can I resolve the issue.
Please find the data present in the UserInfo below.
{
"aud": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"iss": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"iat": 1506085285,
"nbf": 1506085285,
"exp": 1506089185,
"aio": "ATQAy/8FAAAA/WMobpsABxDXJ4gCPGFyk6p39T703tWKOPTaevFDhpQdcbyBdFA2+R4pZaz2ro63",
"amr": [
"pwd"
],
"email": "[email protected]",
"family_name": "xxxxxxxx",
"given_name": "[email protected]",
"groups": [
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
],
"idp": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/",
"ipaddr": "x.x.x.x",
"name": "[email protected]",
"nonce": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"oid": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"sub": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"tid": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"unique_name": "[email protected]",
"ver": "1.0"
}

I am expecting Roles which we have defined in the Manifest file. Can you please let me know whether my understanding is right regarding the roles that need to be present in the userInfo.profile and can I know is there any API reference for the same..
Please find the details of manifest file below.

"appId": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"appRoles": [
{
"allowedMemberTypes": [
"User"
],
"displayName": "Owner",
"id": "fc1fc18a-e366-4257-be5e-e495c339fe64",
"isEnabled": true,
"description": "Owner can manage roles and perform all task actions.",
"value": "Owner"
},
{
"allowedMemberTypes": [
"User"
],
"displayName": "Reader",
"id": "4881ec9c-d4b1-4e14-b4c0-33fdd48b4cb5",
"isEnabled": true,
"description": "Reader only have the ability to view tasks and their statuses.",
"value": "Reader"
}
]

Thanks,
Shashi

Username always undefined

After login I'm receiving the username as undefined.

Debugging I've seen that the variable is wrong in the updateDataFromCache function:
if (user) { this.user.username = user.username; this.user.profile = user.profile; this.user.token = token; this.user.error = this.context.getLoginError(); }
I've changed it to (notice capital N):

this.user.username = user.userName;

Am I right?

I can't get acquireToken to work.

When acquireToken is called, the renew state is stored in the context object in the AdalService instance, but when the token is received and I call handleWindowCallback the context in the AdalService doesn't contain any renew states. If I call acquireToken again I can see that the previous renew state is still in the context. My conclusion is that for some reason there are different instances of the context object in the AdalService. I have added AdalService as a provider in the app-module.ts so there should only be one instance of the AdalService but can there still be several instances of the context object inside of the AdalService? Am I doing something wrong or have I ran into a bug? I'm using the latest 2.x.x version. I should also mention that when I ran adal-angular4 with version 1.0.15 of adal-angular it all worked fine. I saw a code difference in adal-angular that I reported as a bug (AzureAD/azure-activedirectory-library-for-js#712) but the issues was closed with the reply that adal-angular4 had to be updated!

http service undefined

Hey,

Tried your sample, and even updated to latest adal-angular-4.

In home.component i try to do a
this.http.get('apiuri...')

But the private http: Adal4HTTPService is undefined.

Do you know why?

How to access the callback after login?

Hi,

After login I want to show a message if it is successful or an error if not, however it is a void method which means I have no way of knowing when it completes - should it not return a promise or callback?

Cannot find module 'adal-angular'

Getting the following error on ng serve:

ERROR in C:/Users/Matt/Source/Repos/internal/node_modules/adal-angular4/adal4.service.d.ts (3,22): Cannot find module 'adal-angular'.
ERROR in C:/Users/Matt/Source/Repos/internal/node_modules/adal-angular4/node_modules//src/backends/browser_jsonp.d.ts (1,33): Initializers are not allowed in ambient contexts.
ERROR in C:/Users/Matt/Source/Repos/internal/node_modules/adal-angular4/node_modules//src/errors.d.ts (9,33): Initializers are not allowed in ambient contexts.
ERROR in C:/Users/Matt/Source/Repos/internal/node_modules/adal-angular4/node_modules//src/errors.d.ts (10,43): Initializers are not allowed in ambient contexts.
ERROR in C:/Users/Matt/Source/Repos/internal/node_modules/adal-angular4/node_modules//src/errors.d.ts (11,42): Initializers are not allowed in ambient contexts.
ERROR in C:/Users/Matt/Source/Repos/internal/node_modules/adal-angular4/node_modules//src/errors.d.ts (12,43): Initializers are not allowed in ambient contexts.
ERROR in C:/Users/Matt/Source/Repos/internal/node_modules/adal-angular4/node_modules//src/errors.d.ts (13,35): Initializers are not allowed in ambient contexts.
ERROR in C:/Users/Matt/Source/Repos/internal/node_modules/adal-angular4/node_modules//src/animation/dsl.d.ts (81,33): Initializers are not allowed in ambient contexts.
ERROR in C:/Users/Matt/Source/Repos/internal/node_modules/adal-angular4/node_modules//src/animation/animation_metadata_wrapped.d.ts (12,33): Initializers are not allowed in ambient contexts.
ERROR in C:/Users/Matt/Source/Repos/internal/node_modules/adal-angular4/node_modules//http/src/jsonp.d.ts (5,44): Initializers are not allowed in ambient contexts.
ERROR in C:/Users/Matt/Source/Repos/internal/node_modules/adal-angular4/node_modules//http/src/jsonp.d.ts (6,45): Initializers are not allowed in ambient contexts.
ERROR in C:/Users/Matt/Source/Repos/internal/node_modules/adal-angular4/node_modules//http/src/jsonp.d.ts (7,52): Initializers are not allowed in ambient contexts.

Using latest Angular-CLI version. I've tried the fixes suggested at alenny/angular2-adal#8 but they're for the Angular 2 version, and no luck.

Any ideas?

Angular 6

With the release of Angular 6 i get the warning:

npm WARN [email protected] requires a peer of @angular/common@^5.2.5 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@^5.2.5 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/platform-browser@^5.2.5 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/router@^5.2.5 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of rxjs@^5.5.6 but none is installed. You must install peer dependencies yourself.

Maybe update the packages and files to support Angular 6?

Application Refresh Issue

Hi Team,
This is nice wrapper & we are using this in our application. However, on successful authentication it is causing the application to refresh a number of times.

If there are any api calls associated then it gets called multiple times as well.
Same behavior is seen in IE as well.
Can you please let me know what could be the issue?

Unable to call secure WebApi

I've update my app from angular4 to angular6, and now I'm unable to call secure web api.
I try to setup a PrepareOptions method to setup HttpHeaders
I have already try to use a PrepareOptions method to setup HttpHeaders but I've always HttpResponse "Unauthorized".
Here my code

import { Component, OnInit } from '';
import { AdalService } from 'adal-angular4';
import {HttpHeaders, HttpClient} from '/http';
import {environment} from '../../environments/environment';

@component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
activities:any;
constructor(private adalService: AdalService,private http:HttpClient) { }

ngOnInit() {
this.getActivities();
}

getActivities():any{
return this.http.get(${environment.apiUrl},this.prepareOptions())
.subscribe(res=>this.activities=res,error=>console.log(error))
}
private prepareOptions(): any {
let headers = new HttpHeaders();
headers = headers
.set('Content-Type', 'application/json;')
.set('Accept', 'application/json;')
.set('Authorization', Bearer + ${this.adalService.userInfo.token});
return { headers };
}}.
If i try to use Http_interceptor without PrepareOption Method as a parameter of Http call, I've this error:
core.js:1601 ERROR Token renewal operation failed due to timeout:
app.module:

@NgModule({
declarations: [
AppComponent,
HomeComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MaterialModule,
HttpClientModule
],
providers: [AdalService, AdalGuard,
{
provide: HTTP_INTERCEPTORS,
useClass: AdalInterceptor,
multi: true
},
ActivityService

]
,
bootstrap: [AppComponent]
})
export class AppModule { }

ACTIVITYSERVICE.TS
import { Injectable } from '';
import { AdalService } from 'adal-angular4';
import {HttpHeaders, HttpClient} from '/http';
import {environment} from '../environments/environment';

@Injectable({
providedIn: 'root'
})
export class ActivityService {
constructor(private http:HttpClient,private adalService:AdalService) { }
getActivities():any{
return this.http.get(${environment.apiUrl})
}
}

HOME.COMPONENT
this.activitiesService.getActivities().subscribe(res=>console.log(res));

can anyone help me?

Generated token is not authorizing API.

After generating token from my code, when I post the token in Postman header along with my api url in url section and GET request , I am getting below message :
{
"Message": "Authorization has been denied for this request."
}

Please suggest me some solution.

On handlewindowcallback not applying idtoken being sent

So just to clarify this was working 1-2 weeks ago and I updated version to 2.0.14 and caused another issue that broken whole system so reverted back to 2.0.13 and now my authentication will not get applied after my idtoken is returned with the url and handlewindowcallback is called but the service doesn't see the token or still marked as not authenticated. I do see the service trying to deserialize the token but not sure why it's not working. Is it related to the adal.js version upgrading as well?

Anyone see a similar issue

JWT token not included in call to Web API

Hello benbaran,
I'm trying to access web api using http call, for some reason request is not including authentication value in headers section (jwt token received from Azure in my case). Web API returning 401 - unauthorized.
Do I need to save jwt token to local storage after authentication?
Do you have any sample code on this?

Request:
getLocation(): Observable {
return this.http
.get(https://localhost:44383/api/location?cityName=stl)
.map((response: Response) => response)
.catch(this.handleError);
}

token for graph api

I'm not able to use the token to access the Microsoft graph API. How to acquire token so that I can access the graph API. Please help me here with some examples.

Endpoint Token Response `ERROR Token renewal operation failed due to timeout.`

Struggling to configure ADAL with Angular app. Believe struggles are configuration based not the library, but any help would be greatly appreciated.

Angular 6 and adal-angular4 v 3.01

I can login to the site fine, but when requesting a token for an endpoint, the console errors with ERROR Token renewal operation failed due to timeout.

When I look at the actual traffic, I actually am receiving a token in a response from AAD, but it is a 302 and the token is actually embedded in html

<html><head><title>Object moved</title></head><body>
<h2>Object moved to <a href="http://localhost:4201/#access_token=eyJ0eXAiOiJKV<valid token>&amp;token_type=Bearer&amp;expires_in=3599&amp;state=<guid>%7chttps%3a%2f%2<Endpoint Site>&amp;session_state=<guid>">here</a>.</h2>
</body></html>

As before, the token in the HTML is a valid token for the endpoint, but the the response is not being handled correctly and adding the token to the cache and future requests.

Seems to keep looping and opening an iframe inside of another iframe inside another iframe, etc, etc.

Any help would be extremely helpful.

Adal4Interceptor Example

I tried to use the Adal4HTTPService but I get 401's on my service calls and I think that is because it is not (by default) storing the JWT token in the header of the request.

So, I tried to use the Adal4Interceptor but I need additional help configuring/using it. (Or maybe an example added to this repository or the example one at https://github.com/benbaran/adal-angular4-example one would be great?)

In my case, I added
{
provide: HTTP_INTERCEPTORS,
useClass: Adal4Interceptor,
multi: true
},

to my @NgModule's providers section and I am using the Adal4HTTPService as injected into my services. However, they now receive the following error at runtime:

Uncaught Error: Can't resolve all parameters for Adal4Interceptor: (?).
at syntaxError (compiler.es5.js:1694)
at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getDependenciesMetadata (compiler.es5.js:15925)
at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getTypeMetadata (compiler.es5.js:15793)
at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getInjectableMetadata (compiler.es5.js:15779)
at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver.getProviderMetadata (compiler.es5.js:16070)
at compiler.es5.js:15999
at Array.forEach ()
at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver._getProvidersMetadata (compiler.es5.js:15959)
at CompileMetadataResolver.webpackJsonp.../../../compiler/@angular/compiler.es5.js.CompileMetadataResolver.getNgModuleMetadata (compiler.es5.js:15614)
at JitCompiler.webpackJsonp.../../../compiler/@angular/compiler.es5.js.JitCompiler._loadModules (compiler.es5.js:26958)

Does anyone know what "Can't resolve all parameters for Adal4Interceptor: (?)." means?

Thanks!

Object(...) is not a function error while calling acquiretoken

I was trying to use the latest version of adal-angular4 (V3.0.1) in my Angular 5 application. I am using AdalInterceptor to add token to the API calls. From the interceptor while calling acquiretoken, I am getting the below error.

TypeError: Object(...) is not a function
at AdalService.acquireToken (adal.service.js:101)
at AdalInterceptor.intercept (adal.interceptor.js:22)
at HttpInterceptorHandler.handle (http.js:1796)
at HttpXsrfInterceptor.intercept (http.js:2489)
at HttpInterceptorHandler.handle (http.js:1796)
at HttpInterceptingHandler.handle (http.js:2547)
at MergeMapSubscriber.eval [as project] (http.js:1466)
at MergeMapSubscriber._tryNext (mergeMap.js:128)
at MergeMapSubscriber._next (mergeMap.js:118)
at MergeMapSubscriber.Subscriber.next (Subscriber.js:95)

handleWindowCallback() doesn't renew id_token

In handleWindowCallback, if renew succeeds for anything but 'access_token', nothing happens (leaving e.g. acquireToken() hanging).
Should there be a case for handling 'id_token'?
Should there be a catch-all error callback invocation?

ERROR in Metadata version mismatch for module C:/cs/CSM/node_modules/adal-angular4plus/node_modules//core.d.ts, found version 4, expected 3. I am using Visual Studio 2017 along with ASP.net core 2.0 for creating an authentication application using angular4 and adal-angular4plus. I am able to build and run the program without any issues. The error comes only when I try to 'Publish' using VS 2017.

ERROR in Metadata version mismatch for module C:/cs/CSM/node_modules/adal-angular4plus/node_modules//core.d.ts, found version 4, expected 3. I am using Visual Studio 2017 along with ASP.net core 2.0 for creating an authentication application using angular4 and adal-angular4plus. I am able to build and run the program without any issues.

The error comes only when I try to 'Publish' using VS 2017.

package.json
{ "name": "CSM", "private": true, "version": "0.0.0", "scripts": { "test": "karma start ClientApp/test/karma.conf.js" }, "devDependencies": { "@angular/animations": "4.2.5", "@angular/common": "4.2.5", "@angular/compiler": "4.2.5", "@angular/compiler-cli": "4.2.5", "@angular/core": "4.2.5", "@angular/forms": "4.2.5", "@angular/http": "4.2.5", "@angular/platform-browser": "4.2.5", "@angular/platform-browser-dynamic": "4.2.5", "@angular/platform-server": "4.2.5", "@angular/router": "4.2.5", "@ngtools/webpack": "1.5.0", "@types/chai": "4.0.1", "@types/jasmine": "2.5.53", "@types/webpack-env": "1.13.0", "angular2-router-loader": "0.3.5", "angular2-template-loader": "0.6.2", "aspnet-prerendering": "^3.0.1", "aspnet-webpack": "^2.0.1", "awesome-typescript-loader": "3.2.1", "bootstrap": "^3.3.7", "chai": "4.0.2", "css": "2.2.1", "css-loader": "0.28.4", "es6-shim": "0.35.3", "event-source-polyfill": "0.0.9", "expose-loader": "0.7.3", "extract-text-webpack-plugin": "2.1.2", "file-loader": "0.11.2", "font-awesome": "^4.7.0", "html-loader": "0.4.5", "isomorphic-fetch": "2.2.1", "jasmine-core": "2.6.4", "jquery": "3.2.1", "json-loader": "0.5.4", "karma": "1.7.0", "karma-chai": "0.1.0", "karma-chrome-launcher": "2.2.0", "karma-cli": "1.0.1", "karma-jasmine": "1.1.0", "karma-webpack": "2.0.3", "preboot": "4.5.2", "raw-loader": "0.5.1", "reflect-metadata": "0.1.10", "rxjs": "5.4.2", "style-loader": "0.18.2", "to-string-loader": "1.1.5", "typescript": "2.4.1", "url-loader": "0.5.9", "webpack": "2.5.1", "webpack-hot-middleware": "2.18.2", "webpack-merge": "4.1.0", "zone.js": "0.8.12" }, "dependencies": { "@angular/cli": "^1.6.3", "adal-angular4plus": "^1.0.1", "primeng": "^4.1.0" } }

Publish output fragment:

CSM -> C:\cs\CSM\bin\Any CPU\Release\netcoreapp2.0\CSM.dll
"dotnet" exec --runtimeconfig "C:\cs\CSM\bin\Any CPU\Release\netcoreapp2.0\CSM.runtimeconfig.json" --depsfile "C:\cs\CSM\bin\Any CPU\Release\netcoreapp2.0\CSM.deps.json" "C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.mvc.razor.viewcompilation\2.0.1\build\netstandard2.0\Microsoft.AspNetCore.Mvc.Razor.ViewCompilation.dll" @"obj\Any CPU\Release\netcoreapp2.0\microsoft.aspnetcore.mvc.razor.viewcompilation.rsp"
npm install
npm WARN @0.0.43 requires a peer of rxjs@^5.5.2 but none is installed. You must install peer dependencies yourself.
up to date in 5.538s

node node_modules/webpack/bin/webpack.js --config webpack.config.vendor.js --env.prod
Hash: 206eac77ac26ca4f08fe3a14b3c79dfdd47cacbb
Version: webpack 2.5.1
Child
Hash: 206eac77ac26ca4f08fe
Time: 21443ms
Asset Size Chunks Chunk Names
674f50d287a8c48dc19ba404d20fe713.eot 166 kB [emitted]
912ec66d7572ff821749319396470bde.svg 444 kB [emitted] [big]
b06871f281fee6b241d60582ae9369b9.ttf 166 kB [emitted]
89889688147bd7575d6327160d64e760.svg 109 kB [emitted]
vendor.js 1.72 MB 0 [emitted] [big] vendor
vendor.css 917 kB 0 [emitted] [big] vendor

WARNING in .//adal-angular4plus//@angular/core/esm5/core.js
6541:15-36 Critical dependency: the request of a dependency is an expression

WARNING in .//adal-angular4plus//@angular/core/esm5/core.js
6561:15-102 Critical dependency: the request of a dependency is an expression
Child
Hash: 3a14b3c79dfdd47cacbb
Time: 21383ms
Asset Size Chunks Chunk Names
89889688147bd7575d6327160d64e760.svg 109 kB [emitted]
674f50d287a8c48dc19ba404d20fe713.eot 166 kB [emitted]
912ec66d7572ff821749319396470bde.svg 444 kB [emitted] [big]
b06871f281fee6b241d60582ae9369b9.ttf 166 kB [emitted]
vendor.js 7.1 MB 0 [emitted] [big] vendor
node node_modules/webpack/bin/webpack.js --env.prod
Hash: 7c6b35cb9cc073d78bd1e242d2b377746ea93733
Version: webpack 2.5.1
Child
Hash: 7c6b35cb9cc073d78bd1
Time: 4151ms
Asset Size Chunks Chunk Names
main-client.js 115 kB 0 [emitted] main-client

ERROR in Metadata version mismatch for module C:/cs/CSM/node_modules/adal-angular4plus/node_modules/@angular/core/core.d.ts, found version 4, expected 3

ERROR in ./ClientApp/boot.browser.ts
Module not found(0,0): Error : Can't resolve './../$$_gendir/ClientApp/app/app.browser.module.ngfactory' in 'C:\cs\CSM\ClientApp'
@ ./ClientApp/boot.browser.ts 6:0-95
Child
Hash: e242d2b377746ea93733
Time: 4155ms
Asset Size Chunks Chunk Names
main-server.js 1.81 MB 0 [emitted] [big] main-server

ERROR in Metadata version mismatch for module C:/cs/CSM/node_modules/adal-angular4plus/node_modules/@angular/core/core.d.ts, found version 4, expected 3

ERROR in ./ClientApp/boot.server.ts
Module not found(0,0): Error : Can't resolve './../$$_gendir/ClientApp/app/app.server.module.ngfactory' in 'C:\cs\CSM\ClientApp'
@ ./ClientApp/boot.server.ts 8:0-94
C:\cs\CSM\CSM.csproj(135,5): Error MSB3073: The command "node node_modules/webpack/bin/webpack.js --env.prod" exited with code 2.

2>Publish failed due to build errors. Check the error list for more details.
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped =======

What I am missing ?

thanks

Retrieve refresh token for server side custom login

I'm trying to make a custom login using Microsoft Office 365 with my firebase application, using cloud functions. I got to the step of signing in the user and getting the token, however my problem is: I cannot get the refresh token, which I believe is the correct way to authenticate the user in the server side by getting a new token from O365 in the cloud function.
How can I retrieve this token?
Also, is this the correct way to do this type of authentication, or should I use a fancy redirect strategy?
Many thanks!

Azure B2C AD

Hi Ben,

I had some troubles making this work with Azure B2C AD, with this change to the config all works as expected. Especially the logout was troubling.

const config = {
  tenant: environment.tenant,
  clientId: environment.clientId,
  extraQueryParameter: '',
  logOutUri: ''
};


  constructor(private service: Adal4Service,
    private http: Adal4HTTPService) {
   
	
    config.logOutUri = 'https://login.microsoftonline.com/' + environment.tenant + '/oauth2/logout?post_logout_redirect_uri=' +
      encodeURIComponent(window.location.href.split('?')[0].split('#')[0]) + '&' +
      'p=' + environment.profile;

    config.extraQueryParameter = 'p=' + environment.profile + '&scope=openid';

    this.service.init(config);
  }

Unable to call secure WebApi

Hi all,
I've update my app from angular4 to angular6, and now I'm unable to call secure web api.
In angular4 I call Web Api using Adal4HttpService, and all works fine:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Adal4HTTPService } from 'adal-angular4';

import { environment } from '../../../environments/environment';
import { Employee, IEmployee } from './models';

@Injectable()
export class EmployeeService {

constructor(
private http: Adal4HTTPService

) { }
public getEmployees(): Observable<Array> {
return this.http.get(${environment.apiUrl})
.map(response => {
const tmp = <any[]>response.json();
return tmp.map(e => new Employee(e));
});
}
}

In adal-angular4 v 3 (for angular 6) the AdalHttpService doesn't exist.
there is someone who can help me?

[Question] How to get the access token after login()

How can we have access to the acess token given by the aad API after the user has logged in (I've used the login module)? I've seen that the token is passed trough the redirect url as an hash called 'id_token', is that safe? Have I to retrieve that within the url or there are some methods that allow me to access this returned token?

Adal4-http.service always appends the Bearer token header

The Bearer token is always appended even if the Bearer token header already exists. This can cause the first request to succeed but subsequent requests to fail.

Line 158 (i think) could be changed from
options1.headers.append('Authorization', 'Bearer ' + token);
To
options1.headers.set('Authorization', 'Bearer ' + token);

That resolved the issue for me but it will break if I ever do an update so I hope to see it fixed here.

How do we use it in systemjs?

No umd file. Using index.js file gives adal-angular4/adal4-user not found.
Similarly adal-angular4/adal4.service not found, and also adal4-http.service not found.

I have added 'adal-angular4': {
defaultExtension: 'js'
}, to systemjs.

'adal-angular4': 'npm:adal-angular4',
'adal-angular': 'npm:adal-angular',

in map folder

Http is deprecated

Hello, could you please add HttpClient support to your awesome lib?
Because for now http is deprecated in angular 5

Angular 5 ?

Are there any plans for support angular 5 ? (perhaps in a new project)

Is this still maintained?

I see some issues related to angular 5 without response. If this repo is no longer maintained and there are no plans to migrate to angular 5 maybe we should fork it. Anyone interested in this?

ng build --prod Failing

Hey, I'm using the latest version of ng and I'm getting this error when I try to build with the --prod flag:

ERROR in Error: Error encountered resolving symbol values statically. Calling function 'ɵmakeDecorator', function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol Injectable in C:/Source/Miscellaneous Web Sites/MetricsMonitoring/node_modules/adal-angular4/node_modules/@angular/core/core.d.ts, resolving symbol ɵa in C:/Source/Miscellaneous Web Sites/MetricsMonitoring/node_modules/adal-angular4/node_modules/@angular/http/http.d.ts, resolving symbol ɵa in C:/Source/Miscellaneous Web Sites/MetricsMonitoring/node_modules/adal-angular4/node_modules/@angular/http/http.d.ts

Also, I'm getting these warnings when I run ng serve:

WARNING in ./node_modules/adal-angular4/node_modules/@angular/core/@angular/core.es5.js
5659:15-36 Critical dependency: the request of a dependency is an expression
    at ImportLazyContextDependency.getWarnings (C:\Source\Miscellaneous Web Sites\MetricsMonitoring\node_modules\webpack\lib\dependencies\ContextDependency.js:39:18)
    at Compilation.reportDependencyErrorsAndWarnings (C:\Source\Miscellaneous Web Sites\MetricsMonitoring\node_modules\webpack\lib\Compilation.js:703:24)
    at Compilation.finish (C:\Source\Miscellaneous Web Sites\MetricsMonitoring\node_modules\webpack\lib\Compilation.js:561:9)
    at applyPluginsParallel.err (C:\Source\Miscellaneous Web Sites\MetricsMonitoring\node_modules\webpack\lib\Compiler.js:506:17)
    at C:\Source\Miscellaneous Web Sites\MetricsMonitoring\node_modules\tapable\lib\Tapable.js:289:11
    at _addModuleChain (C:\Source\Miscellaneous Web Sites\MetricsMonitoring\node_modules\webpack\lib\Compilation.js:507:11)
    at processModuleDependencies.err (C:\Source\Miscellaneous Web Sites\MetricsMonitoring\node_modules\webpack\lib\Compilation.js:477:14)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)
 @ ./node_modules/adal-angular4/node_modules/@angular/core/@angular/core.es5.js
 @ ./node_modules/adal-angular4/adal4-interceptor.js
 @ ./node_modules/adal-angular4/index.js
 @ ./src/app/app.module.ts
 @ ./src/main.ts
 @ multi ./src/main.ts

WARNING in ./node_modules/adal-angular4/node_modules/@angular/core/@angular/core.es5.js
5675:15-102 Critical dependency: the request of a dependency is an expression
    at ImportLazyContextDependency.getWarnings (C:\Source\Miscellaneous Web Sites\MetricsMonitoring\node_modules\webpack\lib\dependencies\ContextDependency.js:39:18)
    at Compilation.reportDependencyErrorsAndWarnings (C:\Source\Miscellaneous Web Sites\MetricsMonitoring\node_modules\webpack\lib\Compilation.js:703:24)
    at Compilation.finish (C:\Source\Miscellaneous Web Sites\MetricsMonitoring\node_modules\webpack\lib\Compilation.js:561:9)
    at applyPluginsParallel.err (C:\Source\Miscellaneous Web Sites\MetricsMonitoring\node_modules\webpack\lib\Compiler.js:506:17)
    at C:\Source\Miscellaneous Web Sites\MetricsMonitoring\node_modules\tapable\lib\Tapable.js:289:11
    at _addModuleChain (C:\Source\Miscellaneous Web Sites\MetricsMonitoring\node_modules\webpack\lib\Compilation.js:507:11)
    at processModuleDependencies.err (C:\Source\Miscellaneous Web Sites\MetricsMonitoring\node_modules\webpack\lib\Compilation.js:477:14)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)
 @ ./node_modules/adal-angular4/node_modules/@angular/core/@angular/core.es5.js
 @ ./node_modules/adal-angular4/adal4-interceptor.js
 @ ./node_modules/adal-angular4/index.js
 @ ./src/app/app.module.ts
 @ ./src/main.ts
 @ multi ./src/main.ts

Any idea on how I can fix this?

Loop back

Hi ,

Your library works very fine.
If end user haven`t specified the return url. Library finds the current page url and assign as return and logout url.
However for application registered in the Azure Directory requires redirect url and which incorporated in jwt.
PROBLEM
if application base URL : http://localhost:4200/ and end user got unauthenticated for any reason while at specific page of application http://localhost:4200/admin/usersettings. The library parse this URL. which required to be registered at Azure AD portal application as return url.
To avoid multiple return url it would be great to pass the only origin url only.
Fix :
file : adal4.service.ts
let pathDefault = configOptions.authenticatedUri || (window.location.origin + '/');
configOptions.postLogoutRedirectUri = configOptions.postLogoutRedirectUri || pathDefault + '/logout';

this will work for us to save from registering multiple urls of application in Azure AD portal.

Acquire Token does not renew token

Hi,
I have configured AD in my angular 5 web app. It returns the token and stores it in session storage. But I want to renew the token before it expires. so I call acquiretoken() before expiry time but it doesn't renew the token. It returns the same token each time called. Can you please help how can i renew the token silently even if my page is idle.

Thanks,
Jayesh

missing adal.Config

I liked your project and see the goodness in it.
But I needed to change in the adal4.service.d.ts
from "adal.Config" to "any". And then I got it to work.

The issue i got was
adal-angular4/adal4.service.d.ts (48,27): Namespace ''*'' has no exported member 'Config'.

I use
adal-angular -version 1.0.15
adal-angular4 -verison 1.1.10

`constructor();
/**
*
*
* @param {adal.Config} configOptions
*
* @memberof Adal4Service
/
init(configOptions: adal.Config): void;
/
*
*
*
* @readonly
* @type {adal.Config}
* @memberof Adal4Service
*/
readonly config: adal.Config;

to

constructor();
/**
*
*
* @param {adal.Config} configOptions
*
* @memberof Adal4Service
/
init(configOptions: any): void;
/
*
*
*
* @readonly
* @type {adal.Config}
* @memberof Adal4Service
*/
readonly config: any; `

NodeInvocationException: Prerendering failed because of error: ReferenceError: window is not defined

Hi Everyone,

Created a basic application which uses this package of version 1.1.10.

I am getting an error after running the application called as "NodeInvocationException: Prerendering failed because of error: ReferenceError: window is not defined".

I am using web pack. The error which i am getting is in the file "main-server.js". Below is the code which is causing the issue.

window.Logging = {
        level: 0,
        log: function (message) { }
    };

After removing the package and its dependencies from the code, the application is working fine and the above code is not present in the "main-server.js".

Is any one else getting this issue? If Yes, is there any work around?

Infinite loop - Internet Explorer

Successful authentication with Internet Explorer is resulting in an infinite loop between the redirect_URI and Azure AD. Is anyone else seeing this?

Endpoint is not called by ADAL, instead only token is returned

For this issue I created a new Angular6-app with angular cli, that tries to call my backend API with a token retrieved from the oauth-endpoint.

My source code can be found here:
https://github.com/web265p3/angular-adal-test/tree/master/src

I installed the latest version of adal-angular4 and configured everything like I found in the tutorials.
I call my API with the following lines:

    this.http
    .get(`${environment.adalConfig.apiUrl}authentication3`, this.prepareOptions())
    .pipe(
    map((r: any) => {
        return r;
    })).subscribe(a => {
    }, r => {
    });

The prepare options, just adds the token:

prepareOptions(): any {
    let httpHeaders = new HttpHeaders();
    httpHeaders = httpHeaders
        .set('Content-Type', 'application/json')
        .set('Authorization', `Bearer ${this.adalService.userInfo.token}`);
    return { headers: httpHeaders };
}

But a URL with "authentication3" as suffix is never even called. Instead I can find a token, that is returned to my app via an HTTP 302 redirect.

https://login.microsoftonline.com/2ef09b02-2e8f-4181-8bb2-78cfc813799a/oauth2/authorize?response_type=token&client_id=197214be-be8d-4ba1-bdb5-f231ff06bb02&resource=https%3A%2F%2Fmydomain-api.azurewebsites.net&redirect_uri=http%3A%2F%2Flocalhost%3A4200%2F&state=90a7cba4-0370-4ba4-be44-7857b9dfb5a1%7Chttps%3A%2F%2Fmydomain.azurewebsites.net&client-request-id=84e96d07-a7a9-4ec5-956b-c980d3dc1aca&x-client-SKU=Js&x-client-Ver=1.0.17&prompt=none&login_hint=user.name%40tenantname.onmicrosoft.com&domain_hint=tenantname.onmicrosoft.com

The location header redirects me to localhost:4200 with a valid access token. But ADAL does neither take the token, nor calls my endpoint. It just happens nothong.

I enabled adal verbose logging and get the following output:

Wed, 23 May 2018 12:07:08 GMT:1.0.17-INFO: renewToken is called for resource:https://mydomain-api.azurewebsites.net
app.component.ts:21 Wed, 23 May 2018 12:07:08 GMT:1.0.17-INFO: Add adal frame to document:adalRenewFramehttps://mydomain.azurewebsites.net
app.component.ts:21 Wed, 23 May 2018 12:07:08 GMT:1.0.17-VERBOSE: Renew token Expected state: 90a7cba4-0370-4ba4-be44-7857b9dfb5a1|https://mydomain.azurewebsites.net
app.component.ts:21 Wed, 23 May 2018 12:07:08 GMT:1.0.17-INFO: Navigate url:https://login.microsoftonline.com/2ef09b02-2e8f-4181-8bb2-78cfc813799a/oaut…d=84e96d07-a7a9-4ec5-956b-c980d3dc1aca&x-client-SKU=Js&x-client-Ver=1.0.17
app.component.ts:21 Wed, 23 May 2018 12:07:08 GMT:1.0.17-VERBOSE: Set loading state to pending for: https://mydomain.azurewebsites.net
app.component.ts:21 Wed, 23 May 2018 12:07:08 GMT:1.0.17-INFO: LoadFrame: adalRenewFramehttps://mydomain.azurewebsites.net
app.component.ts:21 Wed, 23 May 2018 12:07:09 GMT:1.0.17-INFO: Add adal frame to document:adalRenewFramehttps://mydomain.azurewebsites.net
app.component.ts:21 Wed, 23 May 2018 12:07:09 GMT:1.0.17-INFO: LoadFrame: adalRenewFramehttps://mydomain.azurewebsites.net
app.component.ts:21 Wed, 23 May 2018 12:07:09 GMT:1.0.17-INFO: Add adal frame to document:adalRenewFramehttps://mydomain.azurewebsites.net
app.component.ts:21 Wed, 23 May 2018 12:07:12 GMT:1.0.17-VERBOSE: State: 90a7cba4-0370-4ba4-be44-7857b9dfb5a1|https://mydomain.azurewebsites.net
app.component.ts:21 Wed, 23 May 2018 12:07:12 GMT:1.0.17-INFO: State status:false; Request type:LOGIN

I am out of ideas, what might go wrong here. Why is ADAL just ignoring my call to the "authentication3" route. Any proposals?

page reload when removing hash from uri in handlewindowcallback

in the handlewindowcallback(adal4.service.ts) the hash with token is removed from the uri (as expected).
But my page (or token renew in iframe) is reloaded after

window.location.href = window.location.href.replace(window.location.hash, '');

my basic route is

{ path: '', redirectTo: '/home', pathMatch: 'full' }

i'm using PathLocationStrategy (the default)

any idea?

Question:

This works great..almost..
Any idea how to get the page to clear the IDToken parameters after it gets authenticated>?

Losing query params when login redirect completes

Whenever I visit a url on my site that has query params, I lose the params when the Azure login page returns back to my site after a successful login.

I can see the properly URL encoded value in the "redirectUri" param to the Azure login page, but the query params in my URL are gone when the Azure login page redirects.

Any thoughts?

handleWindowCallback callback not initialising _newStates v1.1.10

Hi

I've raised an issue in Adal.js [https://github.com/AzureAD/azure-activedirectory-library-for-js/issues/698#issuecomment-357325742] and it highlighted to me where the issue might be:

I'm currently using adal-angular4 v1.1.10 which uses Adal.js 1.0.16, if I uses v1.0.14 it works.

In Adal.js 1.0.16 there is some logic in to get the _renewStates from the iframe window after the callback. Looks like we need to do this extra code first before we can use getRequestInfo.

The issue above has a link to the code that we are missing.

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.