Single file PHP that can serve as a JWT based authentication provider to the PHP-CRUD-API project

Overview

PHP-API-AUTH

Single file PHP that can serve as a JWT based authentication provider to the PHP-CRUD-API project.

NB: Are you looking for v1? It is here: https://github.com/mevdschee/php-api-auth/tree/v1

Requirements

  • PHP 7 or higher

Installation

Upload "auth.php" and edit the configuration block at the bottom of the file:

    main([
        'default' => [
            'api.php' => [
                'secret' => 'someVeryLongPassPhraseChangeMe',
                'redirects' => 'http://localhost/vanilla.html',
                'validate' => function ($username, $password) {
                    return $username == 'admin' && $password == 'admin';
                },
            ],
        ],
    ]);

You should change the "secret" and set the "redirects" to the URL of the client (for source code see below) that uses the JWT token. The validate function should be changed to hold a stronger password validation.

The default "clientId" is "default" and is the first key in the config. The default "audience" is "api.php" and this is defined as the second key in the config.

Example client:

https://github.com/mevdschee/php-crud-api/blob/master/examples/clients/auth.php/vanilla.html

Flow

This is the authentication flow:

  • Browser will load the client.
  • The client will redirect the user to the "auth.php"
  • If the user does not have a valid session (cookie) then the "login.html" page is served.
  • The user is redirected back to the client with the token in the URL
  • The client uses the token to call the api.
  • The API will exchange the token for a session (cookie)

Now the client can do API calls until the session times out.

I suggest that you first get PHP-CRUD-API working with Auth0 before you start implementing your own JWT based authentication provider using this repository.

