Skip to content

Obtaining a valid CSRF #158

@robinbeatty

Description

@robinbeatty

Just wanted to some advice on how I would go about obtaining a valid CSRF for an authenticated user?

I need to hit some craft factory actions and some custom endpoint validated by CSRF from a headless application in which the user is authenticated by your plugin.

Have tried appending a CSRF token to the JWT payload like this:

`
public function addJwtClaims(JwtCreateEvent $event)
{
$builder = $event->builder;

    $request = Craft::$app->getRequest();
    $csrfToken = $request->getCsrfToken();
    $csrfIsValidForUser = $request->validateCsrfToken($csrfToken);
    $builder->withClaim('csrf_token', $csrfToken);
    $builder->withClaim('csrf_token_valid', $csrfIsValidForUser); // true in all cases
}

...

Event::on(
        TokenService::class,
        TokenService::EVENT_BEFORE_CREATE_JWT,
        [$this, 'addJwtClaims']
    );

`

I then decode the base64 JWT and retrieve the token.

When I use this token in the req headers (X-CSRF-Token) it won't validate (Bad request etc).

Have also tried explicitly returning just the token from a separate endpoint (actionGetCsrf) which gives me a different token but still not valid.

Any advice? Feel like there's a crucial part of the puzzle I'm missing...
Thanks

Craft 4.9.5

Metadata

Metadata

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions