angular2 with Slim framework jwt authentication - php

I am trying to create a survice to authenticate user name and password in angular2.
Here is the code for authentication.service.ts
import { Injectable } from '#angular/core';
import { Http, Headers, Response } from '#angular/http';
import { Observable } from 'rxjs';
import {Md5} from 'ts-md5/dist/md5';
export interface User {
userName: string;
password: string; }
#Injectable()
export class AuthenticationService {
public token: string;
constructor(private http: Http) {
// set token if saved in local storage
var currentUser = JSON.parse(localStorage.getItem('currentUser'));
this.token = currentUser && currentUser.token;
}
login(user:User): Observable {
return this.http.post('http://localhost/hj1/api/authenticate',
JSON.stringify({ 'user': user.userName, 'password': Md5.hashStr(user.password) }))
.map((response: Response) => {
// login successful if there's a jwt token in the response
console.log(response);
let token = response.json() && response.json().token;
if (token) {
// set token property
this.token = token;
// store username and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify({ user: user, token: token }));
// return true to indicate successful login
return true;
} else {
// return false to indicate failed login
return false;
}
}
);
}
logout() {
localStorage.removeItem("currentUser");
this.token = null;
}
}
and this is my index.php using slim framework
getContainer();
$container["jwt"] = function ($container) {
return new StdClass;
};
$app->add(new \Slim\Middleware\JwtAuthentication([
"path" => "/",
"passthrough" => "/authenticate",
"secret" => getenv("HJ_ENV"),
"error" => function ($request, $response, $arguments) {
$data["status"] = "error";
$data["message"] = $arguments["message"];
return $response
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
},
"callback" => function ($request, $response, $arguments) use ($container) {
$body = $response->getBody();
$body->write($arguments["decoded"]);
$container["jwt"] = $arguments["decoded"];
}
]));
$app->post('/authenticate', 'authenticate');
$app->run();
function authenticate(Request $request, Response $response)
{
$params = json_decode($request->getBody());
$sql = "select * from users where userName = :userName";
$result = json_decode( runQuery($sql, [ ':userName', $params->user ]) );
$body = $response->getBody();
if ( $result && $result[0]->password == $params->password )
{
$decoded = $request->getAttribute("jwt");
$body->write( json_encode([ 'token' => $decoded ]) );
}
else
{
$body->write( json_encode(['token' => null]) );
}
}
function runQuery($sql, ...$params)
{
try
{
$db = getConnection();
$stmt = $db->prepare($sql);
foreach ( $params as $param )
{
$stmt->bindParam( $param[0], $param[1] );
}
$stmt->execute();
$rows = [];
while($row=$stmt->fetch(PDO::FETCH_OBJ))
{
/*its getting data in line.And its an object*/
array_push($rows, $row );
}
$db = null;
return json_encode($rows);
}
catch(PDOException $e)
{
$db = null;
return $e->getMessage() ;
}
}
?>
my question is
I am not able to get token from container['jwt'].
If i give incorrect user name and password then token remain null.
But if i give correct user name and password. the $result variable give me data from my database. i can verify password. but $request->getAttribute("jwt") this method gives me null.
also i have checked $decoded = $container["jwt"]
but this also gives me null.
SO i could not know how to get the token created by jwt.
Thank you.

add(new \Slim\Middleware\JwtAuthentication([
"path" => "/",
"passthrough" => "/authenticate",
"error" => function ($request, $response, $arguments) {
$data["status"] = "error";
$data["message"] = $arguments["message"] ;
return $response
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES |
JSON_PRETTY_PRINT));
}
]));
$app->post('/authenticate', function (Request $request, Response $response )
{
$params = json_decode($request->getBody());
/* $params will contain user and password posted by angular for
verification in data base */
/* here you retrieve user name and password from database */
if ( /* check here user name and password */ )
{
$now = new DateTime();
$future = new DateTime("now +2 hours");
$payload = [
"iat" => $now->getTimeStamp(),
"exp" => $future->getTimeStamp()
];
$secret = getenv("HJ_ENV"); /* put your secret key here */
$token = JWT::encode($payload, $secret, "HS256");
$data["status"] = "ok";
$data["token"] = $token;
return $response->withStatus(201)
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES |
JSON_PRETTY_PRINT));
}
else
{
$data["status"] = "error";
$data["message"] = "Invalid Token" ;
return $response
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES |
JSON_PRETTY_PRINT));
}
});

