/pusher/auth endpoint returning 404 in Laravel - php

I have built a Laravel app where I am trying to implement Web Sockets via Pusher.com (for the first time).
While I have got public channel subscriptions working fine, I am struggling getting private channels working correctly.
According to the laravel documentation you need to uncomment App\Providers\BroadcastServiceProvider::class in app.php config file which I have.
My channels.php has the following rule(s)
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
Broadcast::channel('private-queue.business.{business}', function ($user, Business $business) {
// #todo: add real authentication
return true;
});
Is there anything else I need to add to get /pusher/auth endpoint working?

As of Laravel 7.x, the Broadcasting endpoint is broadcasting/auth and not pusher/auth.
I needed to update my JS like so to be able to define a custom auth endpoint:
const pusher = new Pusher('{{ env('PUSHER_APP_KEY') }}', {
cluster: '{{ env('PUSHER_APP_CLUSTER') }}',
authEndpoint: '/broadcasting/auth',
auth: {
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}',
}
}
});
You will need to add the CSRF-TOKEN otherwise you will get Page Expired errors.

Could you try:
Try this:
Uncomment App\Providers\BroadcastServiceProvider::class in config/app.php
Use php artisan config:cache
Use php artisan route:cache
Check new route broadcasting/auth with php artisan route:list
Source

Related

Laravel Sanctum returning 401 when trying to get the authenticated user

I want to get the currently logged in user whenever my React SPA starts, so I can show the user's information, but every time I try to get it from my Laravel back-end I get a 401.
I am using Laravel + Sanctum for my API, and using React in a different project for the front-end.
BACK-END:
I have the following in my AuthController controller:
public function user()
{
return auth()->user();
}
Inside my routes api.php I have the following route:
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::get('/user', [AuthController::class, 'user']);
Route::post('/logout', [AuthController::class, 'logout']);
});
My .env file contains the following:
SANCTUM_STATEFUL_DOMAINS=localhost:3000
SESSION_DOMAIN=localhost
FRONT-END:
I have a context that has the following:
useEffect(() => {
apiClient()
.get("/api/user")
.then((res) => {
setUser(res.data.user);
});
}, []);
and if you are wondering, my apiClient() comes from here:
import axios from "axios";
const apiClient = () => {
const api = axios.create({
baseURL: "http://localhost:8000",
withCredentials: true,
headers: {
Accept: "application/json",
},
});
return api;
};
export default apiClient;
This context is at the top level of the application.
I am not sure what's going on, my route /login is working as expected, I send the request and receive the user information as response which I set to a React state. On page refresh this state is removed because that's how Javascript works. I want to set it again using the useEffect mentioned above, so when the user loads the web app after closing the browser they can still see their information.
Thanks in advance!
To authenticate your SPA, your SPA's "login" page should first make a request to the /sanctum/csrf-cookie endpoint to initialize CSRF protection for the application:
axios.get('/sanctum/csrf-cookie').then(response => {
//Login...
});
For more information check https://laravel.com/docs/8.x/sanctum#spa-authentication

Routes going through api.php returning unauthorised whereas the same route going through web.php works

I have a page which enables users to create 'folders'. I'm using the function below to getAll folders belonging to each user, so when a user logs in they should see all of their folders but not the folders of other users.
/**
* Retrieve all user folders
*
* #return Response
*/
public function getAll()
{
// notes associated to folder included
return Folder::where('user_id', Auth::user()->id)->get();
}
This is what the vue page used to load all folders looks like:
<template>
<v-app id="inspire">
<v-card v-for="folder in folders" :key="folder.id">
<v-card-text>
Name: {{ folder.name }}
</v-card-text>
</v-card>
</v-app>
</template>
<script>
import { mapState } from "vuex";
export default {
computed: {
...mapState(['folders'])
},
mounted() {
this.$store.dispatch('getAllFolders');
}
};
</script>
This is what the getAllFolders method looks like:
getAllFolders() {
apiClient.get(window.routes['folders.getAll'])
.then(function(response){
console.log(response)
})
.catch(function(error){
console.error(error);
});
},
Adding the route to web.php works and allows for each user to see their relevant folders:
Route::get('folders/get-all', 'FolderController#getAll')->name('folders.getAll');
However adding it to api.php leads to unauthorised errors:
Route::middleware(['auth:api'])->group(function () {
Route::get('folders/get-all', 'FolderController#getAll')->name('folders.getAll');
Route::apiResource('folders', FolderController::class);
});
What might I be doing wrong?
Api routes are stateless, they are designed for requests coming from 3rd parties and will require an auth token, which you can generate using a package like Laravel Sanctum.
See: https://laravel.com/docs/8.x/sanctum#api-token-authentication
If you are doing ajax requests from your own front end then this is adding unneeded complexity. Stick to web.php, which does not apply the api middleware, and add your own prefex so you can tell apart your html and ajax end points. Ie '/data/user_folders'.

Axios call to laravel backend in nuxt.js

I am trying to get a laravel-nuxt project running. I am stuck with creating route calls to my laravel backend using axios async call to serve up data to my nuxt frontend before loading the page.
I am constantly getting getting a 404 with my current laravel-nuxt setup even though I have the route defined in api.php.
I am using this as a template for the project and I have not changed anything in that template yet:
https://github.com/cretueusebiu/laravel-nuxt
So my frontend call is this here:
async asyncData ({ $axios }) {
if (process.server) {
return $axios.$get('/api/data')
.then((res) => {
this.data = res.data;
})
}
}
And my backend route is defined as follows in api.php:
Route::get('/data', 'HomeController#index');
It always gives me a 404, is there something missing that I should be aware of?
According to the Readme in the Github project you have mentioned, you have to add your routes manually to
client/router.js
Read this line under Notes and follow the structure well you'll be able to avoid this.
This project uses router-module, so you have to add the routes
manually in client/router.js.
hope this helps.

Laravel Passport + VueJS: Unauthenticated error

I'm currently building a laravel 5.4 powered page to manage users. I've done all basic pages such as home, login, register, dashboard using blade templating engine. Now I'm building the User Management page. I've successfully implemented VueJS for this particular page. All components are working perfectly.
Now the problem I'm facing now is using Axios to get logged in user data from API route. At first I'm using usual api route to get auth()->user() data but it doesn't work.
I've learned that I must use Laravel Passport to do this API operation.
These are the steps I made after that:
composer require laravel/passport
php artisan migrate
php artisan passport:install
Added the Laravel\Passport\HasApiTokens trait to your App\User model
Called the Passport::routes method within the boot method of your AuthServiceProvider
Set the driver option of the api authentication guard to passport
Added the CreateFreshApiToken middleware to your web middleware group
Edited bootstrap.js file like the following :
window.axios.defaults.headers.common = {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
'X-Requested-With': 'XMLHttpRequest'
};
Axios Code :
axios.post('/api/getmydata', {
params: {
type: 'raw'
}
})
.then((response) => {
console.log(response);
}).catch((error) => {
console.log(error);
});
Changed route (api.php) :
Route::group(['middleware' => 'api'], function(){
Route::post('getmydata', 'ApiController#test');
});
Added function inside ApiController :
public function test() {
$user = Auth::user();
return $user;
}
The problem here is axios somehow return error: Unauthenticated
Is there anything wrong with my code?
Or is there any other way of achieving this? Thank you
Send the access token in the header of your API request:
Application Type :application/json
Authentication : Bearer [Access-Token]

ajax from framework7 to laravel gives me unauthorized error

I've been trying to send ajax request to my laravel backend from my framework7 frontend using ajax.
$.ajax({
url: 'localhost:8000/server_file/grabtracks',
data: {task: "tracks"},
method: 'get',
async: false,
}).done(function(data) {
grabbedTracks = data;
});
Here is the code on my Laravel 5.4 routes
Route::get('/grabtracks', 'HomeController#grab_track');
And here is from my controller
public function grab_track()
{
$tracks = Track::all('id','title','location','price','track_file','track_img');
return response()->json($tracks);
}
I've disabled the CSRF tokens for the meantime, but i keep getting
Unauthorized error from my request
I'm at a loss, i've tried searching but only angularJS and laravel comes up.
It's probably your Controller has Auth middleware in your constructor remove the middleware and everything should work fine:
So you can remove this instructor or modify it to web auth:
public function __construct()
{
$this->middleware('auth');
}

Categories