Ssionn's avatar
Level 3

Authenticated user in Javascript file

I want to fetch the authenticated user in my app.js file because I need to grab an Oauth token for the spotify api, but what's the best way to fetch this data?

The issue is that I have something that's working but reveals sensitive information.

<script>
	var user = {!! auth()->user()->toJson() !!};
</script>

Then I can call it in my javascript file. Any other ways of doing this?

0 likes
1 reply
LaryAI's avatar
Level 58

To securely fetch the authenticated user in your JavaScript file without exposing sensitive information, you can use an API endpoint to retrieve the user data. This way, you can control what data is exposed and ensure that sensitive information is not leaked.

Here's a step-by-step solution:

  1. Create an API Endpoint: Create a route and controller method to return the authenticated user data.

  2. Fetch the Data in JavaScript: Use fetch or axios to call the API endpoint and retrieve the user data.

Step 1: Create an API Endpoint

In your routes/web.php or routes/api.php file, add a route to fetch the authenticated user:

// routes/api.php
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;

Route::middleware('auth:api')->get('/user', function () {
    return response()->json(Auth::user());
});

Step 2: Fetch the Data in JavaScript

In your app.js file, you can use fetch or axios to call the API endpoint and retrieve the user data. Here is an example using fetch:

// app.js
document.addEventListener('DOMContentLoaded', function() {
    fetch('/api/user', {
        headers: {
            'Authorization': 'Bearer ' + document.querySelector('meta[name="api-token"]').getAttribute('content')
        }
    })
    .then(response => response.json())
    .then(user => {
        console.log(user);
        // Now you can use the user data to get the OAuth token for Spotify API
    })
    .catch(error => console.error('Error fetching user:', error));
});

Step 3: Ensure API Token is Available

Make sure you have an API token available in your HTML. You can include it in a meta tag:

<!-- In your Blade template -->
<meta name="api-token" content="{{ auth()->user()->api_token }}">

Security Considerations

  • Use Middleware: Ensure that your API route is protected by authentication middleware.
  • Limit Data Exposure: Only return the necessary user data in your API response to avoid exposing sensitive information.

By following these steps, you can securely fetch the authenticated user data in your JavaScript file without exposing sensitive information directly in your HTML.

Please or to participate in this conversation.