Slim php jwt auth

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Authentication and authorisation middleware for Slim framework

License

pdscopes/slim-auth

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

An authentication and authorisation middleware for Slim 4 framework.

composer require madesimple/slim-auth 

A middleware to determine whether the request contains valid authentication token. The middleware has been designed so that it can easily be extended to:

  • handle any type of token retrieval;
  • handle any type of validation method; and,
  • perform any set of actions if authentication was successful.

To use an Authentication middleware to your Slim application simply:

use Slim\Middleware\Authentication\SimpleTokenAuthentication; /** @var \Slim\App $app The Slim application */ /** @var string $pattern Pattern for either the group or a route */ /** @var callable $callable A callable for a route */ // Add to all routes: $app->add(new SimpleTokenAuthentication($app->getContainer(), $options)); // Add to a group of routes: $app->group($pattern, function () <>) ->add(new SimpleTokenAuthentication($app->getContainer(), $options)); // Add to a specific route: $app->get($pattern, $callable) ->add(new SimpleTokenAuthentication($app->getContainer(), $options));

Side node: We recommend that if you are going to be adding same authentication to more than more groups/routes to put the middleware in dependencies.php .

Читайте также:  Php for discord server

Default options for authentication are:

[ // boolean - whether to enforce an https connection 'secure' => true, // array - list of hostnames/IP addresses to ignore the secure flag 'relaxed' => ['localhost', '127.0.0.1'], // array - list of environment variables to check for the token (set to an empty array to skip) 'environment' => ['HTTP_AUTHORIZATION', 'REDIRECT_HTTP_AUTHORIZATION'], // string - the header to check for the token (set to false, null, or '' to skip) 'header' => 'X-Auth', // string - the regex to match the token ($match[$options['index']] is used as the token) 'regex' => '/(.*)/', // integer - the regex index to use as the token 'index' => 1, // string - the cookie to check for the token (set to false, null, or '' to skip) 'cookie' => 'X-Auth', // string - the identifier for the token in the payload 'payload' => null, // string - the name to store the token in the request attributes 'attribute' => 'token', // object - an instance of a Psr\LoggerInterface 'logger' => null, ];

When authentication fails the middleware throws an HttpUnauthorizedException is thrown.

Simple token authentication is an implementation of Authentication which allows the user to provide a callable to validate a token. The callable is passed to Simple token authentication using the option:

[ // callable - function to validate the token [required] 'validate' => null, ];

The callable should have the following signature:

function ($token): bool < /** @var bool $isValid Populated by this function, true if the token is valid */ return $isValid; >

JWT authentication is an implementation of Authentication which allows the user to use JWT as authentication tokens. JWT authentication overrides the default regex, and adds two extra options:

[ // string - Overrides the default regex 'regex' => '/Bearer\s+(.*)$/i', // string - JWT secret [required] 'secret' => '', // array - list of JWT algorithms [optional] 'algorithm' => ['HS256', 'HS512', 'HS384'], ];

A middleware to determine whether an authenticated request has authorisation to access the requested route.

Читайте также:  Php mysqli check if error

When Authorisation fails the middleware throws an HttpForbiddenException exception.

Note: If you need to access the route from within your app middleware you will need to add the Middleware\RoutingMiddleware middleware to your application just before you call run() .

About

Authentication and authorisation middleware for Slim framework

Источник

Slim3 Framework Authorization with JWT (JSON Web Tokens)

In this post, I will show how you can secure your Slim3 Framework-based applications using JSON Web Token (JWT). To know more about JWT and How it works visit the official website(https://jwt.io).

Download & Install

We gonna use composer to download and install the Slim Framework. The easiest way to start working with Slim is to create a project using Slim-Skeleton as a base by running this bash command:

$ php composer.phar create-project slim/slim-skeleton [my-app-name]

Replace [my-app-name] with the desired directory name for your new application.

You can then run it with PHP’s built-in web server:

$ cd [my-app-name]; php -S localhost:8080 -t public public/index.php

While running built-in web server you can access the application at: http://localhost:8080 . If you head over to the browser with this URL you should get following output:

Connect to database

We gonna use MySQL as a database engine, so lets open src/settings.php file and add follwing array to settings array.

// database connection details "db" => [ "host" => "your-host", "dbname" => "your-database-name", "user" => "your-db-username", "pass" => "your-db-password" ],

After placing your database settings, lets open src/dependencies.php file and inject database object into container with following code:

// PDO database library $container['db'] = function ($c) < $settings = $c->get('settings')['db']; $pdo = new PDO("mysql:host=" . $settings['host'] . ";dbname jwt" => [ 'secret' => 'supersecretkeyyoushouldnotcommittogithub' ]

Now open your src/middleware.php file and add following code.

add(new \Slim\Csrf\Guard); $app->add(new \Tuupola\Middleware\JwtAuthentication([ "path" => "/api", /* or ["/api", "/admin"] */ "attribute" => "decoded_token_data", "secret" => "supersecretkeyyoushouldnotcommittogithub", "algorithm" => ["HS256"], "error" => function ($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)); > ]));

We have configured the middleware to auth check only the URLs contains the /api . If you want to pass multiple patterns pass them in an array format.

Читайте также:  Python manage py startapp users

Open your src/routes.php file and define new route for login as shown below –

. use Slim\Http\Request; use Slim\Http\Response; use \Firebase\JWT\JWT; . . $app->post('/login', function (Request $request, Response $response, array $args) < $input = $request->getParsedBody(); $sql = "SELECT * FROM users WHERE email= :email"; $sth = $this->db->prepare($sql); $sth->bindParam("email", $input['email']); $sth->execute(); $user = $sth->fetchObject(); // verify email address. if(!$user) < return $this->response->withJson(['error' => true, 'message' => 'These credentials do not match our records.']); > // verify password. if (!password_verify($input['password'],$user->password)) < return $this->response->withJson(['error' => true, 'message' => 'These credentials do not match our records.']); > $settings = $this->get('settings'); // get settings array. $token = JWT::encode(['id' => $user->id, 'email' => $user->email], $settings['jwt']['secret'], "HS256"); return $this->response->withJson(['token' => $token]); >);

On the successful login, it will return JWT token. This method is pretty straightforward, first, we are validating the user with email and password, if the request is valid we are generating the JWT auth token. The user has to send this token in the header(Authorization: Bearer ) in order to get access to the protected routes/URLs.

Let’s define another route, it’s not public route, you need to send Authorization token to get access to it. As I mentioned above this URL is staring with /api so the user must authenticate to access this page.

My user table structure and its sample data:

CREATE TABLE `users` ( `id` int(10) UNSIGNED NOT NULL, `first_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `last_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `created_at` timestamp NOT NULL DEFAULT '2019-01-25 22:11:50', `updated_at` timestamp NOT NULL DEFAULT '2019-01-25 22:11:50' ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; INSERT INTO `users` (`id`, `first_name`, `last_name`, `email`, `password`, `created_at`, `updated_at`) VALUES (2, 'Arjun', 'A', '[email protected]', '$2y$10$2N74YBkxYXPtEtFTxynuxeEn9OH9BZ.wI4ldZr00n1FX5q09/llbO', '2018-02-22 18:30:00', '2018-02-22 18:30:00'); ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `users_email_unique` (`email`); ALTER TABLE `users` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

Note: Here my encrypted password is [email protected]

How to test

We gonna use Adanced RESt client to test apis, below are the screen shot of it.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face — we are here to solve your problems.

Источник

Оцените статью