Laravel Sanctum and Nuxt Js returns Unauthenticated - laravel

I recently just deployed my Nuxt Js application and i am having trouble with authentication.
I have set the stateful and session domain in my .env as seen below
SESSION_DRIVER=file
SESSION_LIFETIME=120
SESSION_DOMAIN=api.example.com
SANCTUM_STATEFUL_DOMAINS=example.com
i also have this in my cors.php
'paths' => ['api/*', 'sanctum/csrf-cookie',],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
In my nuxt.config.js i have the following
auth: {
strategies: {
cookie: {
endpoints: {
csrf: {
url: '/sanctum/csrf-cookie'
},
login: {
url: '/api/login',
},
register: {
url: '/api/register',
},
logout: {
url: '/api/logout',
},
user: {
url: '/api/user',
}
},
user: {
property: 'data'
},
}
},
redirect: {
login: '/auth/login',
logout: '/auth/login',
home: '/dashboard',
},
plugins: [
'~/plugins/axios'
]
},
// Axios module configuration: https://go.nuxtjs.dev/config-axios
axios: {
// Workaround to avoid enforcing hard-coded localhost:3000: https://github.com/nuxt-community/axios-module/issues/308
baseURL: 'http://api.example.com',
credentials: true
},
I do not know what i am doing wrong could someone please help

In your .env file, Change your SESSION_DOMAIN from api.example.com to .example.com
And change your axios baseUrl from http://localhost to your api endpoint

Related

Cookies doesnot sets up

I use Axios to get cookies from http://localhost/sanctum/csrf-cookie
My app doing requests from localhost:3000 which is configured by Nuxt.
My backend configured by Laravel sanctum at localhost:80
After the GET request, I have the following cookies set in my headers:
Set-Cookie: XSRF-TOKEN=eyJpdiI6InkvSWhzeUtnYzNpck5NSGozS09IVVE9PSIsInZhbHVlIjoiRmR1RVdmYW8zaXYxeWZUNFNjZmkyNjRVKzZQMGk4MExsK3JmOVRPN0s3M3FGK3V1eFpLaTNRYnhhbExvTW5BbmFqVGN2SWRBdUVZcUJkWEJabnJQakEwN1pYNUk1NDBtRFhRSllkTk45ZHZuRWFUZmc5NHViK21JUTVkWFZhZDEiLCJtYWMiOiI5NjBkMWY5YWFmZTgwODE4ZjIzMzdjMjkxMzk3Zjk3YWU0YmI1ZGUzNzAyMmQzZWVhMWQzM2NmYWEwYjdhYTcxIiwidGFnIjoiIn0%3D; expires=Sat, 01-Oct-2022 16:14:59 GMT; Max-Age=7200; path=/; domain=localhost:3000; samesite=lax
Set-Cookie: laravel_session=eyJpdiI6InhNRVBDT1ovanR4QVdzakNHd1YxekE9PSIsInZhbHVlIjoiajNGUGdxa1NJemxiSGIrc1pwZ3VrNFJBbmd6QnFMZkZmZHdWK3ZPSzVWdGZydHBQTGNPRmpocVN3d1lTcTE1d0RLdWFNNEJPbjhLKzVPaEpvSTZzUm5RQWZaQ0ZHVlAxeElBVkErN2hOUnFRTm8wVGJrUllaNXNmTm50N1plTFoiLCJtYWMiOiIxNGZmNTYzYmFkMmY2NjAzNGQwMTIwMzhlYWNjYTI4MjQzNTM0N2Y4Mzk3MzkwYTdmYzU4MDFiMGVkZGU3NjVjIiwidGFnIjoiIn0%3D; expires=Sat, 01-Oct-2022 16:14:59 GMT; Max-Age=7200; path=/; domain=localhost:3000; httponly; samesite=lax]
But there are no cookies in the application tab:
What is wrong?
In your .env file add
SESSION_DOMAIN=.localhost
Check CORS
'paths' => ['*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'], // All origins
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
For your nuxt project, use #nuxtjs/auth-next package.
The real problem was wrong credentials support in axios module.
This should be the credentials: true, rather than withCredentials: true
axios: {
credentials: true,
baseURL: "http://localhost", // Used as fallback if no runtime config is provided
// withCredentials: true,
headers: {
common: {
"Access-Control-Allow-Origin": "*",
'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS',
'Access-Control-Allow-Credentials': true
},
delete: {},
get: {},
head: {},
post: {},
put: {},
patch: {},
},
},

Getting Unathenticated Error NuxtJs Get request

Am trying to do a simple GET request in NuxtJs using Axios. l have configured my nuxt.config.js like this
axios: {
proxy: true,
credentials: true,
baseURL: 'http://localhost:8000/api/'
},
proxy: {
'/api': { target: 'http://localhost:8000', pathRewrite: {'^/api/v1/': ''} }
},
auth: {
strategies: {
laravelSanctum: {
provider: 'laravel/sanctum',
url: 'http://localhost:8000',
token: {
property: 'token',
global: true,
required: true,
type: 'Bearer',
name: 'Authorization'
},
refreshToken: {
property: 'token',
data: 'token',
maxAge: 60 * 60 * 24 * 30
},
user: {
property: 'user',
},
endpoints: {
login: { url: '/api/auth/login', method: 'post' },
user: { url: '/api/user', method: 'get' },
logout: { url: '/api/auth/logout', method: 'get' },
refresh: { url: '/api/refresh', method: 'get' },
},
tokenType: 'Bearer',
tokenRequired: true,
cookie: {
cookie: {
name: 'XSRF-TOKEN',
},
},
}
},
redirect: {
login: '/',
logout: '/',
callback: false,
home: '/'
},
},
router: {
middleware: 'auth'
},
l have tried alot of methods that were posted here before but no avail. Same issues. l also noticed that when l reload the page. Vuex shows user object empty.
Am using Laravel Sactum, any help will be greatly appreciated. Thanks in advance