Comments
  • Auth does not work properly

    Auth does not work properly

    Hi, I have tried to set up php-api-auth framework but it doesn't work as I expected. You can see it here. If you login using form you get (probably) csrf token. But if I send POST request to .../api.php/?username=admin&password=admin it doesn't give me csrf token and it doesn't check, if credentials are OK neither. I am sure I am making something wrong but I cannot find out what exactly. Thanks a lot for tips. 🙂

    help wanted 
    opened by marekpridal 11
  • Username/password authentication

    Username/password authentication

    Hi Maurits

    Thank you for your sharing your work, it's excellent code and very helpful.

    Sorry for asking a simple question, I may be missing something obvious. I'm seeing a token returned for any username/password pair, even null.

    How can I make this authenticate against known credentials?

    $ curl http://localhost:8888/api.php
    $ curl http://localhost:8888/api.php --data "username=admin&password=admin"
    "3463927620177487360"
    $ curl http://localhost:8888/api.php --data "username=foo&password=bar"
    "6364633731514325019"
    $ curl http://localhost:8888/api.php --data "username=&password="
    "1322945882537392955"
    $
    
    help wanted 
    opened by reubenwalkerau 10
  • App fails to recognize token that  is returned

    App fails to recognize token that is returned

    Hi there!

    I'm running ubuntu 16.06 here and a mysql database.

    If I run the phpcrud api program without this auth stuff installed, I can get results by get method to /api.php

    I then paste the the code from this repo in the /api.php file into the phpcrud /api file right above the the $api = new PHP_CRUD_API and uncomment the top half.

    I change the 'secret' = 'testingtoken123'

    I then visit /login_token.htmlI provide the username and password set as default in auth.php (username, password)

    This sends me to login_token.php with a token. Clicking the OK button sends me back to the API page, but the page is blank.

    If I debug the code, shows me that it is failing to recognize a session. If I use that token and go to /api.php?csrf=eyJ0eXAicOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE0ODMyMjMyMzgsImV4cCI6MTQ4MzIyMzI2OH0.3Z1Z9CZMJwRc8HR03iN5TrczXrMrUO8q6_awuM5cf0s

    I still get a blank page. Debugging the code, i get to line 164 which tells me that I should get a success. I also see my token getting evaluated on 113.

    Any help here would be appreciated. I would assume the outofthebox examples should work with a default installation.

    Thanks!

    help wanted 
    opened by benhbell 8
  • cURL GET request to api.api gives me 401 error

    cURL GET request to api.api gives me 401 error

    Hi,

    First off, thank you so much for the great auth and crud APIs. You have really saved me (and I'm sure, many others) a lot of time by making them available publicly!

    Anyway, I've managed to get the everything up and running in my environment to a point where I can use PostMan and/or a Browser to register a user, authenticate this user and then use the resulting CSRF token to perform GET/POST/PUT requests as advertised.

    My issue arises when I try to send a cURL (GET) request from the project directory on my Production Web Server to the API to retrieve a list of Users from the database. The same URL entered into the browser retrieves the data as expected but not when it is accessed via a cURL request.

    My code is as follows:

    $Url = 'http://example/api/Users?transform=1&csrf='.$_SESSION['csrf'];
    
    $ch = curl_init();
    
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $Url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    
    $Users = curl_exec($ch);
    
    if ($Users === FALSE) {
        die("Curl failed: " . curL_error($ch));
    }
    
    $ch_info = curl_getinfo($ch);
    
    var_dump($Url, $Users, $Users['Users'], $ch_info);
    
    curl_close($ch);
    

    In the above code, var_dump shows me the following:

    1. $Url -> http://example/api/Users?transform=1&csrf=1234567890123456789
    2. $Users -> string (0) ""
    3. $Users['Users'] -> string (0) ""
    4. $ch_info -> ["url"] ->http://example/api/Users?transform=1&csrf=1234567890123456789, ["http_code"]=> int(401) amongst other things...

    I worked around this issue by performing the GET using client-side AJAX/JQuery which tells me that I have a Cookies-related issue as the CSRF I receive from the User Auth request will create a client-side Cookie and I need one that sit on the Server for internal Auth.

    I hope the above makes sense to you and you can give me some insight into what I've done wrong and how to go about fixing it?

    Thanks in advance for your help!

    help wanted 
    opened by rmawani 7
  • Send csrf on Create/Post

    Send csrf on Create/Post

    I've enabled simple user/pass authentication and it works fine when I try to post records using get.

    I use curl to post username and password as defined on api.php and get the csrf token in return I then send the csrf on the url as api.php/table/?csrf=tokenvalue and it returns the json with the records as expected.

    The problem is when I try to create a record also using curl. I first post the username and password, get the proper token, but when I send the csrf as one of the post fields it does not work. I've also tried using in the curl url as /?csrf=tokenvalue but no luck.

    I hope I explained the issue well enough and I would really appreciate your help perhaps with a simples post create example.

    Thanks.

    help wanted 
    opened by fvdias 7
  • HTTP Error 401 unauthorized cache-control

    HTTP Error 401 unauthorized cache-control

    Hi, I i've an auth problem with the API. I don't know if the problem is the api, the server, or mine.

    I'm programming an App for iOS and Android. In iOS i'm connecting with the api and everything works fine (including the auth). But in Andoid, with the same code that i'm using for iOS, i've auth problems.

    I'm logging in and it works ok (i'm getting the correct csrf). But when I try to select registers from a table, this is the response:

    ResponseCode: 401
    ResponseHeader: HTTP/1.1 401 Unauthorized \n Cache-Control: no-store
    ResponseData:
    

    Is a rare behavior because the code and the server is the same. And i'm integrating ok the api because in iOS works perfect.

    Maybe should I use a different header for send request? this is my header:

        vector<string> header;
        header.emplace_back("User-Agent: MyApp/1.0");
        header.emplace_back("Content-Type: application/x-www-form-urlencoded");
        httpRequest->setHeaders(header);
    

    Help plz.

    help wanted 
    opened by raz0r007 6
  • Token authorization

    Token authorization

    I have a problem with authentication using token. I use Postman. My steps:

    1. Send POST to login_token.php with username and password and I get correct token
    2. Send GET to api.php with Bearer Token and I get 401 Unauthorized

    Could you tell me what I'm doing wrong?

    help wanted 
    opened by tomasyhy 6
  • SESSION

    SESSION

    Hi I'm having this error :

    Notice: Undefined variable: _SESSION in /home/php-crud-api-master/auth.php on line 196 "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1Mjg0MTk4OTIsImV4cCI6MTUyODQxOTkyMn0.eOV6tbWX-I8Yoo1qrdDQyeO4cboSTp9yLYMf6USrQmk"/>

    Why? I'm trying to implement login with token. Regards

    help wanted 
    opened by raz0r007 6
  • Trouble getting simple AUTH to work

    Trouble getting simple AUTH to work

    Hey sir,

    I've been playing around with your regular API and it is great fun and very helpful. I want to add the AUTH plugin but have trouble doing so.

    I've added the respective lines in the api.php (uncommented the parts near the end):

    require 'auth.php'; $auth = new PHP_API_AUTH(array( 'authenticator'=>function($user,$pass){ $_SESSION['user']=($user=='admin' && $pass=='admin'); } )); if ($auth->executeCommand()) exit(0); if (empty($_SESSION['user']) || !$auth->hasValidCsrfToken()) { header('HTTP/1.0 401 Unauthorized'); exit(0); }

    I've also added the auth.php and the login/logout.html pages. When using login.html I receive a token result in the body and the header and also a cookie.

    Once I perform /api.php?csrf=MYTOKEN I receive the swagger output. Trying to access /api.php?csrf=MYTOKEN/ or /api.php?csrf=MYTOKEN/TableName I receive a 401 unauthorized.

    Accessing the table without the auth plugin works perfectly fine. I cant figure out what I am doing wrong. I have taken everything from the source here and just adjusted my database configuration. When sending my request for the table I can see in Fiddler that the cookie is sent, too. It is also the same cookie I have received during the login procedure.

    Any hints? My .php is very limited and I have failed to turn something up in google. Thanks a bunch for any help. chris

    help wanted 
    opened by hisbluness 6
  • Example of server config

    Example of server config

    Hi there, First thanks for the awesome accelerator. Please note that I am new to PHP, my last time using it goes back more than 15 years... I'm trying to use the username + password authentication, it doesn't matter what I do, I get 200 Ok on the first post request to api.php on '/' but any subsequent request ends in 401. Is there an example of usage available that I can follow? I've only seen the client usage example but none for the server. Is there also a documentation explaining the different settings? Thank you and sorry for the basic questions

    help wanted 
    opened by younesouhbi 6
  • how to setup middleware to work with auth0

    how to setup middleware to work with auth0

    How to setup a config parameters for the middleware to work with auth0? I already set a parameter "middleware:jwtAuth", but have no idea where/how to set the middleware to accept valid audience/authorized_iss from auth0 ( in other words, how php-crud-api knows that a token is a valid token from auth0) without using php-api-auth

    help wanted 
    opened by paitoncamp 5
  • How to do the authentication regarding user table in DB?

    How to do the authentication regarding user table in DB?

    It seems the login is done by hard coding!

    'validate' => function ($username, $password) {
          return $username == 'admin' && $password == 'admin';
    },
    

    While I expect it does the validation with a user table in the DB!

    Also I activated this config in the api.php:

        'middlewares' => 'dbAuth,authorization',
       'authorization.tableHandler' => function ($operation, $tableName) {
             return $tableName != 'users';
       },
    

    But then it will show the following error in the vanila.html after login by admin:admin:

    { "code": 1012, "message": "Authentication failed'" }

    So it seems I need to connect the auth.php and api.php somehow to have the same session data and also do the authentication regarding a DB table!

    help wanted 
    opened by mjza 8
  • Error: text:

    Error: text: "Could not find configuration: default / default"

    Trying to get auth.php to work I get this error: text: "Could not find configuration: default / default"

    This is the code I'm using: http.post('/auth.php', { username: username, password: password });

    What am I doing wrong?

    Furthermore: At the end of auth.php username and password are both returned as 'admin'. Do I have to change that or can I leave this empty? I don't get it, sorry.

    opened by MaccerC 5
Releases(v2.0.1)
Owner
Maurits van der Schee
Software Architect & Performance Engineer
Maurits van der Schee
PSR-7 and PSR-15 JWT Authentication Middleware

PSR-7 and PSR-15 JWT Authentication Middleware This middleware implements JSON Web Token Authentication. It was originally developed for Slim but can

Mika Tuupola 782 Dec 18, 2022
Multi-provider authentication framework for PHP

Opauth is a multi-provider authentication framework for PHP, inspired by OmniAuth for Ruby. Opauth enables PHP applications to do user authentication

Opauth – PHP Auth Framework 1.7k Jan 1, 2023
LINE strategy for Opauth, Opauth is a multi-provider authentication framework for PHP.

Opauth-LINE Opauth strategy for LINE. Implemented based on https://developers.line.me/web-api/integrating-web-login-v2 using OAuth 2.0. Opauth is a mu

Opauth – PHP Auth Framework 2 Jul 11, 2017
Rinvex Authy is a simple wrapper for @Authy TOTP API, the best rated Two-Factor Authentication service for consumers, simplest 2fa Rest API for developers and a strong authentication platform for the enterprise.

Rinvex Authy Rinvex Authy is a simple wrapper for Authy TOTP API, the best rated Two-Factor Authentication service for consumers, simplest 2fa Rest AP

