2

I am using Angular 9. I would like to do something similar to this, but do not want to expose the token because of security reasons.

<a href="https://url?jwt=xxx">

or

window.location.href = "https://url?jwt=xxx";

So because these two options are not a good idea, is there a way to redirect to a url and add the token to the header? Or is there another viable way?

More info:

In my use case, I would like to redirect the user to a different url. In order to access the url, the server hosting it requires the jwt to authenticate the user.

Richard
  • 8,193
  • 28
  • 107
  • 228

2 Answers2

2

YOu should not send your JWT in the URL. Instead, you can add your token to the windows.localstorage. Like this

localStorage.setItem('token', jwt);

or

$window.localStorage.token = JSON.stringify(jwt);

Refer https://stackoverflow.com/a/44209185/8826642

Refer https://stackoverflow.com/a/44320933/8826642

theWellHopeErr
  • 1,856
  • 7
  • 22
  • 1
    Hi @theWellHoper, thanks for the answer, but this is is not what I was asking. I know I must not expose the token. I would like to redirect to another url and pass the token securely. I don't need to store the token on the browser, but rather pass it to the location I need to redirect to (i.e. the server). So if I can set it in the header for example, that would be a viable option (but I am not sure if that is possible). – Richard Dec 08 '20 at 06:30
0

To navigate in angular 2 and add query params

In HTML:

<a [routerLink]="['urlToNavTo']" [queryParams]="{jwt: tokenValue}"> link title </a>

Or in the TS of the component:

import {Router} from "@angular/router"

constructor(private router: Router) {}

this.router.navigate(['urlToNavTo'], {queryParams: {jwt: tokenValue}});

Hope this is what you needed.

TomerAgmon1
  • 295
  • 3
  • 10
  • thanks for the answer. However, will this not expose the parameter in the url? – Richard Dec 08 '20 at 07:17
  • It is, but it's always exposed (even in the header), that's why it's encrypted. Saving it in local storage won't help if you switch domains. Other option is to send across a session id (managed in the server) – TomerAgmon1 Dec 08 '20 at 07:26
  • What's your opinion on adding a cookie with the token, and then the server reads the cookie? – Richard Dec 08 '20 at 07:27
  • server reading the cookie? I could be mistaken but cookies are for the client. how would you make the server access that? – TomerAgmon1 Dec 08 '20 at 07:29
  • In Java you can do this: `Cookie[] cookies = request.getCookies();` – Richard Dec 08 '20 at 07:35