Git Product home page Git Product logo

security-jwt-service-provider's Introduction

Silex security jwt service provider

Build Status Latest Stable Version Total Downloads Latest Unstable Version License

This provider usage with silex security

require silex

for usage stable version silex your need used security jwt service provider version in 1.*

for usage silex 2.0 version or not stable master your need usage version 2.*

Installation

composer require cnam/security-jwt-service-provider:1.*

Or add your composer.json

require "cnam/security-jwt-service-provider":"1.*"

Simple example

Initialise silex application

require_once __DIR__ . '/../../vendor/autoload.php';

$app = new Silex\Application(['debug' => true]);

Create configuration

add config for security jwt

$app['security.jwt'] = [
    'secret_key' => 'Very_secret_key',
    'life_time'  => 86400,
    'options'    => [
        'username_claim' => 'name', // default name, option specifying claim containing username
        'header_name' => 'X-Access-Token', // default null, option for usage normal oauth2 header
        'token_prefix' => 'Bearer',
    ]
];

Create users, any user provider implementing interface UserProviderInterface

$app['users'] = function () use ($app) {
    $users = [
        'admin' => array(
            'roles' => array('ROLE_ADMIN'),
            // raw password is foo
            'password' => '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg==',
            'enabled' => true
        ),
    ];

    return new InMemoryUserProvider($users);
};

Add config for silex security

$app['security.firewalls'] = array(
    'login' => [
        'pattern' => 'login|register|oauth',
        'anonymous' => true,
    ],
    'secured' => array(
        'pattern' => '^.*$',
        'logout' => array('logout_path' => '/logout'),
        'users' => $app['users'],
        'jwt' => array(
            'use_forward' => true,
            'require_previous_session' => false,
            'stateless' => true,
        )
    ),
);

Register silex providers

$app->register(new Silex\Provider\SecurityServiceProvider());
$app->register(new Silex\Provider\SecurityJWTServiceProvider());

Example for authorization and request for protected resources

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\InMemoryUserProvider;
use Symfony\Component\Security\Core\User\User;


$app->post('/api/login', function(Request $request) use ($app){
    $vars = json_decode($request->getContent(), true);

    try {
        if (empty($vars['_username']) || empty($vars['_password'])) {
            throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $vars['_username']));
        }

        /**
         * @var $user User
         */
        $user = $app['users']->loadUserByUsername($vars['_username']);

        if (! $app['security.encoder.digest']->isPasswordValid($user->getPassword(), $vars['_password'], '')) {
            throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $vars['_username']));
        } else {
            $response = [
                'success' => true,
                'token' => $app['security.jwt.encoder']->encode(['name' => $user->getUsername()]),
            ];
        }
    } catch (UsernameNotFoundException $e) {
        $response = [
            'success' => false,
            'error' => 'Invalid credentials',
        ];
    }

    return $app->json($response, ($response['success'] == true ? Response::HTTP_OK : Response::HTTP_BAD_REQUEST));
});

$app->get('/api/protected_resource', function() use ($app){
    return $app->json(['hello' => 'world']);
});

$app->run();

Full example in directory tests/mock/app.php

And should for tests correct work silex-security-jwt-provider

security-jwt-service-provider's People

Contributors

cnam avatar gaving avatar monteiro avatar ronanguilloux avatar royopa avatar vladimirbasic avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

security-jwt-service-provider's Issues

cookies feature

Hello Cnam! send the token in a cookie is very efficient in a normal website that wants to be stateless. Cookies are quite safe and once obtained are automatically sent to the server. I would like this feature is implemented.

        //Snippet in Silex\Component\Security\Http\Firewall::handle

        if ($this->options['header_name'] == "Cookie" && $this->options['cookie_name']) {
            $cookie = $request->cookies->get($this->options['cookie_name']);
            $requestToken = $this->getToken($cookie);
        }
        else {
            $requestToken = $this->getToken(
            $request->headers->get($this->options['header_name'], null)
            ); 
        }   

Thank You.

fail to getUsername() on security.token_storage token

Hello,

I try to get the username on a secure route using:
$app['security.token_storage']->getToken()->getUsername()

and I get the following error:

PHP Notice:  Undefined property: Silex\Component\Security\Http\Token\JWTToken::$usernameClaim in C:\work\web\nova-backoffice\vendor\cnam\security-jwt-service-provider\src\Silex\Component\Security\Http\Token\JWTToken.php on line 60

Except for the secret_key and header_name, security.jwt configuration use the default settings.
The secure routes are defined like this:

    'secure' => array(
        'pattern' => '^.*$',
        'users' => $app['users'],
        'jwt' => array(
            'use_forward' => true,
            'require_previous_session' => false,
            'stateless' => true,
        )           
    ),

Version:

        "doctrine/dbal": "^2.5",
        "silex/silex": "~1.3",
        "symfony/security": "~2.7",
        "cnam/security-jwt-service-provider": "1.*"