Laravel 8 from origin 'http://localhost:8000' has been blocked by CORS policy

I have problem in a Axios Laravel crossite, which returns this erorr:
Access to XMLHttpRequest at 'http://localhost/moddle/moodle/login/index.php' from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have done follow like laravel-cors and answer on stackoverflow, none of them worked.
This is my Axios:
let axiosConfig = {
headers: {
"Access-Control-Allow-Origin": "*",
'Content-Type': 'application/json;',
"Content-Type": "application/x-www-form-urlencoded",
}
};
axios.post('http://localhost/moddle/moodle/login/index.php', response.data, {
crossOrigin: null,
}, axiosConfig).then(
response => {
console.log(true);
window.location.href = "http://localhost/moddle/moodle/my/";
}).catch(erorr => {
});
In my cors.php
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
In my middleware
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
//
// \App\Http\Middleware\Cors::class,
];
You can add into TrustHosts.php Middleware without doing anything extra. read the complete solution here: https://stackoverflow.com/a/70361284/2612926
Please do the following to resolve the issue.
php artisan config:cache

In ajax post request my app blocked by CORS policy error

I encountered CORS policy error in my laravel 5.8 / jquery 3.4.1 app when I need send post request to create google calendar event with api like:
public function calendar_add_event(Request $request)
{
session_start();
$startDateTime = $request->start_date;
$endDateTime = $request->end_date;
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$this->client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Calendar($this->client);
$calendarId = 'primary';
$event = new Google_Service_Calendar_Event([
'summary' => $request->title,
'description' => $request->description,
'start' => ['dateTime' => $startDateTime],
'end' => ['dateTime' => $endDateTime],
'reminders' => ['useDefault' => true],
]);
$results = $service->events->insert($calendarId, $event);
if (!$results) {
return response()->json(['status' => 'error', 'message' => 'Something went wrong']);
}
return response()->json(['status' => 'success', 'message' => 'Event Created']);
} else {
return redirect()->route('oauthCallback');
}
}
In js code I send post request :
backendCalendar.prototype.saveCalendarAddEvent = function (user_id) {
var href = this_backend_home_url + "/admin/calendar_add_event";
$.ajax( {
type: "POST",
dataType: "json",
url: href,
data: { "title": $('#new_event_title').val(), "description": $('#new_event_description').val(), "start_date": $('#new_event_start_date').val(), "end_date": $('#new_event_end_date').val(), "_token": this_csrf_token},
success: function( response )
{
popupAlert("New event was added successfully !", 'success')
},
error: function( error )
{
popupErrorMessage(error.responseJSON.message)
}
});
} // backendCalendar.prototype.saveCalendarAddEvent
I installed https://github.com/barryvdh/laravel-cors package and left file config/cors.php without changes :
<?php
return [
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedOriginsPatterns' => [],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'],
'exposedHeaders' => [],
'maxAge' => 0,
];
in routes/web.php I added HandleCors middleware :
Route::group(['middleware' => ['auth', 'isVerified', 'CheckUserStatus'], 'prefix' => 'admin', 'as' => 'admin.'], function () {
...
Route::post('calendar_add_event', 'gCalendarController#calendar_add_event')->middleware(\Barryvdh\Cors\HandleCors::class);
and I hoped that would fix my problems, but I still have this error : https://imgur.com/a/uyTy30Y
How to fix it ?
I found a decision here : Access-Control-Allow-Origin error sending a jQuery Post to Google API's
by additing additive parameters crossDomain and modification of dataType :
$.ajax({
url: 'https://www.googleapis.com/moderator/v1/series?key='+key,
data: myData,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); },
beforeSend: setHeader
});

“Unauthenticated” when consuming own API with passport?

I have installed passport as the documentation instructed and added this line the 'web' middleware:
'web' => [
// Other middleware...
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
and now , Iam trying to get some data using datatable ( datatables.net ) with ajax:
api.php
Route::group(['prefix' => 'v1', 'middleware' => 'auth:api'], function()
{
Route::get('/itemsData', 'DataController#getItemsData')->name('api.getItemsData');
});
in blade:
<script>
$(document).ready(function() {
$('#Table').DataTable({
"order": [],
"processing": true,
"serverSide": true,
"ajax": "{{ route('api.getItemsData') }}",
"columns": [{
"data": "name"
}, {
"data": "created_at"
}],
});
});
</script>
but Iam getting this as a response:
{"message":"Unauthenticated."}
Ok, Passport was looking for 'X-CSRF-TOKEN' which is not in the request header, so It must be added..
so, for this case:
"ajax": {
"url": "{{ route('api.getItemsData') }}",
'beforeSend': function (request) {
request.setRequestHeader("X-CSRF-TOKEN", '{{ csrf_token() }}');
}
},
You need to pass the access_token that you have obtained from Passport in request header as
$.ajaxSetup({
headers: {
'Authorization': 'Bearer ' + 'your access token'
}
});

Resources