Related

How to pass calculated/final value of one function to other functions in a controller of Codeigniter application

Using sessions we can achieve this, but need this without sessions or cookies.
<?php
class Employees extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
$this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => $_SESSION['invalid'],
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
$this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => $_SESSION['login'],
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
public function addNew()
{
$response = array();
$this->auth(); // this value is always null returned by auth() method
}
}
?>
This is more of a OOP programming basics question. If you want to re-use a variable in another function of the same controller object, you have to set the variable globally for the Employees class and then set/get its value in your functions by using $this->yourVariableName. But the set value of the object instance can only be reused in that instance only. Which means that after the auth() function, another function should be called subsequently to "access" the $this->yourVariableName.
Another way is to pass the $jwtoken as a parameter to a function.
But the following code answers your question "How to pass calculated/final value of one function to other functions in a controller of Codeigniter application", if it doesn't, then your question should be corrected I guess.
Edit:
Ow ok, first the auth() function is being called, then you would like to pass the $jwtoken value to another function, am I right? Well once a function is finished executing, the variable "disappears" if not passed to another function. If you would like to process the $jwtoken value immediately within the auth() function, then the answer is to pass the $jwtoken value to another function from within the auth() function:
<?php
class Employees extends CI_Controller
{
public function __construct() {
parent::__construct();
}
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
$this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => $_SESSION['invalid'],
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
// this is one way you can pass the value to another function, depending on what you want to do, you can also place a condition and continue only if the return value of the following function is respected:
$this->addNew($jwtoken);
// What is the addNew() supposed to do?
$this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => $_SESSION['login'],
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
public function addNew($jwtoken = "default_value_if_not_set") {
echo $jwtoken;
}
}
Since you are creating an API, I assume the API is a REST api and stateless, so there is no interference of sessions and cookies.
I assume your process works like this:
User does a login request from the app to the api and the api returns a token when the credentials check is valid
The token is stored in the app (in a local database for example) and used for other requests
So the only thing you need to do is (I assume you have a route to addNew):
public function addNew() {
$token = $this->input->get('token');
$loginData = $this->validateToken($token);
//... add new process
}
And from your app you need to pass the token with the request to the api.
How do you validate the token?
To obtain the data you have set in the token, you have to decode the token:
/**
* throws SignatureInvalidException
*/
function validateToken($token)
{
$jwt = new JWT();
return $jwt->decode($token, jwtSecretKey, 'HS256');
}
Code improvement
Avoid using sessions and cookies
Since your api is stateless, you have to avoid settings cookies or sessions. So in your controller you can remove the flash data helper:
public function auth() {
$adminEmail = $this->input->post('adminEmail');
$adminPassword = $this->input->post('adminPassword');
if ($adminEmail != "" && $adminPassword != "") {
$query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
//if user exist
if ($query->num_rows() <= 0) {
$response = array();
$jwtoken = "";
# REMOVE THIS LINE
# $this->session->set_flashdata("invalid", "Wrong email or password");
$response = array(
'status' => 'invalid',
'message' => "Wrong email or password", //CHANGE THIS LINE
'token' => $jwtoken,
);
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
} else {
// $this->session->set_userdata('adminEmail', $adminEmail);
$response = array();
$jwt = new JWT();
$data = array(
'adminEmail' => $adminEmail,
'iat' => time()
);
$jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
// I want to pass $jwtoken's variable to all the functions in a controller
# REMOVE THIS LINE
# $this->session->set_flashdata("login", "Scucessfully login!");
// if (isset($_SESSION['adminEmail'])) {
if ($jwtoken != "") {
$response = array(
'status' => 'valid',
'message' => "Scucessfully login!", //CHANGE THIS LINE
'token' => $jwtoken
);
}
$abc = $jwtoken;
//used to send finalized values
$this->output
->set_content_type('application/json')
->set_output(json_encode($response));
return $jwtoken; //return value
}
}
}
Return the output response instead of $jwtoken
In your response you have already set the the token, so you can simply return the response:
return $this->output
->set_content_type('application/json')
->set_output(json_encode($response));
Your query is vulnerable to sql injections
Use escape method around you variables or bind the params:
$sql = "select * from admin_tbl where email=? and password = ?";
$query = $this->db->query($sql, array($adminEmail, $adminPassword));

GET url varible in Slim v3.2 PHP Stripe checkout

I cannot get a URL varible in my stripe checkout PHP slim app.
I need to be able to get a price varible from the URL to echo out into the session for the price of stripe payment. However it is just not working, I can use $_GET['price']; to echo out before it becomes a SLIM APP however when it becomes a SLIM APP it just wont work...
use Slim\Http\Request;
use Slim\Http\Response;
use Stripe\Stripe;
require 'vendor/autoload.php';
$dotenv = Dotenv\Dotenv::create(realpath('../../'));
$dotenv->load();
Stripe::setApiKey(getenv('STRIPE_SECRET_KEY'));
$db = new SQLite3('./store.db');
$db->exec("CREATE TABLE IF NOT EXISTS sessions(id INTEGER PRIMARY KEY, stripe_id TEXT, status TEXT)");
// createSession
function createSession($sessionId) {
global $db;
$stmt = $db->prepare("INSERT INTO sessions(stripe_id, status) VALUES (:id, 'pending')");
$stmt->bindValue(':id', $sessionId, SQLITE3_TEXT);
return $stmt->execute();
}
// markSessionPaid
function markSessionPaid($sessionId) {
global $db;
$stmt = $db->prepare("UPDATE sessions SET status='paid' WHERE :id = stripe_id");
$stmt->bindValue(':id', $sessionId, SQLITE3_TEXT);
return $stmt->execute();
}
// getSessionStatus
function getSessionStatus($sessionId) {
global $db;
$stmt = $db->prepare("SELECT status FROM sessions WHERE :id = stripe_id");
$stmt->bindValue(':id', $sessionId, SQLITE3_TEXT);
$result = $stmt->execute();
return $result->fetchArray()[0];
}
$app = new Slim\App;
$app->get('/', function (Request $request, Response $response, $args) {
$response->getBody()->write(file_get_contents("../../client/index.html"));
return $response;
});
$app->get('/success', function (Request $request, Response $response, $args) {
$response->getBody()->write(file_get_contents("../../client/success.html"));
return $response;
});
$app->get('/cancel', function (Request $request, Response $response, $args) {
$response->getBody()->write(file_get_contents("../../client/cancel.html"));
return $response;
});
function middleware1() {
$price = $app->request()->get('price');
};
$app->post('/create-session', 'middleware1', function(Request $request, Response $response) use ($app) {
try {
// One time payments
$session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => [[
'name' => 'Order',
'description' => 'ORDER ID: 123456789A',
'images' => ['testimage'],
'amount' => $price,
'currency' => 'aud',
'quantity' => 1,
]],
'success_url' => 'http://localhost:4242/success?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => 'http://localhost:4242/cancel',
]);
// Subscription recurring payments
// $session = \Stripe\Checkout\Session::create([
// // 'customer' => 'cus_123',
// 'payment_method_types' => ['card'],
// 'subscription_data' => [
// 'items' => [[
// 'plan' => 'starter',
// 'quantity' => 1,
// ]],
// ],
// 'success_url' => 'http://localhost:4242/success?session_id={CHECKOUT_SESSION_ID}',
// 'cancel_url' => 'http://localhost:4242/cancel',
// ]);
createSession($session->id);
} catch (Exception $e) {
return $response->withJson($e->getJsonBody(), 400);
}
return $response->withJson($session);
});
$app->post('/webhook', function(Request $request, Response $response) use ($app) {
// You can find your endpoint's secret in your webhook settings
$endpoint_secret = getenv('STRIPE_WEBHOOK_SECRET');
$payload = $request->getBody();
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
$event = null;
try {
$event = \Stripe\Webhook::constructEvent(
$payload, $sig_header, $endpoint_secret
);
} catch(\UnexpectedValueException $e) {
// Invalid payload
http_response_code(400);
exit();
} catch(\Stripe\Exception\SignatureVerificationException $e) {
// Invalid signature
http_response_code(400);
exit();
}
// Handle the checkout.session.completed event
if ($event->type == 'checkout.session.completed') {
$session = $event->data->object;
// Fulfill the purchase...
handle_checkout_session($session);
}
return $response->withJson(['message' => 'success']);
});
$app->get('/session-status', function (Request $request, Response $response, array $args) {
$status = getSessionStatus($request->getQueryParam('session_id'));
return $response->withJson($status);
});
function handle_checkout_session($session) {
// Call out to inventory management system
// Ding in Slack
// send an email
markSessionPaid($session->id);
}
$app->run();
I've tried everything
$app->request()->get('price');
And more!
The URL looks like this www.example.com/server/php/?price=5770&orderid=y2INOqCUrEzrua1XwBMg
Any help would be greatly appreciated!
You cannot use $_GET in Slim since it wont work. One way to do it is since the parameters are passed in query I think you mean it like this checkout/?price=200. If so, then you can access it using this:
$queryParams = $app->request()->getQueryParams();
$price = $queryParams["price"];
This would probably work

