Giter VIP home page Giter VIP logo

slim-csrf's People

Contributors

akrabat avatar alexweissman avatar andrewcarteruk avatar ayesh avatar blizzz avatar cbenard avatar chocolatkey avatar codeguy avatar coolgoose avatar cwreden avatar davidepastore avatar dependabot-preview[bot] avatar dependabot[bot] avatar designermonkey avatar dopesong avatar geggleto avatar ivandokov avatar joebengalen avatar juliangut avatar l0gicgate avatar markusdosch avatar masakielastic avatar nbayramberdiyev avatar odan avatar schnittstabil avatar silentworks avatar slamdunk avatar thomas-lb avatar tuupola avatar zzgab 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

slim-csrf's Issues

Don't regenerate token on each request?

I load two pages with form, in different browser tabs. As the CSRF token is regenerated on each request (GET as well as POST), the first form will fail submitting.

If this issue is worked on, here is the next pitfall to expect: Submitting a form shouldn't make the other forms, opened in other tabs already, to fail.

I had a look at Laravel, it generates the token only if it doesn't exist yet. It never regenerates it, even after a form submission. (VerifyCsrfToken.php, Store.php)

How to validate subsequent AJAX requests?

It seems to work on the first submit, but if submitted again, the tokens are invalid. Any strategies on how to refresh tokens for subsequent Ajax requests with the need for 'refreshed' tokens to pass along?

Automatically set CSRF value in middleware

$app->add(function ($req, $res, $next) {
    $nameKey  = $this->csrf->getTokenNameKey();
    $valueKey = $this->csrf->getTokenValueKey();

    $this->view['csrf_key_name']      = $nameKey;
    $this->view['csrf_value_name']    = $valueKey;
    $this->view['csrf_key_content']   = $req->getAttribute($nameKey);
    $this->view['csrf_value_content'] = $req->getAttribute($valueKey);

    return $next($req, $res);
});

When I place the code in the middleware, only the first 2 lines that have value while $req->getAttribute($nameKey) and $req->getAttribute($valueKey) return empty. But,, they work when $req is in the context of app route.

Is there any way to make this work so that I don't need to write those 4 lines in every route? Thanks

composer raise warnings

MacBook-Pro-van-Tim:my-app tim$ composer require slim/csrf
file_put_contents(/Users/tim/.composer/cache/repo/https---packagist.org/packages.json): failed to open stream: Permission denied
https://packagist.org could not be fully loaded, package information was loaded from the local cache and may be out of date
Using version ^0.1.0 for slim/csrf
./composer.json has been updated
Loading composer repositories with package information
file_put_contents(/Users/tim/.composer/cache/repo/https---packagist.org/packages.json): failed to open stream: Permission denied
https://packagist.org could not be fully loaded, package information was loaded from the local cache and may be out of date
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for slim/csrf ^0.1.0 -> satisfiable by slim/csrf[0.1.0].
    - Conclusion: remove psr/http-message 1.0
    - Conclusion: don't install psr/http-message 1.0
    - slim/csrf 0.1.0 requires psr/http-message ~0.9 -> satisfiable by psr/http-message[0.10.0, 0.10.1, 0.11.0, 0.9.0, 0.9.1, 0.9.2].
    - Can only install one of: psr/http-message[0.10.0, 1.0].
    - Can only install one of: psr/http-message[0.10.1, 1.0].
    - Can only install one of: psr/http-message[0.11.0, 1.0].
    - Can only install one of: psr/http-message[0.9.0, 1.0].
    - Can only install one of: psr/http-message[0.9.1, 1.0].
    - Can only install one of: psr/http-message[0.9.2, 1.0].
    - Installation request for psr/http-message == 1.0.0.0 -> satisfiable by psr/http-message[1.0].


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

Remove storage check on guard construction

Hello.
The Guard class validates storage on construction. This forces to start session globally and makes impossible to have routes without session.
I use a middleware to start the session and i apply it only to some routes.

Storage limit is not enforced during failed POST

If a POST, PUT, DELETE, PATCH fails the storage limit is not enforced. I set the storage limit to one in the hopes that always only one valid CSRF token was available. But when the check failed it didn't enforce the limit thus making two CSRF available at the same time.

Security Access - Token Generation

I don't understand about generation of security tokens. Example:

$app->get('/foo', function ($request, $response, $args) {
// CSRF token name and value
$nameKey = $this->csrf->getTokenNameKey();
$valueKey = $this->csrf->getTokenValueKey();
$name = $request->getAttribute($nameKey);
$value = $request->getAttribute($valueKey);
});

