I am trying to use JWT with angular 5 and PHP to generate a token. For testing reasons, I encrypted the userid
variable using CryptoAESJs
library and send it via post
method to php script:
getToken()
{
let userid = 123;
let key = "coded";
let encUserID = crypto.AES.encrypt(userid, key);
const headerOptions = new HttpHeaders().set
('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
const params = new HttpParams().set('userID', encUserID);
this.http.post('http://aff.local/jwtTest.php', params, {
headers: headerOptions,
responseType: 'json'
}).subscribe(
res=>{
console.log(res);
},
error=>{
console.log(error);
}
)
}
I send it to the PHP script:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application\JSON');
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS');
header('Access-Control-Allow-Headers: *');
error_reporting(E_ALL);
require_once "CryptoJSAES.php";
require_once('JWT.php');
ini_set('log_errors', 0);
ini_set('display_errors', 1);
$key = "coded";
$id = $_POST['userID'];
$token = CryptoJSAES::decrypt($id,$key);
$jwt = JWT::encode($token, $key);
$jwtDecode = JWT::decode($jwt, $key, array('HS256'));
echo json_encode($jwtDecode);
?>
Inside my app.component.html
, I added a button:
<button mat-raised-button (click)='getToken()'>Click Me</button>
So run the getToken()
method when click event is fired.
Once clicked, I got the following error at the console:
ERROR RangeError: Invalid array length
at WordArray.init.clamp (core.js:272)
at WordArray.init.concat (core.js:237)
at Object.pad (cipher-core.js:415)
at Object._doFinalize (cipher-core.js:492)
at Object.finalize (cipher-core.js:163)
at Object.encrypt (cipher-core.js:675)
at Object.encrypt (cipher-core.js:833)
at Object.encrypt (cipher-core.js:201)
at AppComponent.push../src/app/app.component.ts.AppComponent.getToken (app.component.ts:20)
at Object.eval [as handleEvent] (AppComponent.html:1)
Is it a problem with material ? Or with the browser ? Or it is a problem with the value sent from Angular to PHP ?
EDIT
//Imports
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import * as crypto from 'crypto-js';