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

1.0.0-beta.10: Failed to construct 'URL': Invalid URL

Open ghost opened this issue 8 years ago • 30 comments

with beta 9 everything was working fine but with beta10 i get now: Failed to construct 'URL': Invalid URL url example: /api/v1/system/mode (same server)

JwtModule.forRoot({
      config: {
        tokenGetter: tokenGetter,
        whitelistedDomains: ['localhost']
      }
    }),
export function tokenGetter() {
  return localStorage.getItem(Configuration.AUTH_TOKEN_ID);
}

This issue is caused by the changes on src/jwt.interceptor.ts in pull request #438 const requestUrl = new URL(request.url); will not accept relative urls. It has to be new URL(relative, base) or new URL(full-url)

ghost avatar Jan 30 '18 14:01 ghost

+1

laran avatar Jan 31 '18 05:01 laran

I have the same error. Beta 9 works.

jameskentTX avatar Jan 31 '18 14:01 jameskentTX

same issue

miguelcaravantes avatar Jan 31 '18 18:01 miguelcaravantes

Any word on this? Did you find any work-arounds @DaveXCS ? I have an interceptor that makes it a full url, but unfortunately it looks like the jwt interceptor is first in the chain and i don't seem to be able to change it so my interceptor is first.

cmcclellen avatar Feb 08 '18 20:02 cmcclellen

same issue

fititrick avatar Feb 12 '18 08:02 fititrick

The current workaround is to use full url or use beta9. The author of the pull request has the opinion that a crashing or non working application is better than an unsafe application. I would personally prefer to make it safe and working but it seems they have different understanding about that :-)

ghost avatar Feb 12 '18 08:02 ghost

@DaveXCS Unfortunately, I don't get it working. Maybe it's an issue because I'm using the Ionic Framework (3.9.2)? At the moment, I'm doing this:

whitelistedDomains: [new URL('http://localhost:1337'), new URL('https://api.myurl.com')]

But the same Error: TypeError: Failed to construct 'URL': Invalid URL

With beta.9 it was:

whitelistedDomains: ['localhost:1337', 'api.myurl.com']

Mike1707 avatar Feb 12 '18 09:02 Mike1707

The problem is not the url of the whitlisted domains. The problem is if you send any request with the angular http service e.g.: this.http.get('/api/values', httpOptions) will not work but this.http.get('http://localhost:3030/app/api/values', httpOptions) will work. Beta9 had a try catch around const requestUrl = new URL(request.url); So in the case of a relative url the error 'Invalid URL' was catched with an empty catch block. In Beta10 they removed the try/catch and now relative url requests are no longer working (which is the default on most of the application). Beta9:

 isWhitelistedDomain(request: HttpRequest<any>): boolean {
     let requestUrl: URL;
     try {
       requestUrl = new URL(request.url);
       return (
         this.whitelistedDomains.findIndex(
           domain =>
             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;
     }

The second options is not to use this http interceptor at all and manually add the token in every request (add "Authentication: Bearer token" to the header in the http options)

ghost avatar Feb 12 '18 10:02 ghost

That's very interesting since I'm totally sure I just use full URLs in all of my requests.

Mike1707 avatar Feb 12 '18 10:02 Mike1707

At the point the interceptors are called, how do you ever know the full path? I want an application to be able to work on dev, test, prod servers and domain names might change so I never want any specific domain hard coded. I suppose I need to make a non-intercepted request first to get the baseUrl of the deployment and then use that?

mjb1632 avatar Feb 14 '18 20:02 mjb1632

you could do here sth like -> if request.url starts with '/' (or regex expression) and whitlisted domains contain 'localhost' -> return true so you don't need the full url.

btw you can write your own interceptor instead of the angular-jwt interceptor sth like that:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(public auth: AuthService) {}
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${this.auth.getToken()}`
      }
    });
    return next.handle(request);
  }
}

ghost avatar Feb 15 '18 06:02 ghost

There are also cases where it's impossible to know the full URL in advance (the final prod host name is unknown at development time). I think the library has to allow for relative URLs.

brian428 avatar Feb 22 '18 17:02 brian428

Could we just replace the creation of the url by this :

var requestUrl = new URL(request.url, /^https?:\/\//i.test(request.url) ? undefined : window.location.href)

in the mean time, open the file in the node_module jwt.interceptor.js and replace the faulty line by what i proposed and it should work.

image

Sambaja avatar Feb 27 '18 02:02 Sambaja

Same issue here.

Sample URL: "./assets/i18n/en.json"

anibalsanchez avatar Mar 10 '18 15:03 anibalsanchez

Why hasn't this been addressed before the final release?

dushkostanoeski avatar Mar 11 '18 10:03 dushkostanoeski

@Sambaja we are using this library under {N}ativeScript on iOS / Android. I'd prefer the fix in #489 if possible.

noumaans avatar Mar 11 '18 18:03 noumaans

Hi everybody,

I was dealing with exactly the same issue after updating to 1.0.0, even if I was already using absolute URLs in all of my requests. After investigating, I realized that the problem was coming from the custom factory of the translation package TranslateModule.

export function TranslateFactory(http: HttpClient): TranslateHttpLoader {

    return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}

And this is how I fixed it.

export function TranslateFactory(http: HttpClient): TranslateHttpLoader {

    return new TranslateHttpLoader(http, location.origin + '/assets/i18n/', '.json');
}

Hope this will be helpful!

ghost avatar Mar 12 '18 11:03 ghost

That's right. It's a very good solution by the moment. Thank you so much!!

jualoppaz avatar Mar 12 '18 14:03 jualoppaz

Same issue :(

Meanwhile I had to do a downgrade to 1.0.0-beta.9 version.

elfrasco avatar Mar 12 '18 19:03 elfrasco

Same issue :(

Meanwhile I had to do a downgrade to 1.0.0-beta.9 version.

ydemir avatar Mar 12 '18 20:03 ydemir