Problems with session variables in slim php framework

I developed an API that I already have on a server. During the whole development I did tests with POSTMA and I had no problem, however, now that I want to use the API from the production domain to another domain it doesn't work: /
Production -> Local consumption POSTMAN: If it works
Production -> Local consumption from a website: Does not work
The problem is with the session variables, I have some consulates that occupy parameters such as "user ID" or "company id" that I set in the first step when I authenticate with JWT.
Step 1: Authentication (Route)
use App\Lib\Auth,
App\Validation\EmpleadoValidation,
App\Lib\Response;
$app->group('/autenticar/', function () {
$this->post('empresa', function ($req, $res, $args) {
$parametros = $req->getParsedBody();
if(isset($parametros['API']) && isset($parametros['API-KEY'])){
return $res->withHeader('Content-type', 'application/json')
->write(
json_encode($this->model->empresaAuth->autenticar($parametros['API'], $parametros['API-KEY']))
);
}else{
$r = new Response;
return $res->withHeader('Content-type', 'application/json')->withStatus(403)->write(json_encode($r->SetResponse(false, "Cabeceras no válidas")));
}
});
});
Step 1.2: Authenticate (Model)
public function autenticar($TOKEN, $KEY){
try{
$sql="SELECT e.id AS id_empresa, u.id AS id_admin, e.TOKEN, e.KEY,
u.email, e.nom_comercial
FROM empresas AS e
INNER JOIN empresas_usuariosprincipales AS u ON u.id_empresa=e.id
WHERE e.TOKEN = :TOKEN AND e.KEY= :KEY and e.API=1";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(":TOKEN", $TOKEN, PDO::PARAM_STR);
$stmt->bindParam(":KEY", $KEY, PDO::PARAM_STR);
$respuesta = $stmt ->execute();
$respuesta = $stmt ->fetch();
$data = $respuesta;
}catch(Exception $e){
die($e);
}
if(is_object($data)){
$token = Auth::SignIn([
'DISS' => $data->id_empresa.'-'.$data->id_admin,
'TOKEN' => $data->TOKEN,
]);
/**
* I used this library but it doesn't work for me
* https://github.com/akrabat/rka-slim-session-middleware
*/
$this->sesion->data = $data->TOKEN;
$this->sesion->id_empresa = $data->id_empresa;
$this->sesion->id_usuario = $data->id_admin;
/**
* I create session variables with the local system, but they don't work either
*/
$_SESSION['data'] = $data->TOKEN;
$_SESSION['id_empresa'] = $data->id_empresa;
$_SESSION['id_usuario'] = $data->id_admin;
$this->response->data = array("TOKEN" => $token);
return $this->response->SetResponse(true);
}else{
return $this->response->SetResponse("false", "Credenciales no válidas");
}
}
The problem arises when I want to access some resource of my API, I have a Middelwere configured, I don't know if this is causing the inconvenience. For example, in the following resources, when I access the model, my "user_id" and "business_id" session variables do not exist.
Step 2. I try to access a route (Resource). The resource requests access to the Middelwere
$app->group('/agenda/', function () {
$this->get('get', function ($req, $res, $args) {
return $res->withHeader('Content-type', 'application/json')
->write(
json_encode($this->model->agenda->getAll())
);
});
})->add(new AuthMiddlewareEmpresa($app));
Step 2.1 The Middleware validates the permissions to access the resource.
class AuthMiddlewareEmpresa{
private $app = null;
private $r = null;
public function __construct($app){
$this->app = $app;
$this->r = new Response;
}
public function __invoke($request, $response, $next){
$c = $this->app->getContainer();
$app_tokken_name = $c->settings['app_token_name'];
$token = $request->getHeader($app_tokken_name);
if($c->model->detallesempresa->obtener()->data!=false && $c->model->detallesempresa->obtener()->data->api==1){
if(isset($token[0])) $token = $token[0];
try{
Auth::Check($token);
}catch(Exception $e){
$r = new Response;
$r->data = array("TOKEN" => null);
return $response->withHeader('Content-type', 'application/json')->withStatus(401)->write(json_encode($r->SetResponse(false, "Token no válido.")));
}
}else{
$r = new Response;
return $response->withHeader('Content-type', 'application/json')->withStatus(401)->write(json_encode($r->SetResponse(false, "Sin acceso a Jobtify API.")));
}
return $next($request, $response);
}
}
but when the Middleware requires access to the model to validate the permissions from the database. I simply cannot access the session variables. T_T
2.3. This is the model. Return null because when doing the queries it does not detect the session variables user_id and company_id
class DetallesEmpresaModel{
private $db;
private $TOKEN = "";
private $id_empresa = "";
private $id_usuario = "";
private $response;
private $sesion;
public function __construct($db){
$this->db = $db;
$this->response = new Response();
$this->sesion = new \RKA\Session();
if(isset($this->sesion->id_empresa)){
$this->TOKEN = $_SESSION['data'];
}
if(isset($this->sesion->id_empresa)){
$this->id_empresa = $this->sesion->id_empresa;
}
if(isset($this->sesion->id_usuario)){
$this->id_usuario = $this->sesion->id_usuario;
}
}
/*
Este modelo es accesible internamente
*/
public function obtener(){
try{
$sql="SELECT e.id_paquete AS paquete, e.activa, e.api, priv.* FROM empresas_privilegios AS priv
INNER JOIN empresas AS e ON priv.id_empresa=e.id
WHERE id_empresa=:id_empresa";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(":id_empresa", $this->id_empresa, PDO::PARAM_STR);
$respuesta = $stmt ->execute();
$respuesta = $stmt ->fetch();
$data = $respuesta;
}catch(Exception $e){
die($e);
}
$this->response->SetResponse(true);
$this->response->data = $data;
return $this->response;
}
}