Rinvex 34 Feb 14, 2022
A PHP boilerplate based on Slim Framework, for start projects with Eloquent ORM, Validation, Auth (JWT), Repositories and Transformers ready

A PHP boilerplate based on Slim Framework, for start projects with Eloquent ORM, Validation, Auth (JWT), Repositories and Transformers ready.

Damiano Petrungaro 58 Aug 10, 2022
It's a Laravel 8 authentication markdown that will help you to understand and grasp all the underlying functionality for Session and API Authentication

About Auth Starter It's a Laravel 8 authentication markdown that will help you to understand and grasp all the underlying functionality for Session an

Sami Alateya 10 Aug 3, 2022
Rest API - JWT - Symfony5

Symfony5 JWT - REST API Example Symfony5 JWT - REST API Example Built With PHP Symfony 5 PostgreSQL Getting Started This is an example of how you may

Salih Gencer 1 Dec 24, 2021
phpCAS is an authentication library that allows PHP applications to easily authenticate users via a Central Authentication Service (CAS) server.

phpCAS is an authentication library that allows PHP applications to easily authenticate users via a Central Authentication Service (CAS) server.

Apereo Foundation 780 Dec 24, 2022
Security Defense for Firebase's PHP-JWT Library

PHP-JWT-Guard Protect your code from being impacted by issue 351 in firebase/php-jwt. Installation First, install this library with Composer: composer

Paragon Initiative Enterprises 8 Nov 27, 2022
Simple JWT Auth support for Laravel PHP Framework

Laravel JWT Simple JWT Auth for Laravel PHP Framework using Firebase JWT under the hood. Installation Standard Composer package installation: composer

Ricardo Čerljenko 34 Nov 21, 2022
PHP package for JWT

PHP-JWT A simple library to encode and decode JSON Web Tokens (JWT) in PHP, conforming to RFC 7519. Installation Use composer to manage your dependenc

Firebase 8.6k Jan 7, 2023
JWT auth for Laravel and Lumen

JWT Artisan Token auth for Laravel and Lumen web artisans JWT is a great solution for authenticating API requests between various services. This packa

⑅ Generation Tux ⑅ 141 Dec 21, 2022
Laravel Auth guard for FusionAuth JWT

Laravel FusionAuth JWT Implement an Auth guard for FusionAuth JWTs in Laravel. It ships with also a middleware to check against the user role. Install

Theraloss 7 Feb 21, 2022
Probando JWT en Laravel

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

SelsiusRC28 1 Nov 2, 2021
JSON Web Token (JWT) for webman plugin

JSON Web Token (JWT) for webman plugin Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场景。

 ShaoBo Wan(無尘) 25 Dec 30, 2022
Sistema de Administrativo - Cliente e Vendedor - Autenticação JWT e Relacionamentos BD

Hi there, My name is ATTILA SAMUELL TABORY, I love technology ?? Sistema Administrativo Laravel e Vue JS - JWT e Relacionamentos BD Sistema Administra

Attila Samuell 7 May 9, 2022
Aplicação criada com Slim Framework com objetivo de criar autenticação com JWT e aprender sobre o framework Slim

Slim JWT App Essa aplicação tem como foco o aprendizado do Framework Slim e também a utilização de JWT. Como rodar a Aplicação A aplicação está config

Nicolas Pereira 9 Oct 4, 2022
JWT Authenticator for symfony

HalloVerdenJwtAuthenticatorBundle This bundle provides a JWT authenticator for Symfony applications. It's using PHP JWT Framework for parsing and vali

Hallo Verden 0 Jul 8, 2022
This repository includes a sample project to illustrate the usage of the JobRouter® Authentication Factor API.

JR 2FA Example Plugin This repository includes a sample project to illustrate the usage of the JobRouter® Authentication Factor API. It can be used as

JobRouter 4 Sep 10, 2021