Search code examples
angularapiangular6access-token

How to pass access-token in URL after login


I have created a login page, successfully logged in, and fetched an authorization-key, then stored it into local storage. Now, I want to pass the authorization-key in the URL, not in headers, to all requests made after login. How can I do that?


Solution

  • I created a stackblitz as an example to use the interceptor to add some params

    See https://stackblitz.com/edit/angular-jqs7wu

    Edit: added relevant code

    This is just a basic http request with 1 query param (QuestionService)

    fetchQuestions(topic: string): Observable<any[]> {
        const params = new HttpParams().append('intitle', topic);
    
        return this.http.get<any[]>("https://api.stackexchange.com/2.2/search", { params });
      }
    

    The Interceptor (QuestionInterceptor) adds some other params to the request before submitting it into network

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {    
        const params = req.params
          .append('pagesize', String(pagesize))
          .append('site', site)
          .append('order', order)
          .append('sort', sort); // append your auth key here instead of those params
    
        const cloneReq = req.clone({ params });
    
        return next.handle(cloneReq);
      }