Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel passport - CreateFreshApiToken no laravel_token cookie

CreateFreshApiToken, once added to 'web' middleware group in Kernel.php, is supposed to attach laravel_token cookie to response for every request coming through web middleware, isn't it? Eg anything in this group supposed to receive the cookie:

Route::group(['middleware' => ['web']], function () {
    Route::get('/{vue?}', function () { return view('index'); } )->where('vue', '[\/\w\.-]*');
});

I'm trying to replace current workflow that uses client_secret, seeing that oauth2 and website are on the same domain, the idea of self-consuming api with the help of CreateFreshApiToken had a nice ring to it, though at this point I'm not sure if I'm doing it right.

like image 855
ego Avatar asked Dec 08 '22 17:12

ego


1 Answers

Quoting my comment as requested

"You will not receive the token in this method. The cookie created will contain the encrypted token and will be used by the passport token guard to authenticate requests coming with the cookie. So the routes protected by the auth:api middleware will get authenticated without manually attaching any access token. So after the initial login (which should be the traditional way) you need to reload the page at least once so that the cookie gets created by the CreateFreshApiToken middleware."

Apart from that you can use the password grant for your SPA. This is what you would see 90% of the tutorials on the net do. But they store the client id and secret in the JavaScript file, which is very bad practise from a security perspective. To overcome this you can create a proxy route/middleware which injects the client id and secret. So you would just need to pass the email and password to obtain the access token and refresh token.

But again you need to store the access token and refresh token in the browser's local storage, which is what developers normally do. But the token becomes vulnerable to XSS attacks. So there are lot of angles to think about from a security perspective when working with SPA authentication.

To overcome all the above issues you need to store the token securely in a HttpOnly cookie and then use a middleware to resolve the token from the cookie and authenticate the user on any API request. This is the most practical and secure way of doing authentication with SPA. Laravel Passport does just that but needs some initial work with custom login routes to make it happen. The lack of proper documentation and clarity on it's usage and working is a problem with Passport.

Here are some good resources on these https://web.archive.org/web/20141208132104/http://alexbilbie.com/2014/11/oauth-and-javascript/

http://esbenp.github.io/2017/03/19/modern-rest-api-laravel-part-4/

https://stormpath.com/blog/token-auth-spa

like image 193
Sandeesh Avatar answered Dec 11 '22 12:12

Sandeesh