$app->post('/bar', function ($request, $response, $args) {
// CSRF protection successful if you reached
// this far.
});

If /foo is public, anyone can generate a token and use to valid the access to another method (/bar). Any help about it?

Cannot get request's nameKey and valueKey when 'setPersistentTokenMode' is set to true

After setting PersistentTokenMode to true, $request->getAttribute($nameKey) and $request->getAttribute($valueKey) will be null.

However, using getTokenName and getTokenValue is working properly. I am aware that PR #67 should be fixing this issue, but it is still not working properly. Any suggestions? Thanks!

    // CSRF token name and value
    $nameKey = $this->csrf->getTokenNameKey();
    $valueKey = $this->csrf->getTokenValueKey();
    $name = $this->csrf->getTokenName();
    $value = $this->csrf->getTokenValue();

    // NOT WORKING WHEN Token is persistent
    // $name = $request->getAttribute($nameKey);
    // $value = $request->getAttribute($valueKey);

Random Compact Version Issue

The version constraints on the paragonie/random_compat package allow version 1.4.x to be installed, and version 1.4, the usage of OpenSSL was returned, to allow version 2 to completely and finally remove it.

OpenSSL, as explained on ParagonIE's blog, is not a secure random generator, and i believe if it's worth using a "secure" random generator, than even allowing an insecure option should not be permitted.

Resolving this would be as simple as changing the version constraints of paragonie/random_compat to >=1.3 <1.4 or better yet, updating to Version 2. The only problem with this, is it will cause problems with other packages (EG: Illuminate/Support has a version constraint of ~1.4)

How to integrate slim-session

Hey!

I'd like to integrate slim-csrf (v0.8.3) with https://github.com/bryanjhv/slim-session (v3.0).
It seems that slim-csrf directly accesses $_SESSION, but I'd need it to utilize new \SlimSession\Helper() instead.
Is this achievable? I'd like to avoid having to upgrade my complete application from slim3 to slim4.

Thanks in advance!

1.0.0 throws errors at Slim 3

Hello.

As post title, 1.0.0 throws parameter errors at Slim 3.

When I remove it and go back to install the older version and it works well.

composer require slim/csrf:0.8.3

Twig Extension Not Working

The values are not generated unless they are manually generated. Here is the code below:

Injecting into twig:

// Twig-View Render
$container['view'] = function ($container) {
    $view = new \Slim\Views\Twig(__DIR__ . '/../templates', [
        'cache' => false
    ]);
    $basePath = rtrim(str_ireplace('index.php', '', $container->get('request')->getUri()->getBasePath()), '/');
    $view->addExtension(new Slim\Views\TwigExtension($container->get('router'), $basePath));
    // Global CSRF Extension
    $view->addExtension(new Test\Library\Twig\CsrfExtension());
    return $view;
};

Twig Extension:

<?php


use Twig_Extension;
use Twig_Extension_GlobalsInterface;
use \Slim\Csrf\Guard as Csrf_Guard;

class CsrfExtension extends Twig_Extension implements Twig_Extension_GlobalsInterface
{
    protected $csrf;
    
    public function __construct()
    {
        $this->csrf = new Csrf_Guard;
        $this->csrf->setPersistentTokenMode(true);
    }

    public function getGlobals()
    {
        // CSRF token name and value
        $csrfNameKey = $this->csrf->getTokenNameKey();
        $csrfValueKey = $this->csrf->getTokenValueKey();
        $keyPair = $this->csrf->generateToken();
        return [
            'csrf'   => [
                'keys' => [
                    'name'  => $csrfNameKey,
                    'value' => $csrfValueKey
                ],
                'name'  => $keyPair['csrf_name'],
                'value' => $keyPair['csrf_value']
            ]
        ];
    }

    public function getName()
    {
        return 'slim/csrf';
    }
}

Managing CSRF with cookies disabled

The middleware makes use of PHP Sessions, which in turn requires cookies to be enabled on the web application. Some users set their browser to disable all cookies and as such the middleware will return a 400 error. Is there a way we can either a) re-route if cookies are not enabled or b) make use of an alternative store other than PHP Sessions?

Session storage validation

I am trying to implement @akrabat's Session Middleware and Slim-Csrf middleware together, but the validation in the __construct is blocking me (or I don't see the correct way).

I am registering both middlewares as follows:

$app->add(new \RKA\SessionMiddleware(['name' => 'session']));
$app->add(new \Slim\Csrf\Guard);

but I always get CSRF middleware failed. Session not found. Changing the order of the registration of these middlewares is not helping either. I think the reason is that the validation for existing session is done at initialization of the Guard class and this is not giving change of the previous middleware to start the session because it's not yet invoked.

Double-submit cookie defense pattern

I think double-submit cookie defense pattern is the best way against CSRF:

  • You don't need to save the token in a server (session-based CSRF protection).

  • It's scalable and easy to implement.

Would it make sense to implement it?

Note: if yes, this middleware, created by me, could be useful.

check fails with js and application/x-www-form-urlencoded

I had some problems to set up the csrf-check with ajax-calls and pure javascript, until I understood, that you have to set the right headers in your xhr-call. It works with:

xhr.setRequestHeader('Content-Type', 'application/json');

It does not work with

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

If you want to use the detection with isXHR, you also have to set the header

xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

There are only jquery examples out there, so I post this just for others to avoid the headache that I got (probably because of a lack of http-knowledge).

Delete if this does not help anyone...

add .gitattributes file

I see the slimphp/slim repository has a .gitattributes file that excludes tests from the composer download when --prefer-dist is provided. Can you maybe add this file to this repository, too? And also maybe to /Twig-View and /Slim-Csrf? Thank you.

New token on each page load

This is more a question than an issue but it can lead to a PR.

The problem

This middleware generates a new token for each request and use the request attribute to pass this token along. Some pages doesn't have forms (a csrf token is not needed) but this middleware will query the session and generate a token anyway.
Another issue happens if we have 2 forms on the same page that can be submitted using ajax (with persistent set to false). It's more an edge but it can happen.

Proposed solution

I think a better solution would be to "store" a new token when we generate a new one. This way the session won't be modified when token aren't necessary. Moreover we won't have to pass the request to the token generator making dependency injection (I'm not a huge fan of using request within my container).

// The middleware will be the same
$app->add(Guard::class)
// but the generator will be different
$container->get(Guard::class)->getTokenValueKey() // string
$container->get(Guard::class)->generateToken() // string
// maybe offer an helper
$container->get(Guard::class)->input()

I think it could be a better solution but this change will break the backward compatibility. So there is 2 solutions :

  • Create a new Guard (RequestIndependentGuard)
  • Create a new library (if you don't think this should be included for slim)

Thanks

Adapter for Laravel sessions

I'm looking to replace the native $_SESSION superglobal in my app with Laravel sessions. Laravel's sessions seem to build, in turn, on Symfony sessions, which implement IteratorAggregate and Countable. However, they notably do not implement ArrayAccess, which appears to be required for Slim-Csrf:

    /**
     * CSRF storage
     *
     * Should be either an array or an object. If an object is used, then it must
     * implement ArrayAccess and should implement Countable and Iterator (or
     * IteratorAggregate) if storage limit enforcement is required.
     *
     * @var array|ArrayAccess
     */
    protected $storage;

How difficult would it be to relax this requirement? Would an adapter be needed to fetch and store data from the Laravel/Symfony sessions?

Cannot unset string offsets

I integrated Slim-Csrf like in the description and it works fine with php´s own webserver but if i try to work on a apache server the following appear on a post request:

slim_csrf_error

Any Ideas?

How to instantiate with $persistentTokenMode = true

In order to use persistent tokens, you advise to "set the sixth parameter of the constructor to true." Considering future updates, is there a more flexible way to e.g. instantiate with true other than hard-coding the value in the constructor itself? I tried it the following way, and verified that $persistentTokenMode was indeed true. However, the names and keys were then empty in the route view:

$app->add($container->get('csrf'));
$container->csrf->setPersistentTokenMode(true);

Hard-coding $persistentTokenMode = true also results in empty values. (I'm using Twig)

Slim Middleware vs Pimple service

Is there any reason to implement ServiceProviderInterface?

I used this class as an example to build a Menumanager middleware which may be also registered as service, but there is a conflict: Both middleware and pimple call by default the __invoke method, each with different arguments (RequestInterface, ResponseInterface, callable vs \Pimple\Container).

I've work around that by registering the middleware's method like so:

$app->add('menumanager:run');

but I wonder it's good idea to have one class for both things. In case of Slim-Csrf there are no public methods or properties to use (except register) so I see little use as a service anyway.

[Discussion] Source code using PSR-7 Interface or Slim Interface

I see a lot of TypeHinting PSR-7 interface but usage of Slim Add-On methods.

Using the PSR-7 Type-Hint's seem wrong since we are requiring methods that only exist on the Slim\Http versions.

Thoughts on changing this?

Examples:
https://github.com/slimphp/Slim-Csrf/blob/master/src/Guard.php#L128
https://github.com/slimphp/Slim-Csrf/blob/master/src/Guard.php#L162-L163
https://github.com/slimphp/Slim-Csrf/blob/master/src/Guard.php#L314
https://github.com/slimphp/Slim-Csrf/blob/master/src/Guard.php#L297-L298

Corrupted session storage generates warning in PHP7.2

When the default session storage for the CSRF class is corrupted for some reason and saved in the session with a value different from an array in PHP7.2 the native count() function now throws a warning. The warning is throw in Slim\Csrf\Guard::getLastKeyPair() on line 303. This to be fixed we should first check if the storage in the session is an array or not in the method Slim\Csrf\Guard::validateStorage() right after we check if the session array contains a key with the given prefix.

I'll try to do a fix on this issue.

CSRF failure needs to be customisable

When the CSRF fails, then this code is executed: return $response->withStatus(400);

This results in a blank browser. Ideally, I would would to display the form again with an error message at the top saying that there was a failure.

Store latest generated Name, Token

I am trying to create a slim-csrf-twig extension. Using Constructor injection you can get a Request object, however this is before the middleware is run...in my case at the route level. I also inject the Guard class.

The request object does not contain the name, and token and it only exists on the request object passed through the middleware.

I think that is a design flaw. The last generated name, token should be accessible via the Guard class as protected members with a getter. Thus I will only need to inject the Guard class into the extension and I will be happy to make it available to everyone :)

namespace VMS\Helpers;


use Slim\Csrf\Guard;
use Slim\Http\Request;

class CsrfHelper extends \Twig_Extension
{

    private $request;

    private $guard;

    public function __construct(Request $request, Guard $guard)
    {
        $this->request = $request;
        $this->guard = $guard;
    }

    public function getName()
    {
        return 'csrfSlim';
    }

    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('csrf_element', array($this, 'csrfElement')),
        ];
    }

    public function csrfElement()
    {
        $nameKey = $this->guard->getTokenNameKey();
        $valueKey = $this->guard->getTokenValueKey();
        $nameValue = $this->request->getAttribute($nameKey);
        $valueValue = $this->request->getAttribute($valueKey);
        return '
        <input type="hidden" name="'.$nameKey.'" value="'.$nameValue.'">
        <input type="hidden" name="'.$valueKey.'" value="'.$valueValue.'">
        ';
    }

}

//cc @akrabat @codeguy @silentworks

CsrfExtension name & value empty in Twig Extension

No matter what I try the getTokenName() & getTokenValue() methods always return null.

I copied and pasted the CsrfExtension straight from the the docs.
Registered in my ViewServiceProvider and passed CsrfExtension the container instance of Guard.

function register()
    {
        $this->getContainer()
             ->share('view', function () {

                 $view = new Twig(base_path('resources/views/'), [
                     'cache' => base_path('storage/cache/views'),
                     'debug' => config()->get('app.debug') // this also auto reloads views cache if set to true
                 ]);

                 // Instantiate and add Slim specific extension
                 $uri = $this->getContainer()->get('request')->getUri()->getBasePath();
                 $basePath = rtrim(str_ireplace('index.php', '', $uri), '/');
                 $view->addExtension(
                     new TwigExtension($this->getContainer()->get('router'), $basePath)
                 );

                 // add app specific Twig extensions
                 $view->addExtension(
                     new CsrfExtension($this->getContainer()->get('csrf'))
                 );

                 return new View(
                     $view,
                     $this->getContainer()->get('request'),
                     $this->getContainer()->get('response')
                 );
             });
    }

If I do this though inside the CsrfExtension, I get key and value:

function getGlobals()
    {
        // CSRF token name and value
        $keyPair = $this->csrf->generateToken();

        return [
            'csrf' => [
                'field' => '
                <input type="hidden" name="' . $this->csrf->getTokenNameKey() . '" value="' . $keyPair['csrf_name'] . '">
                <input type="hidden" name="' . $this->csrf->getTokenValueKey() . '" value="' . $keyPair['csrf_value'] . '">
            ',
            ]
        ];
    }

Outputs:

array:2 [▼
  "csrf_name" => "csrf5b37612c206c8"
  "csrf_value" => "57e1d057703cb37a97eea2c6d85f5f65"
]

