Not able to pass JWT authorization using Angular8

Viewed 327

Below php api script given by client when I run into local then Static data storing in api server successfully.

<?php
    //creating payload parameters:
    $classTitle = 'Demo Class on 3rd April, 2020';
    $classInfo = 'This is a demo class scheduled to understand API';
    $classDateTime = '2020-11-12 11:30 AM';
    $timezone = 'Asia/Kolkata';
    $classDuration = 15;
    $classRecording = 'yes';
    $classAutoStart = false;
    $recordingAutoStart = false;
    $classVideoRes = 720;


    /*xyz.com*/
    $apiKey = '12345';
    $secretKey = '12345';

    // Create token header as a JSON string
    $header = json_encode(['alg' => 'HS256','typ' => 'JWT']); // ensure to place first alg part and next typ part

    // Create token payload as a JSON string
    $payload = json_encode(['classTitle' => $classTitle ,'classInfo' => $classInfo ,'classDateTime' => $classDateTime ,'timezone' => $timezone ,'classDuration' => $classDuration ,'classRecording' => $classRecording ,'classAutoStart' => $classAutoStart ,'recordingAutoStart' => $recordingAutoStart ,'classVideoRes' => $classVideoRes ,'apiKey' => $apiKey]);

    // 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, $secretKey , true);

    // Encode Signature to Base64Url String
    $base64UrlSignature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));

    // creating JWT token variable
    $jwt_token = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;

    // creating authorization varibale
    $authorization = 'Bearer '.$jwt_token;

    ?>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript">
        $.ajax
        ({
        type: "POST",
         url: 'https://xyz/client/schedule',
        contentType: 'application/json',
        data: JSON.stringify({
            "apiKey": "12345"
        }),
        dataType : 'json',
        headers: {
        'authorization': '<?php echo $authorization; ?>'
        },
        success: function(retval)
        {
        // alert(retval);
        console.log(retval);
        // var success = retval.success;
        }
        });
    </script>

Directly i pass parameters to above php api then also its not working, my senior told me you have to call above code from angular I wrote code but i am not able to store successfully below is my angular code.

Below is my model class

export class Schedule1 {

classTitle: string;
classInfo: string;
classDateTime: string;
timezone: string;
classDuration: number;
classRecording:string;
classAutoStart: boolean;
recordingAutoStart: boolean;
classVideoRes: number;
    
   constructor() {
    
      
   }

  }

Below is component.ts on button click passing static values

import { Schedule1 } from '../Models/Schedule1.model'


   Schedule1: Schedule1 = new Schedule1();

    addSchedule(scheduleForm: NgForm): void {

    //static data parameter passing
    this.Schedule1.classTitle='hi Class on 3rd April, 2020';
    this.Schedule1.classInfo= 'This is a demo class scheduled to understand API';
    this.Schedule1.classDateTime= '2020-11-12 11:30 AM';
    this.Schedule1.timezone= 'Asia/Kolkata';
    this.Schedule1.classDuration= 15;
    this.Schedule1.classRecording= 'yes';
    this.Schedule1.classAutoStart= false;
    this.Schedule1.recordingAutoStart= false;
    this.Schedule1.classVideoRes= 720;


    //const data = JSON.stringify(this.Schedule1);
    const data = { 
    apiKey: "dcbf187d-bdfe-431b-8f60-fa19bf51cd85", 
    data:  JSON.stringify(this.Schedule1)
    } 

    this.subscription = this.userSvc
    .fetchData("https: //xyz.com/client/schedule", data)
    .subscribe(
    data => {
    // Data on Success
    console.log("data", data);
    },
    error => {
    console.log("error", error);
    }
    );

    }

Below is service.ts

  fetchData(url: string, data: any): Observable<any> {
    const headers = {
    
    Authorization: "Bearer "+"1234",
     "My-Custom-Header": "foobar",
    contentType: "application/json"
    };

   return this.http.post(url, data, {
    headers
    });
   }

in console getting this error.

enter image description here

4 Answers

Can you please try the following changes in your code to check if it works:

First change:

 const data = this.Schedule1; 

Second change

 fetchData(url: string, data: any): Observable<any> {
    const headers = {
    
    Authorization: "Bearer "+"dcbf187d-bdfe-431b-8f60-fa19bf51cd85",
     "My-Custom-Header": "foobar",
    contentType: "application/json"
    };

   return this.http.post(url, data, {
    headers
    });
   }

I think you need to define the type of request option that you passing to request so you have to use

return this.http.post(url, data, headers: new HttpHeaders({
   'Content-Type':  'application/json',
   'My-Custom-Header': 'foobar',
   Authorization: 'my-auth-token'
}));`

also, you need to import HttpHeaders

import { HttpHeaders } from '@angular/common/http';

Try using unblock cors extension on your browser and check it again

you are getting this error 'https ://xyz.com/client/schedule' from origin 'localhost:4200' has been blocked by CORS policy because server and client is running on different host, either you have to run server locally or try this,

open chrome using this command and check browser network tab

chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

image

Did you try to setup a config file "src/proxy.conf.json"

{
    "/api/*": {
       "target": "http://localhost:4200",
       "secure": false,
       "logLevel": "debug"
    }
}

and have your "angular.json" point to the config file

"architect": {
  "serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
      "browserTarget": "your-application-name:build",
      "proxyConfig": "src/proxy.conf.json"
    },

this will only be for testing purposes (since you have no access to the server, right ?)

Related