1

I have an angular 9 application + spring service which are authenticated against keycloak. The problem is that i want to open the spring swagger link in a new tab from the angular ui. Currently I am trying to add the bearer token to the authorization header when calling the url, but without much luck.

This is a snippet of what i am trying

var currentUserObject = JSON.parse(sessionStorage.getItem('currentUser'));

this.http.get(this.swaggerUrl, {
    headers: new HttpHeaders({
      'Authorization': 'Bearer ' + currentUserObject.access_token
    })
  }).subscribe(() => window.location.href=this.swaggerUrl)
}
  • Yeah this won’t work (not anything to do with Angular). Does it not support cookies for auth? – MikeOne Aug 05 '22 at 14:55

2 Answers2

1

I use this lib in my Angular apps to handle user authentication and Bearer tokens header (access-token refreshing, automaticaly add Authorization header to configured routes, etc.)

Also, this is not directly related but if your API is documented with Swagger, have you considered using OpenAPI generator to generate an Angular client lib? It exposes very convenient services to query your API.

ch4mp
  • 6,622
  • 6
  • 29
  • 49
1

I don't think this is possible. window.open nor any other means to open a link will support setting headers. As this would be a security flaw in the browser. In any case, if a server would expect something to be a parameter, it would accept it as a GET/POST param or maybe a cookie (this one needs same origin).

This is what I would do:

  1. If I control the server: Accept the token as query string param, then set it as cookie in the response.

  2. If I don't control the server: Create a proxy script (with Express for instance), that would sit between you and the server.

  3. If you only want to open a single page, like a doc page or something, without navigation, then just create a new page in your angular app that would load the swagger doc using HttpClient or fetch and render the contents inside some div. Then open that page in new tab with windows.open. This would be an example:

    const routes = [
      ...
      {path: 'view-swagger', component: ViewSwaggerComponent}, // Pass params to this route to load the right swagger resource.
      ...
    ]
    
Abraham Toledo
  • 401
  • 4
  • 8