Is there anything wrong with doing it this way?

I'm just really curious why the other methods aren't working...
Tried sifting through the source but am really unsure why this isn't working

CSFR tokens for multiple forms\post per page (Ajax)

I have a Page that dynamically loads multiple forms via ajax let say each form is supposed to be a like button,

so when CSFR is disabled forms works fine , and no exception is thrown ,but when enabled the problem appear
the problem is the first request will work because the tokens will match
but since ajax will not refresh the page the other forms will still have the old token so any subsquent request will not work and "Failed CSRF check!" exception will be thrown ,
i searched a lot for a solution and i find a tedious one which is to return the new csrf in the response to the AJAX post, then update the value of the csrf token field but it is not a fancy soulotion besides im using a CSRF middleware to append the values automaticly

` public function __invoke($request, $response, $next){

    $nameKey = $this->container->csrf->getTokenNameKey();
    $valueKey = $this->container->csrf->getTokenValueKey();

    $name = $this->container->csrf->getTokenName();
    $value = $this->container->csrf->getTokenValue();

    // Render HTML form which POSTs to /bar with two hidden input fields for the
    // name and value:
    $output  = '<input type="hidden" name="'.$nameKey .'" value="'.$name .'">';
    $output .= '<input type="hidden" name="'.$valueKey.'" value="'.$value.'">';

    // Append The CSRF Gards To The View
    $this->container->view->addAttribute('csrf_gards', $output );

    // Pass the Request to the next one
    $response = $next($request, $response);
    return $response;
}`

a nice approach like CodeIgniter would be to allow this kind of behavior
$config['csrf_regenerate'] = FALSE;

so any help would be appreciated

Token is not deleted after validation

Until version 0.8.3 the used token is removed:

        // If we're not in persistent token mode, delete the token.
        if (!$this->persistentTokenMode) {
            $this->removeFromStorage($name);
        }

