title: Angular 6 do I have to generate jwt in client to match server or just the server
body: <p>I am a total newbie to jwt and I thank you for your patience.</p>
  
  <p>I am generating jwt in PHP with the following:</p>
  
  <pre><code>// Create token header as a JSON string
  $header = json_encode(['typ' =&gt; 'JWT', 'alg' =&gt; 'HS256']);
  
  // Create token payload as a JSON string
  $payload = json_encode(['username' =&gt; $this-&gt;username, 'password' =&gt; $this-&gt;password]);
  
  // Encode Header to Base64Url String
  $base64UrlHeader = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
  
  // Encode Payload to Base64Url String
  $base64UrlPayload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));
  
  // Create Signature Hash
  $signature = hash_hmac('sha256', $base64UrlHeader . "." . $base64UrlPayload, '&lt;big secret&gt;', true);
  
  // Encode Signature to Base64Url String
  $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));
  </code></pre>
  
  <p>All of that was just to generate the signature - $base64UrlSignature - which is then set to the key:</p>
  
  <p>$this->key = $base64UrlSignature;</p>
  
  <pre><code>        $token = array(
              "iss" =&gt; $this-&gt;iss,
              "aud" =&gt; $this-&gt;aud,
              "iat" =&gt; $this-&gt;iat,
              "nbf" =&gt; $this-&gt;nbf,
              "data" =&gt; array(
                  "username" =&gt; $this-&gt;username,
                  "password" =&gt; $this-&gt;password
                  )
          );
  
          // generate jwt
          $this-&gt;jwt = JWT::encode($token, $this-&gt;key);
          echo json_encode(
              array(
                  "status" =&gt; 401,
                  "id" =&gt; 0,
                  "uName" =&gt; "Guest",
                  "isAdmin" =&gt; "0",
                  "ts" =&gt; "2018-12-28 00:00:00",
                  "loggedIn" =&gt; false,
                  "msg" =&gt; "Combination of username and password not found",
                  "jwt" =&gt; $this-&gt;jwt
              )
          );
  </code></pre>
  
  <p>My question is, do I have to do the same on the client side in Angular, to see if it matches with the one generated by the server?</p>
  
  <p>So far all that I have read, has to do with the server generating the jwt, then in Angular do the following:</p>
  
  <pre><code>localStorage.setItem("jwt", res.jwt);
  </code></pre>
  
  <p>Just place in local storage. Is that all there is to it?</p>
  
  <p>Shouldn't there be a comparison of the token generated by the server to the token generated by the client?</p>
  
  <p>If so, then how do I translate the above code to do so? For instance, what is the equivalent in Angular to Google's jwt PHP class:</p>
  
  <pre><code>$this-&gt;jwt = JWT::encode($token, $this-&gt;key);
  </code></pre>
  
  <p>I am adding code to the original post. The following is the interceptor that I have made:</p>
  
  <pre><code>import { ShoppingCartValuesService } from "./shopping-cart-values.service";
  import { Injectable, Injector } from "@angular/core";
  import {
    HttpEvent,
    HttpInterceptor,
    HttpHandler,
    HttpRequest
  } from "@angular/common/http";
  import { Observable } from "rxjs/";
  import * as jwt_decode from "jwt-decode";
  
  @Injectable()
  export class AuthInterceptor implements HttpInterceptor {
    constructor(public srvc: ShoppingCartValuesService) {}
    intercept(
      req: HttpRequest&lt;any&gt;,
      next: HttpHandler
    ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
      const idToken = localStorage.getItem("jwt");
  
      if (idToken) {
        const cloned = req.clone({
          headers: req.headers.set("Authorization", "Bearer " + idToken)
        });
        console.log("Decoded jwt token: ", this.getDecodedAccessToken(idToken));
        return next.handle(cloned);
      } else {
        return next.handle(req);
      }
    }
  
    getDecodedAccessToken(token: string): any {
      try {
        return jwt_decode(token);
      } catch (error) {
        console.log("error: ", error);
        return false;
      }
    }
  }
  </code></pre>
  
  <p>Which is called anytime a click is made in the links of the navbar via the click handler checkRequest() that is passed the route and later prepends the entire URL:</p>
  
  <pre><code>  &lt;li class="nav-item"&gt;
      &lt;a
        class="nav-link"
        data-toggle="tooltip"
        title="Products"
        routerLink="/products"
        id="products"
        (click)="checkRequest('/products')"
        &gt;&lt;span&gt;Products&lt;/span&gt;&lt;/a
      &gt;
    &lt;/li&gt;
  </code></pre>
  
  <p>Modifying post once again to show console.log result from the (click)="checkRequest('/products');</p>
  
  <p>CheckRequest method:</p>
  
  <pre><code>checkRequest(url) {
  const newUrl = this.srvc.serverBase + url;
  this.clickResponse = this.http.get(newUrl, { observe: "body" });
  console.log(
    "newUrl: " +
      newUrl +
      " this.clickResponse: " +
      JSON.stringify(this.clickResponse)
  );
  </code></pre>
  
  <p>}</p>
  
  <p>From console.log when clicking the '/products' link:</p>
  
  <pre><code>newUrl: http://local.kronus:8001/products this.clickResponse: {"_isScalar":false,"source":{"_isScalar":false,"source":{"_isScalar":false,"source":{"_isScalar":true,"value":{"url":"http://local.kronus:8001/products","body":null,"reportProgress":false,"withCredentials":false,"responseType":"json","method":"GET","headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"params":{"updates":null,"cloneFrom":null,"encoder":{},"map":null},"urlWithParams":"http://local.kronus:8001/products"}},"operator":{"concurrent":1}},"operator":{}},"operator":{}}
  </code></pre>
  
  <p>The interceptor does not seem to be producing anything. Is there something that I missing to include the interceptor somehow?</p>
  
  <p>Another update: after some more reading, I realized that I need to inject the interceptor into my login service:</p>
  
  <pre><code>private authInt: AuthInterceptor
  </code></pre>
  
  <p>Also, I added to the login service:</p>
  
  <pre><code>clickResponse: Observable&lt;any&gt;;
  </code></pre>
  
  <p>I moved the checkRequest method to the login service:</p>
  
  <pre><code>checkRequest(url) {
    const newUrl = this.appBase + url;
    return (this.clickResponse = this.http.get(newUrl, { observe: "body" }));
  }
  </code></pre>
  
  <p>In the navbar component, I changed the method to the following calling the service's checkRequest:</p>
  
  <pre><code>checkRequest(url) {
  this.srvc.checkRequest(url).subscribe(data =&gt; {
    console.log("after clicking login: ", data);
  });
  }
  </code></pre>
  
  <p>Here is the 404 error in the console:</p>
  
  <pre><code>    HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: "Not Found", url: "http://localhost:4200/login", ok: false, …}
  error: "&lt;!DOCTYPE html&gt;↵&lt;html lang="en"&gt;↵&lt;head&gt;↵&lt;meta charset="utf-8"&gt;↵&lt;title&gt;Error&lt;/title&gt;↵&lt;/head&gt;↵&lt;body&gt;↵&lt;pre&gt;Cannot GET /login&lt;/pre&gt;↵&lt;/body&gt;↵&lt;/html&gt;↵"
  headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
  message: "Http failure response for http://localhost:4200/login: 404 Not Found"
  name: "HttpErrorResponse"
  ok: false
  status: 404
  statusText: "Not Found"
  url: "http://localhost:4200/login"
  </code></pre>
  
  <p>How is it possible that /login is not found? I am literally on the login page. Is it because this checked before the app made the login page?</p>
  
  <p>This is when I realized that I do not need to send '/login' but the uri to the api, which produced no errors, but no jwt in the headers either. I tried to do the same thing on admin/products page, which the following line seems to just return the payload coming from the api:</p>
  
  <pre><code>return (this.clickResponse = this.http.get(newUrl, { observe: "body" }));
  </code></pre>
  
  <p>Yet, I do not see anything in the headers section that jwt Authorization Bearer is passed. What am I missing?</p>
  
  <p>Thanks in advance</p>