Unexpected Value exception

I am having below error in postman while i was teting my api. It shows slim application error in postman. Error Type: UnexpectedValueException
Message: Wrong number of segments
File: C:\Users\tahmeed\Documents\app-timber-api2\vendor\firebase\php-jwt\src\JWT.php
Line: 78
Do i need to modify the token or the JWT.php ?
decode.php in JWT.php
public static function decode($jwt, $key, array $allowed_algs = array())
{
$timestamp = is_null(static::$timestamp) ? time() : static::$timestamp;
if (empty($key)) {
throw new InvalidArgumentException('Key may not be empty');
}
$tks = explode('.', $jwt);
if (count($tks) != 3) {
throw new UnexpectedValueException('Wrong number of segments');
}
list($headb64, $bodyb64, $cryptob64) = $tks;
if (null === ($header = static::jsonDecode(static::urlsafeB64Decode($headb64)))) {
throw new UnexpectedValueException('Invalid header encoding');
}
if (null === $payload = static::jsonDecode(static::urlsafeB64Decode($bodyb64))) {
throw new UnexpectedValueException('Invalid claims encoding');
}
if (false === ($sig = static::urlsafeB64Decode($cryptob64))) {
throw new UnexpectedValueException('Invalid signature encoding');
}
if (empty($header->alg)) {
throw new UnexpectedValueException('Empty algorithm');
}
if (empty(static::$supported_algs[$header->alg])) {
throw new UnexpectedValueException('Algorithm not supported');
}
if (!in_array($header->alg, $allowed_algs)) {
throw new UnexpectedValueException('Algorithm not allowed');
}
if (is_array($key) || $key instanceof \ArrayAccess) {
if (isset($header->kid)) {
if (!isset($key[$header->kid])) {
throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key');
}
$key = $key[$header->kid];
} else {
throw new UnexpectedValueException('"kid" empty, unable to lookup correct key');
}
}
// Check the signature
if (!static::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) {
throw new SignatureInvalidException('Signature verification failed');
}
// Check if the nbf if it is defined. This is the time that the
// token can actually be used. If it's not yet that time, abort.
if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) {
throw new BeforeValidException(
'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)
);
}
// Check that this token has been created before 'now'. This prevents
// using tokens that have been created for later use (and haven't
// correctly used the nbf claim).
if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) {
throw new BeforeValidException(
'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
);
}
// Check if this token has expired.
if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) {
throw new ExpiredException('Expired token');
}
return $payload;
}
AuthController.php
<?php
namespace App\Controllers\AppodMobile;
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \Interop\Container\ContainerInterface as ContainerInterface;
use \Illuminate\Database\Query\Expression as Raw;
use App\Models\AppodMobile\Users as Users;
use Firebase\JWT\JWT;
use Tuupola\Base62;
class AuthController
{
use \App\CommonFunctions;
protected $container;
public function __construct(ContainerInterface $container) {
$this->container = $container;
}
function auth($request,$response)
{
$input = $request->getParsedBody();
$user = Users::select('id','pword')->where('email','=',$input['email'])->first();
// verify email address.
if(!$user) {
$response->withStatus(404);
return $response->withJson(['error' => true, 'message' => 'User does not exist.'],404);
}
// verify password.
$salt = getenv('TMS_SALT');
if (!(sha1($salt.$input['password']) == $user->pword)) {
$response->withStatus(401);
return $response->withJson(['error' => true, 'message' => 'Password is incorrect.'],401);
}
$now = new \DateTime();
$future = new \DateTime("+120 minutes");
$server = $request->getServerParams();
$jti = (new Base62)->encode(random_bytes(16));
$payload = [
"iat" => $now->getTimeStamp(),
// "exp" => $future->getTimeStamp(),
"jti" => $jti,
"sub" => $server["PHP_AUTH_USER"]
];
$token = JWT::encode($payload, getenv('JWT_SECRET'), "HS256");
$data = array(
'token' => $token,
'user_id'=>$user->id,
// appod'expires' => $future->getTimestamp()
);
$response->withStatus(200);
return $response->withJson($data);
}
}
You should use third paramater in Decode Method to solve the Uncaught UnexpectedValueException: Algorithm not allowed
Here is the below code
<?php;
require('jwt/vendor/autoload.php');
use \Firebase\JWT\JWT;
function generate_token($uid){
$key = "thiismykey";
$jwt = JWT::encode($uid, $key);
echo "JWT Toke = ".$jwt."<br>";
$decoded = JWT::decode($jwt, $key, array('HS256'));
echo "After Encode = ".$decoded;
}
//call the funtion
generate_token("santosh");
?>
Output -
JWT Toke = eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.InNhbnRvc2gi.ZUyzpLH0FLB9VdRPS2CaQAqM_wKHjXP80moIzL-8u2o
After Encode = santosh

