Angular2-jwt: Problems with official angular release (2.0.0) integration

Created on 20 Sep 2016  ·  38Comments  ·  Source: auth0/angular2-jwt

The 'bootstrap' method of angular 2 does not expect to get providers in an array as currently the guide shows however there is 'NgModule' annotation that expects to get a list of dependant modules such as yours.

I want to use the function 'provideAuth' to configure this module for my application use.
How should i configure it to work with the current release of angular?

Most helpful comment

just clarifying my working solution:

var storage = new Storage();

export function getXSRF() {
    return new CookieXSRFStrategy('csrftoken', 'X-CSRFToken');
}

export function getAuthHttp(http) {
    return new AuthHttp(new AuthConfig({
      noJwtError: true,
      headerPrefix: 'JWT',
      globalHeaders: [{'Accept': 'application/json'}],
      tokenGetter: (() => storage.get('id_token')),
    }), http);
}

@NgModule({
  imports: [
    IonicModule.forRoot(MyApp),
  ],
  providers: [
    AuthService,
    {
        provide: AuthHttp,
        useFactory: getAuthHttp,
        deps: [Http]
    },
/*    {
        provide: XSRFStrategy,
        useFactory: getXSRF,
    }*/
  ],
  declarations: [
    MyApp,
...
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
...
  ]
})

export class AppModule {}

All 38 comments

Is there a working example of this with on github? I am having similar problems with Angular2 final.

i have same issue... anyone can help please

works for me if I use it like mentioned in https://github.com/auth0/angular2-jwt/issues/171

providers: [ // expose our Services and Providers into Angular's dependency injection
    ENV_PROVIDERS,
    APP_PROVIDERS,
  AuthHttp,
  provideAuth({
    headerName: 'Authorization',
    headerPrefix: 'bearer',
    tokenName: 'token',
    tokenGetter: (() => localStorage.getItem('id_token')),
    globalHeaders: [{ 'Content-Type': 'application/json' }],
    noJwtError: true
  }),
    disableDeprecatedForms(),
    provideForms(),
    ValidationService,
    AuthService,
    AuthProvider,
    LocationService,
    TeamProvider,
    UserProvider,
    HistoryRequestProvider,
    Config,
  ]

Would it make sense to export everything as a module?

Very naive approach follows 🙈

@NgModule({
  imports: [HttpModule],
  providers: [AuthHttp],
  declarations: [],
  exports: []
})
export class JwtModule {

  static forRoot(config: AuthConfig = new AuthConfig()): ModuleWithProviders {
    return {
      ngModule: JwtModule,
      providers: [
        { provide: AuthConfig, useValue: config }
      ]
    };
  }
}

Sample using module for angular 2.0 would be great

I'm trying to put it into ionic 2 which now linked with angular 2

@NgModule({
  imports: [
    IonicModule.forRoot(MyApp),
    HttpModule
  ],
  providers: [
    AuthHttp
  ],
  declarations: [
...
  ],
  bootstrap: [IonicApp],
  entryComponents: [
...
  ]
})
export class AppModule {
  static forRoot(config: AuthConfig = new AuthConfig({
      noJwtError: true,
      headerPrefix: 'JWT',
      globalHeaders: [{'Accept': 'application/json'}],
    })): ModuleWithProviders {
    return {
      ngModule: AppModule,
      providers: [
        { provide: AuthConfig, useValue: config }
      ]
    };
  }
}

ionic build gives

[10:01:36]  ngc error: Error: Error at /opt/git/ionic2/.tmp/app/app.module.ngfactory.ts:401:72: Supplied parameters do not match any signature of call target.
    at check (/opt/git/ionic2/node_modules/@angular/tsc-wrapped/src/tsc.js:31:15)
    at Tsc.typeCheck (/opt/git/ionic2/node_modules/@angular/tsc-wrapped/src/tsc.js:86:9)
    at /opt/git/ionic2/node_modules/@angular/tsc-wrapped/src/main.js:33:23
    at process._tickCallback (internal/process/next_tick.js:103:7)
    at Module.runMain (module.js:577:11)
    at run (node.js:348:7)
    at startup (node.js:140:9)
    at node.js:463:3

this line shows

    if ((this.__AuthHttp_74 == (null as any))) { (this.__AuthHttp_74 = new import44.AuthHttp()); }

could you correct me?

Same issue as @theromis.

ALSO, if I try to use AUTH_PROVIDERS in the providers array for default configuration, I get node_modules/angular2-jwt/angular2-jwt"' has no exported member 'AUTH_PROVIDERS'.

