0

I have a laravel function for login which creates a sanctum token once successful:

public function attempt(Request $request)
{
    $validated = $request->validate([
        'email' => ['required', 'email'],
        'password' => 'required',
    ]);

    if (auth()->attempt(array_merge($validated, ['status' => '1']))) {
        $request->session()->regenerate();
        $user = auth()->user();
        $token = $user->createToken('sanctum-token')->plainTextToken;

        return redirect('/horseinfo')->with('message', __('errors.success'))->cookie('api_token', $token, 60, null, null, false, true);
    }

    return back()->withErrors(['email' => 'invalid email.'])->onlyInput('email');
}

Security isn't really my strength. Now, I've read that the token should be stored in an HTTP-only cookie to prevent JavaScript from accessing it. How can I get the cookie containing the token securely so I can access API routes with Sanctum auth when JavaScript cannot access the cookie?

my js has separate file. is it safe to add script on a blade template?

I am using fetch API to access api routes and have no idea how to get the token.

2
  • 1
    Not giving you access to the cookie in client-side JavaScript code, is the point of HttpOnly. Your own code doesn't need access - fetch itself will send the cookie. But if your request is cross-origin, you need to set credentials in your request options appropriately. Commented Jul 8, 2024 at 6:31
  • thank you for your answer. I've confirmed this since the fetch api on the same server doesn't require token but when used in another API handling software, it requires authentication. Commented Jul 10, 2024 at 1:33

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.