(https://github.com/slimphp/Slim-Csrf/blob/0.8.3/src/Guard.php#L254-L257)
and a new token is generated after validation:

// Need to regenerate a new token, as the validateToken removed the current one.
$request = $this->generateNewToken($request);

(https://github.com/slimphp/Slim-Csrf/blob/0.8.3/src/Guard.php#L152-L153)

Is there any particular reason why the token is no longer deleted in the latest version for slim 4?

Slight quibble about implementation

One of my team has been using this and having difficulty in understanding it's implementation due to the fact that a fresh token pair is generated on every single request.

It wasn't until he told me that the ajax side of the project was complicated due to having to get access to the right token for each step of a request system that I looked up CSRF in general.

https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#General_Recommendation:_Synchronizer_Token_Pattern

This is a resource that I found that suggests it should be one token per session. Is there any reason that this implementation is one per request?

Session Expires Quickly

Hello,

I am using the Gaurd with the following arguments:

new \Slim\Csrf\Guard('csrf', $_, function(Request $request, Response $response, $next) {
  return $response
    ->withStatus(400)
    ->withHeader('Content-type', 'text/plain')
    ->write('Security check failed. Please refresh the page.');
}, 200, 16, true));

I have users reporting that when they leave the page sit 30–60 minutes, the CSRF check fails on the next API request. I have been able to reproduce this on Mobile Safari on iOS. As far as I know, nothing is killing the session, as the user is still logged in. Any idea why this would be happening? I don't see anything in the code about how long to keep the tokens, so I would expect them to last as long as the session.

API csrf

Hi, i'm using Slim Framework as my first framework and i saw videos about how works it. It's simple and great but i have hm... doubts...

I'm doing a web service with Csrf and works well but i have problems cause i'm trying to sign up or sign in with a smartphone. Well... I did ajax the problem is the CSRF i'm trying to disable for some kind of routes without success.

I'm trying to find an example for dummies ^^'.

I tried to delete the "add(container->csrf)" from kernel to add it to every route but it doesn't work.

Thanks for your time!

How to validate AJAX with CSRF ?

Hello guys I have a little problem I am using slim 3 framework along with slim-csrf what I did is registering the csrf to the container I aslo created a csrfExtension that extends the twigExtension.
in the csrfExtenstion class I created a method that return the csrf fields neede markup this way I don't need to retype the whole markup in my forms I just call the function that I created and it works fine.

Now the problem is in my website admins-panel page there is a lot of ajax requests that I want to apply the csrf on here is where the problem appears the csrf only works for the first request but it will give an error on any other request cause the csrf_name and csrf_value that I am picking from my view has expired so how to get the new csrf_name and csrf_value so I can pass them along with my other ajax requests.

hope you can help me
Thanks in advance

Review

Hi Josh Lockhart,

I don't believe mt_rand is a nice candidate. So the line

$token = hash("sha512", mt_rand(0, mt_getrandmax()));

seems not safe to me. I don't recall the discussion thread, but there was one.

It was also in @auraphp Session . See commit auraphp/Aura.Session@7e3c836

Later iirc after reviewed by ircmaxwell , it was changed to make use of a RandomInterface, via which you can incorporate something like RandomLib or Random generators.

It will be nice, if there is a way we can incorporate libraries. So only need to deal with one library for security.

https://github.com/auraphp/Aura.Session#defending-against-csrf

Thanks!

Option to whitelist routes

Right now, we can use the CSRF middleware in one of two ways: either applied to all routes, or on a route-by-route basis.

It would be nice if there were an option to whitelist certain routes, so that CSRF checks are performed on all routes except those explicitly listed.

add redirect to setFailureCallable

I've added the setFailureCollabel to my code but I ran into a small problem.
That's my code:

$guard->setFailureCallable(function ($request, $response, $next) use ($c) {
    $response = $response->withRedirect( $c->get('router')->pathFor('index'));
    return $next($request, $response);
});

So when the CSRF failed I would like to redirect the User to the index route.
The problem is that slim itself still continue to run my code so the authentification process which i have in my login POST route code gets called and the user gets logged in.

So my question is, is there a way to tell slim in the setFailureCallable that he have to please quit everything and just to the redirect richt now?

The workaround would be here to use the example with withAttribute but then I had to add a IF block in every POST route code to check if it is false and then don't execute the POST code.

Add Persistence Option / Guard for Tokens

It would be great to have a way to 'persist' tokens for subsequent attempts on requests. Please take a look at this issue which outlines a valid use case for such a scenario.

Via @geggleto

The fix is a guard around
[ https://github.com/slimphp/Slim-Csrf/blob/master/src/Guard.php#L204 ], using what I think would be a controllable setting. We would keep the default currently which would be "strict" => true

Problem with cross-domain ajax

Hi people. I'm using Slim for REST API and Vue2 + Webpack for frontend.

I want to make POST request, data is sending good, but slim said: 'Failed check csrf', i made route to return csrf_name and csrf_token, for example:

get CsrfToken.php

<?php
/**
 * @var $csrf \Slim\Csrf\Guard
 */
$csrf = $this->container->get('csrf');

print json_encode($csrf->generateToken());
?>

and my ajax is:

<script>
    fetch('/', {
        method: 'post',
        credentials: 'include',
        headers: {
            'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: 'csrf_name=csrfName&csrf_value=csrfValue'
    })
        .then(function (response) {
            return response.text();
        })
        .then(function (response) {
            console.log(response);
        })
</script>

Tell me pls, what i am doing wrong?and how do I make a POST request?

Session generate on each reload and did not clear the old session.

I use this manual code

session_start();

$slimGuard = new \Slim\Csrf\Guard;
$slimGuard->validateStorage();

// Generate new tokens
$csrfNameKey = $slimGuard->getTokenNameKey();
$csrfValueKey = $slimGuard->getTokenValueKey();
$keyPair = $slimGuard->generateToken();

// and put those name, value, keypair into input hidden.

and then write out the sessions.

echo '<pre>'.print_r($_SESSION, true).'</pre>'."\n";

Every time I reload the page, it generate new token session and did not clear the old one.
12 times of page load means 12 sessions and more...

I think this make a lot of junk token that is never use. How to clear the old session before generate the new one? Or is this a bug?

Session filling up

Is this supposed to generate a new key => value for every page load?

I am testing a session component and had this middleware activated. Whenever I refresh the page, another pair is added, and none are cleaned up.

Why is failureCallable not an Exception?

I'm wondering why failureCallable is a Closure and not a thrown Exception/Error?

With an exception we can use the Slim errorHandler functionality. Unless you use Slim for an API, I think there's a big chance that you're using the Custom Error Handling since you want errors to look good within your template.

I understand this would be difficult to change now, but I'm just wondering why this was chosen.

For completeness sake, this is what I'm doing to solve it for myself;

$guard->setFailureCallable(function($request, $response, $next) use ($errorHandler, $c){
        return $errorHandler($c)($request, $response, new Exception('failed csrf check'));
});

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.