Note that $token->setUsernameClaim($this->options['username_claim']); is properly called in JWTListener.php:65

Do you need more details, or there is something obvious I am doing wrong ?

Pimple 3.2.x support

It looks like the composer.json needs to be updated to support the current versions of pimple being pushed out:

  • Installation request for cnam/security-jwt-service-provider ^2.1 -> satisfiable by cnam/security-jwt-service-provider[2.1.1]
  • cnam/security-jwt-service-provider 2.1.1 requires pimple/pimple 3.0.* -> no matching package found.

Composer

Hello !

I don't know if it's a problem of mine, but I'm unable to add this project in my composer. Due to a confusion with pimple:

$ composer require cnam/security-jwt-service-provider
Using version 0.0.6.* for cnam/security-jwt-service-provider
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Can only install one of: pimple/pimple[v3.0.0, v1.1.1].
    - Can only install one of: pimple/pimple[v3.0.0, v1.1.1].
    - cnam/security-jwt-service-provider 0.0.6 requires pimple/pimple 3.0.* -> satisfiable by pimple/pimple[v3.0.0].
    - Installation request for cnam/security-jwt-service-provider 0.0.6.* -> satisfiable by cnam/security-jwt-service-provider[0.0.6].
    - Installation request for pimple/pimple == 1.1.1.0 -> satisfiable by pimple/pimple[v1.1.1].


Installation failed, reverting ./composer.json to its original content.

My require in my composer.json contain only this atm:

"require": {
    "silex/silex": "~1.2",
    "doctrine/dbal": "~2.5",
    "monolog/monolog": "1.x",
    "firebase/php-jwt": "~1.0"
  }

Example for logout?

If I have a defined firewall like this:

$app['security.firewalls'] = array(
    'login' => [
        'pattern' => 'auth',
        'anonymous' => true,
    ],
    'secured' => array(
        'pattern' => '^/api/',
        'logout' => array('logout_path' => '/v1/logout'),
        'security' => $app['debug'] ? false : true,
        'users' => $app['users'],
        'jwt' => array(
            'use_forward' => true,
            'require_previous_session' => false,
            'stateless' => true,
        )
    ),
);

and my API routes are like this:

/*
 * API Routes
 */
$api = $app['controllers_factory'];
$api->post('/auth', 'App\Controllers\API\AuthController::auth');
$api->get('/pages/{path}', 'App\Controllers\API\PageController::children')->assert('path', '.*');
[...]
$app->mount('/api/v1', $api);

How can I handle a logout call / route definition?

e.g. /api/v1/logout (destroy the user's session?)

AdvancedUserInterface::isEnabled not called

Hello,
I notice that you call $this->userChecker->checkPostAuth($user) in JWTProvider::authenticate
but checkPreAuth($user) is not called.
This make methods like AdvancedUserInterface::isEnabled() never being called.
Is it expected ? Or do I miss something ?

Token Prefix not working

Hi! I'm testing right now the workflow using the Silex Firewall and it seems broken. In the JWTListener, the option token_prefix is missing, so headers like the recommended by JWT are not valid:

Authorization: Bearer <token>

It works well if I remove the Bearer string. Instead of decoding the string directly the lib should remove the token prefix from the Request Header first.

Success and Failure Handlers not Called

How to make the Success and Failure Handlers get called upon authentication success/failure.
I setup according to the example provided but the specified handlers have no effect ..

` $app['security.authentication.success_handler.secured'] = function () use ($app) {
return new Authentication\AuthenticationSuccessHandler($app['security.http_utils'], []);
};

    $app['security.authentication.failure_handler.secured'] = function () use ($app) {
        return new Authentication\AuthenticationFailureHandler($app['request'], $app['security.http_utils'], []);
    };`

Could you give a less basic example?

I tried to use your provider but it doesn't seem to work. I can access every routes whereas I should be redirect to login route or raise an exception maybe.
Here is my code...

$app['security.jwt'] = array(
     'secret_key' => 'aze123&',
     'life_time'  => 86400, //life time token
     'options' => array(
         'header_name' => 'AUTH-HEADER-TOKEN' //header name for authorisation
     )
);
$app->register(new Silex\Provider\SecurityJWTServiceProvider());
$app['security.firewalls'] = array(
    'login' => array(
        'pattern' => 'login|register|oauth',
        'anonymous' => true,
    ),
    'secured' => array(
        'pattern' => '^.*$',
        'logout' => array('logout_path' => '/users/logout'),
        'users' => array(
            'admin' => array('ROLE_ADMIN', '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg==')
        ),
        'jwt' => array(
            'use_forward' => true,
            'require_previous_session' => false,
            'stateless' => true
        )
    )
);

Anyway, thank you for this code I was searching for a looong time !!

Example did not works

Your example of JWT service provider did not works. 'A Token was not found in the TokenStorage.' error occurs.

Can you explain it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.