1

Angular2 Typescript application is generating source .js files.

While debugging I observed that the authorization header is undefined.

I have jwt token for custom services defined.

How can I apply the same jwt token to generated Angular2 source .js files?

jwpfox
  • 5,124
  • 11
  • 45
  • 42
HydTechie
  • 797
  • 10
  • 17
  • check this out for setting up token in http header http://stackoverflow.com/questions/34464108/angular2-set-headers-for-every-request – Sriram Nov 29 '16 at 09:53
  • Your question is not very clear, there's no code ... You're gonna have to give us more than a bounty to help you ;) – maxime1992 Nov 29 '16 at 12:53
  • Hi Guys, my question is around - the security of code(ts/js) files- if any browser asks for the generated code(ts/js), this security should be applied, may be redicted to login, if no jwt token present. – HydTechie Dec 01 '16 at 09:45

2 Answers2

1

The thing is not related to generated js files. The easiest, fastest and most comfortable solution is to use npm module angular2-jwt.

  • Install the modulenpm install angular2-jwt.
  • Configure your app.module.ts like this:

    import { AUTH_PROVIDERS } from 'angular2-jwt';
    @NgModule({
      ...
    
      providers: [
        AUTH_PROVIDERS
      ],
    
      ...
    })
    
  • Then use it everywhere you want in your app by:

    import { AuthHttp } from 'angular2-jwt';
    this.authHttp.get('http://example.com/api/thing')
      .subscribe(
        data => this.thing = data,
        err => console.log(err),
        () => console.log('Request Complete')
      );
    

That way your requests would be authenticated if you have your token in a cookie named id_token. If you want to store your token by another method (localStorage, indexedDb...) please, refer to the module's documentation (https://github.com/auth0/angular2-jwt#configuration-options) on how to change it, but it is fairly easy. If you need it I can explain it right here.

Hope it helps.

Jorge
  • 540
  • 6
  • 21
0

As far as I understand from your short post, you just want to send the token in http request header. I use the same strategy on my applications and I don't use any extra module.

I have an authentication request and I store my token on localStorage:

this.http.post('/login', userCredentials).subscribe(
    token => localStorage.addItem('Authorization', token),
    error => this.handleError(error)
)

Then I just get the token from localStorage and use it in my requests headers:

let options = { headers: new Headers() };   
let jwt = localStorage.getItem('Authorization');
options.headers.append('Authorization', jwt); 

return this.http.get('/api/request', options)
           .map(result => result.json());

In my opinion, angular2-jwt is useful if you want to decode your jwt.

Patriicya
  • 158
  • 2
  • 10