ALSO, when I attempt to inject AuthHttp into a service class, I get .tmp/app/app.module.ngfactory.ts:493:117: Argument of type 'AuthHttp' is not assignable to parameter of type 'AuthHttp'

Here is the relevant code from app.module.ts

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    AuthHttp,
    AUTH_PROVIDERS,
  ]
})
export class AppModule {}

It's worth noting, this configuration WORKS when I run the app in the browser using Ionic Serve. There are NO errors.

The build only fails when I attempt to build to emulator or device.

Same problem as @theromis & @MattDHill :(

Just want to update I'm using 0.1.23 version, current 0.1.24 not in npm repo.
When I'm installing it as:
npm install [email protected]:auth0/angular2-jwt.git#a3d20932d4936ed383301afaec58f0945814acdd

it just don't see it at all:

[11:01:08]  ngc error: Error: Error at /root/work/1/ionic2/.tmp/providers/auth-service.ts:4:33: Cannot find module 'angular2-jwt'.
Error at /root/work/1/ionic2/.tmp/providers/auth-service.ts:5:27: Cannot find module 'angular2-jwt'.
Error at /root/work/1/ionic2/.tmp/services/auth/auth.ts:2:31: Cannot find module 'angular2-jwt'.
Error at /root/work/1/ionic2/.tmp/providers/admin-service.ts:4:26: Cannot find module 'angular2-jwt'.
Error at /root/work/1/ionic2/.tmp/providers/contacts-service.ts:5:26: Cannot find module 'angular2-jwt'.
Error at /root/work/1/ionic2/.tmp/providers/messages-service.ts:5:26: Cannot find module 'angular2-jwt'.
Error at /root/work/1/ionic2/.tmp/providers/notifications-service.ts:4:26: Cannot find module 'angular2-jwt'.
Error at /root/work/1/ionic2/.tmp/app/app.component.ts:4:29: Cannot find module 'angular2-jwt'.
Error at /root/work/1/ionic2/.tmp/app/app.module.ts:14:69: Cannot find module 'angular2-jwt'.
Error at /root/work/1/ionic2/.tmp/pages/room/room.ngfactory.ts:19:27: Cannot find module '../../../angular2-jwt'.
Error at /root/work/1/ionic2/.tmp/pages/people/people.ngfactory.ts:31:27: Cannot find module '../../../angular2-jwt'.
Error at /root/work/1/ionic2/.tmp/pages/contacts/contacts.ngfactory.ts:18:27: Cannot find module '../../../angular2-jwt'.
Error at /root/work/1/ionic2/.tmp/pages/tabs/tabs.ngfactory.ts:22:27: Cannot find module '../../../angular2-jwt'.
Error at /root/work/1/ionic2/.tmp/pages/profile-detail/profile-detail.ngfactory.ts:18:27: Cannot find module '../../../angular2-jwt'.
Error at /root/work/1/ionic2/.tmp/app/app.module.ngfactory.ts:51:27: Cannot find module '../../angular2-jwt'.
    at check (/root/work/1/ionic2/node_modules/@angular/tsc-wrapped/src/tsc.js:31:15)
    at Tsc.typeCheck (/root/work/1/ionic2/node_modules/@angular/tsc-wrapped/src/tsc.js:86:9)
    at /root/work/1/ionic2/node_modules/@angular/tsc-wrapped/src/main.js:33:23
    at process._tickCallback (internal/process/next_tick.js:103:7)
    at Module.runMain (module.js:592:11)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3


[11:01:08]  ngc error: Compilation failed

My error is different when trying to emulate:

[18:00:40]  ngc error: Error: can't find symbol undefined exported from module /Users/viegas/Faculdade/4/TIDIR/APP/Client/node_modules/angular2-text-mask/dist/angular2TextMask.d.ts, resolving symbol AppModule in /Users/viegas/Faculdade/4/TIDIR/APP/Client/.tmp/app/app.module.ts, resolving symbol AppModule in /Users/viegas/Faculdade/4/TIDIR/APP/Client/.tmp/app/app.module.ts
    at simplifyInContext (/Users/viegas/Faculdade/4/TIDIR/APP/Client/node_modules/@angular/compiler-cli/src/static_reflector.js:469:23)
    at StaticReflector.simplify (/Users/viegas/Faculdade/4/TIDIR/APP/Client/node_modules/@angular/compiler-cli/src/static_reflector.js:472:22)
    at StaticReflector.annotations (/Users/viegas/Faculdade/4/TIDIR/APP/Client/node_modules/@angular/compiler-cli/src/static_reflector.js:61:36)
    at _loop_1 (/Users/viegas/Faculdade/4/TIDIR/APP/Client/node_modules/@angular/compiler-cli/src/codegen.js:53:54)
    at CodeGenerator.readFileMetadata (/Users/viegas/Faculdade/4/TIDIR/APP/Client/node_modules/@angular/compiler-cli/src/codegen.js:66:13)
    at /Users/viegas/Faculdade/4/TIDIR/APP/Client/node_modules/@angular/compiler-cli/src/codegen.js:100:74
    at Array.map (native)
    at CodeGenerator.codegen (/Users/viegas/Faculdade/4/TIDIR/APP/Client/node_modules/@angular/compiler-cli/src/codegen.js:100:35)
    at codegen (/Users/viegas/Faculdade/4/TIDIR/APP/Client/node_modules/@angular/compiler-cli/src/main.js:7:81)
    at Object.main (/Users/viegas/Faculdade/4/TIDIR/APP/Client/node_modules/@angular/tsc-wrapped/src/main.js:30:16)

In my app.module I have:

import { AuthHttp, AUTH_PROVIDERS } from 'angular2-jwt';

[...]
providers: [
     ...
    AuthHttp,
    AUTH_PROVIDERS,
]

It also doesnt work with angular compiler when i run the command

ngc -p /path/to/tsconfig.ts

it shows: "Error: Error encountered resolving symbol values statically. Calling function 'provideAuth', function calls are not supported. Consider replacing the function or lambda with a reference to an exported function"

this is not a solution.
I need to put JWT configuration here.

export class AppModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: AppModule,
      providers: [
        { provide: AuthConfig, useValue: new AuthConfig({
          noJwtError: true,
          headerPrefix: 'JWT',
          globalHeaders: [{'Accept': 'application/json'}],
        })},
        {provide:XSRFStrategy, useValue: new CookieXSRFStrategy('csrftoken', 'X-CSRFToken')}
      ]
    };
  }
}

@theromis shouldn't you be providing AuthHttp instead of AuthConfig?

@sfabriece as long as both are provided it should be fine. Providing authConfig with useValue is slightly more concise than using a factory to provide authhttp

Thanks @escardin

@sfabriece But this code doesn't work for me with 0.1.23

This is how i'm doing mine. I haven't tested it with a production build.

I add the AuthProvider to the list of providers in the module.

export function AuthHttpFactory(http: any) {
  return new AuthHttp(new AuthConfig({
    tokenName: 'token',
    globalHeaders: [
      { 'Content-Type': 'application/json' },
      { 'Accept': 'application/json' }
    ],
  }), http);
}

export const authProvider = {
  provide: AuthHttp,
  useFactory: AuthHttpFactory,
  deps: [Http]
};

@sfabriece

  1. Where you passing authProvider ?
  2. This code located in the src/app/app.module.ts?

Please join the room via gitter app to handle a further conversation about this: https://gitter.im/angular2-jwt/Lobby?utm_source=share-link&utm_medium=link&utm_campaign=share-link

Having same issue as other people. The 'old' way to globally configure / bootstrap as seen below no longer functions. It would be helpful I think to update the main page of this repo with the latest 2.0 NgModule method. Thanks!

provide(AuthHttp, {
    useFactory: (http) => {
        return new AuthHttp(new AuthConfig({
            headerName: 'my-auth-token',
            tokenName: 'my-auth-token',
            tokenGetter: (() => localStorage.getItem('my-auth-token')),
            globalHeaders: [{ 'Content-Type': 'application/json' }],
            noJwtError: true,
            noTokenScheme: true
        }), http);
    },
    deps: [Http]
}),

Following works for me.

  provideAuth({
    // headerName: 'Authorization',
    // headerPrefix: 'Bearer',
    // tokenName: 'token',
    // tokenGetter: (() => localStorage.getItem('id_token')),
    globalHeaders: [{ 'Content-Type': 'application/json' }],
    noJwtError: true
  }),

Thanks @kodeine. Is adding that to the providers array of NgModule going to automatically tie togethter http / AuthHttp for every request? I am new to using this library but it looked as thought previously there was also a factory method defined.

@kodeine Following can not work because provideAuth doesn't works for ionic build any more, it works only for ionic serve

finally made stuff working for ionic2 rc0
with help of: https://github.com/ecureuill/Ionic2RC-Auth0
at least it compiles fine and I can trace the code
but it still not sending JWT token
I assume it because of changed storage mechanism

