1
votes

I have a simple web app using regular authentication for all of my web routes. There are just a few places in my app where I want to be able to call a few API routes from Javascript. Can I setup Sanctum's SPA authentication to work without doing an SPA-style login?

I have followed the instructions server-side, and on my login page I am doing a CSRF cookie request using the axios library before the user logs-in using the standard routes. But when I try to then hit a Sanctum protected route I just get redirected to the home page.

Is it expected that Sanctum session-based auth should work with a regular app login?

Edit

I located the problem. In EnsureFrontendRequestsAreStateful is this function:

public static function fromFrontend($request)
{
    $referer = Str::replaceFirst('https://', '', $request->headers->get('referer'));

    $referer = Str::replaceFirst('http://', '', $referer);

    return Str::startsWith($referer, config('sanctum.stateful', [])) ||
           Str::is(config('sanctum.stateful', []), $referer);
}

$referer is null on my requests, so this function cannot return true. If 'referer' is changed to 'host' it works. Is this acceptable? Does it satisfy the point of the function still, that the "given request is from the first-party application frontend" or are there security implications I haven't considered?

2

2 Answers

0
votes

'Referer' works when hitting the API endpoint from Javascript, but when hitting it from Postman or in a browser window the headers non-existence causes a problem. So in simple GET testing it is redirecting to login, but is working fine when called from the Axios library in a Vue component.

0
votes

'Referer' works in postman too, you need only add header to your request Referer -> {{host}}. host it's postman variable or you can type it like localhost. Sanctum by default checking this referers localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1, but you can specify your own referer by adding variable to env file SANCTUM_STATEFUL_DOMAINS=your-app-domain.com here.