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

Authorisation not sent (possibly whitelist issue)

Open eddiejaoude opened this issue 8 years ago • 29 comments

Exactly the same issue as here https://github.com/auth0/angular2-jwt/issues/464

It was closed because he ditched auth0 however, that is not an option for us.

Locally it works locally with http using whitelist: ['localhost:3000'], how when deployed on https, with or without the port in the whitelist it fails whitelist: ['api.server.com:443']

eddiejaoude avatar Feb 01 '18 19:02 eddiejaoude

I got this to work by changing from the default setup...

JwtModule.forRoot({
      config: {
        tokenGetter: () => {
          return localStorage.getItem('access_token');
        },
        whitelistedDomains: [environment.whitelist]
      }
    }),

to the custom setup...

export function jwtOptionsFactory() {
  return {
    tokenGetter: () => {
      return localStorage.getItem('access_token');
    },
    whitelistedDomains: environment.whitelist
  }
}

JwtModule.forRoot({
          jwtOptionsProvider: {
            provide: JWT_OPTIONS,
            useFactory: jwtOptionsFactory
          }
        }),

Where environment is...

export const environment = {
  production: true,
  api: 'https://example.io',
  whitelist: ['example.io', 'https://example.io', 'example:443'],
  version: 'x.x.x',
};

Shortly, I will investigate further to understand more, but hopefully that helps someone.

eddiejaoude avatar Feb 02 '18 07:02 eddiejaoude

I'm also getting this problem and can confirm using the factory fixes it.

Angular CLI: 1.6.4
Node: 8.9.4
OS: win32 x64
Angular: 5.2.0
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

@angular/cli: 1.6.4
@angular-devkit/build-optimizer: 0.0.37
@angular-devkit/core: 0.0.24
@angular-devkit/schematics: 0.0.45
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.9.4
@schematics/angular: 0.1.12
typescript: 2.5.3
webpack: 3.10.0

cwmrowe avatar Feb 08 '18 09:02 cwmrowe

Even that my solution above didn't work correctly, not sure what changed.

I reverted back to the older version with using two http clients...

export function authHttpServiceFactory(http: Http, options: RequestOptions) {
  return new AuthHttp(new AuthConfig({
    tokenGetter: (() => localStorage.getItem('access_token')),
    globalHeaders: [{'Content-Type':'application/json'}]
  }), http, options);
}
{
     provide: AuthHttp,
     useFactory: authHttpServiceFactory,
     deps: [Http, RequestOptions]
}

eddiejaoude avatar Feb 08 '18 09:02 eddiejaoude

Maybe it is connected to this issue: from the documentation, if whitelistedDomains is not specified, it should work if the request is made to the same serving domain. From this code, taken from jwt.interceptor.js :

JwtInterceptor.prototype.isWhitelistedDomain = function (request) {
        var requestUrl;
        try {
            requestUrl = new URL(request.url);
            return (this.whitelistedDomains.findIndex(function (domain) {
                return typeof domain === 'string'
                    ? domain === requestUrl.host
                    : domain instanceof RegExp ? domain.test(requestUrl.host) : false;
            }) > -1);
        }
        catch (err) {
            // if we're here, the request is made
            // to the same domain as the Angular app
            // so it's safe to proceed
            return true;
        }
    };

looks like if whitelistedDomains is empty, it will always return -1 thus the request will be forbidden (the condition > -1 will never be true).

EDIT: This should fix the issue?

return (this.whitelistedDomains.length > 0? this.whitelistedDomains.findIndex(function (domain) {
                return typeof domain === 'string'
                    ? domain === requestUrl.host
                    : domain instanceof RegExp ? domain.test(requestUrl.host) : false;
            }) > -1 : window.location.hostname === requestUrl.hostname);

FDN73 avatar Feb 08 '18 11:02 FDN73

I have the same issue than @eddiejaoude. I need to parametrize the whitelistedDomains with the current location, but I can't figure out the way.

elfrasco avatar Mar 12 '18 16:03 elfrasco

If you leave the whitelist empty the isWhitelistedDomain method will always return false. It will never match anything, and hence never send the authorization headers. (This is contrary to the documentation, which implies that having an empty whitelist will match local domain requests.)

Workaround - If you use domain-less routes, the workaround is to add the null domain to the whitelist, which you can do through a RegExp. In other words, do this:

whitelistedDomains: [  /^null$/  ]

1619digital avatar Mar 15 '18 12:03 1619digital

@PartyArk Your workaround does not work for me. This is the error that I am getting because of the regex:

ERROR in app\app.module.ts(97,11): Error during template compile of 'AppModule'
  Expression form not supported.

tobiasetter avatar Mar 29 '18 07:03 tobiasetter

@PartyArk thank you! This worked for us.

david-poindexter avatar Apr 01 '18 16:04 david-poindexter

whitelistedDomains makes direct comparation between the domain and the requestUrl.host, so is comparing for example 'localhost' === 'localhost:80' --> always false

i changed ( domain === requestUrl.host) to (domain === requestUrl.host.split(':')[0]) , dont need to put obvious things like the 80 port.

I think it puts de port in the string when you are for example in port 4200 and the server is in 80.

source: @auth/angular-jwt/src/jwt.interceptor.js

Sorry if what i did is dumb, i am still learning. Sorry too for my english.

Here is the original code:

JwtInterceptor.prototype.isWhitelistedDomain = function(request) { var requestUrl = URL.parse(request.url, false, true); return ( this.whitelistedDomains.findIndex(function(domain) { return typeof domain === 'string' ? domain === requestUrl.host <-- Here is the "problem" (at least in my context) : domain instanceof RegExp ? domain.test(requestUrl.host) : false; }) > -1 ); };

jorgellose avatar Apr 01 '18 22:04 jorgellose

Over 2 months and still no official solution 😞. Is this project dead?

eddiejaoude avatar Apr 02 '18 09:04 eddiejaoude

Here is a work around to monkey patch the interceptor and send authorization headers to relative URLs where the host is null. I import it from my main.ts.

import { JwtInterceptor } from '@auth0/angular-jwt';
import { HttpRequest } from '@angular/common/http';
import * as URL from 'url';

// https://github.com/auth0/angular2-jwt/issues/481
if (JwtInterceptor.prototype['_isWhitelistedDomain'] == null) {
    JwtInterceptor.prototype['_isWhitelistedDomain'] = JwtInterceptor.prototype.isWhitelistedDomain;

    // send tokens to null host (the server that originated the app)
    JwtInterceptor.prototype.isWhitelistedDomain = function isWhitelistedDomain(request: HttpRequest<any>): boolean {
        const requestUrl = URL.parse(request.url, false, true);
        if (requestUrl.host === null) {
            return true;
        }
        return this['_isWhitelistedDomain'](request);
    };
}

kalahari avatar Apr 06 '18 15:04 kalahari

There is an issue about whitelisting urls without host: #518

tobiasetter avatar Apr 19 '18 06:04 tobiasetter

Updated 5/2/18 - Modified jwtConf.whitelistedDomains

I had this issue today as well. I used a combination of the solutions above. I'm teetering on being redundant here, but hopefully my thorough solution below is worth it :)

// app.module.ts

// Put the tokenGetter function at the top of app.module.ts rather than inside of .forRoot
export function tokenGetter() {
  return localStorage.getItem('access_token');
};

// Declare a variable that utilized tokenGetter. Use /^null$/ for whitelistedDomains as an alternative to an empty array
const jwtConf = {
  config: {
    tokenGetter: tokenGetter,
    whitelistedDomains: new Array(new RegExp('^null$')),
    throwNoTokenError: true
  }
};

// use the variable inside of .forRoot
...
  imports: [
    HttpClientModule,
    JwtModule.forRoot(jwtConf),
...

dapperdandev avatar Apr 19 '18 17:04 dapperdandev

When I raised this issue, I think I was using a beta or a RC, is this still an issue now a v1.1 (master branch) has been released?

eddiejaoude avatar Apr 24 '18 23:04 eddiejaoude

Same issue for me. the whitelistedDomains: [ /^null$/ ] didn't work for me. I a using a urlRewrite can this have anything to do this with?

tbadlov avatar Apr 25 '18 19:04 tbadlov

@eddiejaoude: Verified that I'm n 1.1.0. Still an issue.

dapperdandev avatar Apr 25 '18 20:04 dapperdandev

@tbadlov: I couldn't get it to solely by whitelisting [ /^null$/ ]. I had to declare the tokenGetter() function outside of the .forRoot() method and declare the jwtConf variable.

So my code references the jwtConf varable from the .forRoot() method, then the jwtConf variable has the .config.tokenGetter property that references the tokenGetter() function.

dapperdandev avatar Apr 25 '18 21:04 dapperdandev

In dev mode the /^null$/ regex, works, but not when running in --aot mode.

Expression form not supported 

eddiejaoude avatar Apr 25 '18 23:04 eddiejaoude

From another issue, here is a solution to the above comment that works with --aot.

whitelist: new Array(new RegExp('^null$'))

eddiejaoude avatar Apr 26 '18 00:04 eddiejaoude

It doesn't work, using IIS to serve angular with URL Rewrite to call Express (using the same IIS server with IISNode). I had to use the solution provided by this comment. But essentially, it is not using the library which sucks.

tbadlov avatar Apr 26 '18 01:04 tbadlov