Phalcon Rest Micro sessions not set

Iḿ trying to make an rest application using Phalcon, i save some of the info
of the logged in user in an session but i don't get this to work, my code:
$this->session->set( Sessions::USERINFO, array (
'login' => true,
'type' => UserTypes::ADMIN,
'username' => $this->user->getUsername(),
'adminid' => $this->user->getAdminID(),
'fullname' => $this->user->getFullName(),
'avatar' => $this->user->getAvatar() )
);
return $this->session->get( Sessions::USERINFO );
When he returns the session it works but when i try to get the session in an other request it returns empty
return array("session" => $this->session->isStarted(),
"session Data" => $this->session->get(Sessions::USERINFO));
isStarted returns true
get returns null
Sessions::USERINFO
is an class with const values
const USERINFO = "userInfo";
Session var creation
$di->setShared( 'session', function () {
$session = new Session();
$session->start();
return $session;
} );
I am using this to save my session:
$obj = $this->request->getJsonRawBody();
$user = Users::findFirstByUsername($obj->username);
if($user) {
if($this->security->checkHash($obj->password, $user->password)) {
unset($user->password);
$this->session->set('auth', $user->toArray());
$response = $user->toArray();
}
else {
$response = array('msg' => 'failed');
}
}
else {
$response = array('error' => 'User not found');
}
$this->setPayload($response);
return $this->render();
And this to recieve information from my session
if($this->session->get('auth')['username']) {
$response = $this->session->get('auth');
}
else {
$response = array('msg' => 'noInfo');
}
$this->setPayload($response);
return $this->render();
This is how I start my session:
$di->set('session', function () {
$session = new SessionAdapter();
$session->start();
return $session;
});
It works just fine, you might want to try this.
I found the problem. Had to enable this in my frondend application:
RestangularProvider.setDefaultHttpFields({
withCredentials: true
});
The frontend was not sending the cookie with every request.

Categories