简体   繁体   中英

Laravel Passport grant API Token with session or restrict access to js files

Problem
I am using a jQuery AJAX call to access the API of my app. Since my Javascript files are, technically, accessible to the public, I can't put API Credentials in the this file. The web routes which access the protected API are guarded with a middleware which checks if the user has access. Technically, one could access the js files given the correct url . The admin pages would still not be accessible, but one could now access the API.

Question
I would like to know if there is a way to either
A) Use the session cookie to get the user and check if that user is an admin.
or
B) (Preferred) Make the js files only accessible to the web routes which use them (in my case, the admin routes)
or
C) Another option that I am clearly not seeing, that would solve my problem.

I am using Laravel's Passport API Authentication for the API routes.

PS: Typing the credentials in manually each time, is not an option. These routes, typically, need to be accessed quickly.

If I understand your question ... you can pass all the information that you want even the information that is in the session in ajax request, the only thing that you are going to need is some kind of middleware in the backend that check the session (any variable) was generated by the sever (your backend).

The algorithm it is going to be similar to the algorithm that check if the token that the user is using to access to the data was generated by the server. Do you understand the idea? Save in a database the 'session credentials' that you want to check if the user is an admin.

To answer the other question, you need some php file that handles the request and after that, if the user has permissions to access the js file, then you serve it.

At some time I use a similar algorithm to create a tracking system and serve a white pixel (a .jpg file), the only change is that I don't check for credentials.

Take care about don't forget to add the appropriate header in you file (the file with serves the js file) header("Content-Type: application/javascript");

I don't recommend use the session information to verify all of that things because there is possible to have security issues. If you can, use the token generated by the passport to verify that the user is an admin.

I hope I make myself clear in the explanation and you understand the idea. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM