Hi Everyone,
I need help to understand something. I'm using Alpinejs in Wordpress custom plugin to fetch and post data using APIs which I built in Laravel sanctum.
I'm using following fetch function fetchItems() { fetch('', { method: 'GET', headers: { 'Authorization': 'Bearer ', 'Content-Type': 'application/json', // Add other headers if needed }, }) .then(response => response.json()) .then(data => { this.items = data.data; this.loading = false; this.total_steps = this.items.length; if(this.items.length){ this.selections.techstack = this.items[0].techstack; } }) .catch(error => { console.error('Error fetching items:', error); this.loading = false; }); }, I've created bearer token as below in Laravel
public function createToken(Request $request) {
$validated = $request->validate([
'name' => 'required'
]);
$token = $request->user()->createToken($request->name);
$apitoken = new ApiToken();
$apitoken->name = $request->name;
$apitoken->token = $token->plainTextToken;
$apitoken->save();
return $this->jsonResponse(__('response.action.success'), []);
}
How I'm handling api routes in laravel
I'm working on localhost, I can see my bearer token is visible in chrome inspect elements. Can someone please help how I can protect my APIs.
Regards, Basit
Hello,
From what I understood, you want to protect your Bearer Token which is exposed on the client side. It's always going to be visible.
There are a few ways to protect your APIs further. It really depends on how you have setup your APIs.
https://laravel.com/docs/10.x/sanctum#issuing-api-tokens
There are a few ways to do this. You could create some middleware or setup a CSP.
https://laravel.com/docs/10.x/middleware
public function handle(Request $request, Closure $next): Response
You can use $request
to access the host, IP, etc. This may not be the best approach if the API is consumed directly by individuals.
I would personally reach for API tokens or a CSP.
https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
https://github.com/spatie/laravel-csp
I hope this helps.
I see you are trying to create a token. I'm not exactly sure what you are trying to do. I would suggest watching a course on here to get more familiar.
https://codecourse.com/courses/api-token-authentication-with-laravel-sanctum-airlock
This course covers things like protecting routes and associating token abilities.
If you don't have a Codecourse plan, today is the day to grab one at 50% off. I'm not sure where you are located but, Codecourse supports PPP if that option is needed.