angular2-jwt icon indicating copy to clipboard operation
angular2-jwt copied to clipboard

Angular 5 Issue No provider for InjectionToken JWT_OPTIONS!

Open danishmirza opened this issue 8 years ago • 14 comments

AppComponent.html:2 ERROR Error: StaticInjectorError(AppModule)[JwtHelperService -> InjectionToken JWT_OPTIONS]: StaticInjectorError(Platform: core)[JwtHelperService -> InjectionToken JWT_OPTIONS]: NullInjectorError: No provider for InjectionToken JWT_OPTIONS! at _NullInjector.get (core.js:994) at resolveToken (core.js:1292) at tryResolveToken (core.js:1234) at StaticInjector.get (core.js:1102) at resolveToken (core.js:1292) at tryResolveToken (core.js:1234) at StaticInjector.get (core.js:1102) at resolveNgModuleDep (core.js:10847) at _createClass (core.js:10884) at _createProviderInstance$1 (core.js:10858)

danishmirza avatar Jan 29 '18 06:01 danishmirza

In my case I had accidentally installed @auth0/angular-jwt instead of angular2-jwt. After mending the packages, everything worked perfectly.

jhotujec avatar Feb 03 '18 03:02 jhotujec

So I encountered this whilst trying to use JwtHelperService within a test spec. I am in the process of upgrading to Angular 5 from Angular 4 and switched to using auth/angular-jwt from angular2-jwt

Original TestBed setup was similar to

let jwtHelper: JwtHelperService;
    
    TestBed.configureTestingModule({
      providers: [
        JwtHelperService,
        AuthIdentityService
      ]
    });
    jwtHelper = TestBed.get(JwtHelperService);

I imported the module and defined the getter for the token

let jwtHelper: JwtHelperService;

    TestBed.configureTestingModule({
      imports: [JwtModule.forRoot({
        config: {
          tokenGetter: () => {
            return '';
          }
        }
      })],
      providers: [
        JwtHelperService,
        AuthIdentityService
      ]
    });
    jwtHelper = TestBed.get(JwtHelperService);

Note: my use case within my tests is to decode some tokens with known content jwtHelper.decodeToken(mockBearerTokenValue)

blakejolley avatar Feb 03 '18 13:02 blakejolley

Hey @blakejolley ,

Have you got any resolution even I am facing the similar issue while writing test cases for the service which includes "auth/angular-jwt".

bhanu499 avatar Feb 26 '18 11:02 bhanu499

I defined JwtHelper inside the constructor and it works: this.jwtHelper = new JwtHelperService();

jungleAl avatar Apr 10 '18 13:04 jungleAl

Is there any other suggestions to fix the problem? I have the similar problem and I could not fix it. I tried to add the options you propose here but no result...

brusevfourth avatar Jul 17 '18 11:07 brusevfourth

@inject it as a factory provider!

import { JwtHelperService as _JwtHelperService } from '@auth0/angular-jwt';

export const JwtHelperService  = {
  provide: _JwtHelperService,
  useFactory: () => {
    return new _JwtHelperService();
  }
};

Narrator avatar Jul 23 '18 18:07 Narrator

Can someone please tell any final fix for the issue?

akashdeepsinghal avatar Sep 15 '18 09:09 akashdeepsinghal

This fix is for @auth0/angular-jwt and not for angular2-jwt. Just as @blakejolley said, this comes after updating from angular2-jwt to @auth0/angular-jwt.

Here is the final fix for this issue. In your module, just add this :

export function getToken(): string {
    return localStorage.getItem('token');
}

@NgModule({
    imports: [
        JwtModule.forRoot({
            config: {
                tokenGetter: getToken
            }
        })
    ], 
    providers: [ 
        JwtHelperService
    ]
})

nohanna avatar Nov 05 '18 13:11 nohanna

@nohanna

Not sure what that code accomplishes. If I do it, then getToken is never invoked.

In fact, if I replace it with just this:

  imports: [
    JwtModule.forRoot({})
  ]

the effect is exactly the same.

vitaly-t avatar Nov 07 '18 05:11 vitaly-t

@vitaly-t Yes, the behavior is the same for me too. I wrote it just as the documentation did. But in my case, it is the same effect.

nohanna avatar Nov 09 '18 12:11 nohanna

I would expect that I don't need to import JwtModule into my module. Registering JwtHelperService in providers should be enough.

@NgModule({     
    providers: [ 
        JwtHelperService
    ]
})

In my case I decorated my service with providedIn: 'root'

@Injectable({ providedIn: 'root' })
export class AuthenticationService {
  // workaround
  private jwtHelper = new JwtHelperService();

  constructor(
    // private jwtHelper: JwtHelperService // injection doesn't work
  ) { }

ziomyslaw avatar Mar 13 '19 08:03 ziomyslaw

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If you have not received a response for our team (apologies for the delay) and this is still a blocker, please reply with additional information or just a ping. Thank you for your contribution! 🙇‍♂️

stale[bot] avatar Oct 26 '19 03:10 stale[bot]

If you want to use as a library for JWT manipulation on global app level without any injection of auth logic, you can inject as a factory in your app CoreModule

import { Injector, NgModule, Optional, SkipSelf } from '@angular/core';
import { JwtHelperService } from '@auth0/angular-jwt';


@NgModule({
  providers: [
    {
      provide: JwtHelperService,
      useFactory: () => new JwtHelperService()
    }
  ],
  imports: []
})
export class CoreModule {
  constructor(@Optional() @SkipSelf() private _core: CoreModule) {
    if (_core) {
      throw new Error('CoreModule is already loaded. Import it in the AppModule only!');
    }
  }
}

Usage in service or components:

import { Injectable } from '@angular/core';
import { JwtHelperService } from '@auth0/angular-jwt';

@Injectable({ providedIn: 'root' })
export class AuthenticationService {

  constructor(private _jwtHelper: JwtHelperService) {
  }
}

krekhovetskyi avatar Oct 15 '20 14:10 krekhovetskyi

Given below my error instruction : I want to go login page so pls anybody help me ERROR NullInjectorError: R3InjectorError(o)[InjectionToken HTTP_INTERCEPTORS -> [object Object] -> InjectionToken JWT_OPTIONS -> a -> a -> a]:

Murugansmegam avatar Oct 12 '22 10:10 Murugansmegam