export function getXSRF() {
    return new CookieXSRFStrategy('csrftoken', 'X-CSRFToken');
}

export function getAuthHttp(http) {
    return new AuthHttp(new AuthConfig({
      noJwtError: true,
      headerPrefix: 'JWT',
      globalHeaders: [{'Accept': 'application/json'}],
    }), http);
}

@NgModule({
  imports: [
    IonicModule.forRoot(MyApp),
  ],
  providers: [
    AuthService,
    {
        provide: AuthHttp,
        useFactory: getAuthHttp,
        deps: [Http]
    },
    {
        provide: XSRFStrategy,
        useFactory: getXSRF,
    }
  ],
  declarations: [
    MyApp,
...
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
...
  ]
})

export class AppModule {}

attempt to put custom token getter doesn't helps, I assume it because of asynchronous response
may be somebody knows how to fix that?

var storage = new Storage();
function tokenGet() {
    storage.get('id_token').then(token => {
        console.log('id_token', token);
        return token;
    });
}

export function getAuthHttp(http) {
    return new AuthHttp(new AuthConfig({
      noJwtError: true,
      headerPrefix: 'JWT',
      globalHeaders: [{'Accept': 'application/json'}],
      tokenGetter: tokenGet,
    }), http);
}

ok
working function should be just:

var storage = new Storage();
function tokenGet() {
    return storage.get('id_token');
}

just clarifying my working solution:

var storage = new Storage();

export function getXSRF() {
    return new CookieXSRFStrategy('csrftoken', 'X-CSRFToken');
}

export function getAuthHttp(http) {
    return new AuthHttp(new AuthConfig({
      noJwtError: true,
      headerPrefix: 'JWT',
      globalHeaders: [{'Accept': 'application/json'}],
      tokenGetter: (() => storage.get('id_token')),
    }), http);
}

@NgModule({
  imports: [
    IonicModule.forRoot(MyApp),
  ],
  providers: [
    AuthService,
    {
        provide: AuthHttp,
        useFactory: getAuthHttp,
        deps: [Http]
    },
/*    {
        provide: XSRFStrategy,
        useFactory: getXSRF,
    }*/
  ],
  declarations: [
    MyApp,
...
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
...
  ]
})

export class AppModule {}

@theromis will it work with art compilation?

@lihaibh What is art compilation?

It works with prod and dev builds, what means working in ionic build and ionic serve

Please update README with new way! Thanks!

@theromis i mean AOT compilation (Ahead Of Time compilation with angular-compiler)

i got the main logins and authhttp working with this above.. now tokenNotExpired() seems to not be behaving correctly.. any thoughts? related to the localstorage change maybe?

Yeah, you need to get the token from storage manually and pass the token as
the SECOND argument in tokenNotExpired().

Your working flow works when you emulate or build?

On 6 Oct 2016 17:20, "chrishawn" [email protected] wrote:

i got the main logins and authhttp working with this above.. now
tokenNotExpired() seems to not be behaving correctly.. any thoughts?
related to the localstorage change maybe?


You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/auth0/angular2-jwt/issues/173#issuecomment-252076808,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AF5H8cmBoiYiL1OJWSMUyQ0gdd-Ecnnvks5qxVf2gaJpZM4KB2BT
.

@gfviegas yes only thing i had to do was comment out headerPrefix: 'JWT', because my backend doesn't use that

Thanks @theromis, adding this to the readme 👍

What is the recommend minimal woking solution to using this with ngc? It seems the underlying issue with IONIC is its use of the AOT compiler. I am facing the same issue on my plain angular2 project. Obviously, I don't have access to the ionic-storage, but I'm sure that can be easily replaced with session storage etc. however, is all the getAuthHttp stuff necessarily? I don't really understand what is going on here.

I have blindly changed the function to:

export function getAuthHttp(http: any) {
    return new AuthHttp(new AuthConfig({
      noJwtError: true,
      headerPrefix: 'JWT',
      globalHeaders: [{'Accept': 'application/json'}],
      tokenGetter: (() => sessionStorage.getItem('id_token')),
    }), http);
}

and it works in the compiler (haven't checked functionality yet). Is this all necessary for out-of0the0box functionality in a vanilla ng2 app using AOT compilation with ngc?

Looks like this duplicated #158 please reopen if it does not.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ciesielskico picture ciesielskico  ·  5Comments

kolkov picture kolkov  ·  3Comments

sfabriece picture sfabriece  ·  4Comments

Tirka picture Tirka  ·  3Comments

leosvelperez picture leosvelperez  ·  5Comments