CSRF token mismatch From separate vue project to laravel controller - laravel

I have two projects running
One is front end
Other is backend
Frontend project is made in vue js and backend is made in laravel
I am trying to do a post request via axios but i get csrf token mismatch
I cant use the meta tag solution as they both are different projects
**Route i want to hit**
Route::group(['middleware' => 'auth'], function () {
Route::post('tasks', 'TaskController#store')->name('tasks.store');
});
**my axios call in my vue js project**
addTask:function()
{
this.displayError = false;
if($('.inputs').length > 0)
{
const config ={
onUploadProgress:function(progressEvent)
{
var percentCompleted = Math.round((progressEvent.loaded * 100)/progressEvent.total);
console.log(percentCompleted)
}
}
var form = new FormData();
form.append("title",this.title);
form.append("description",this.txtdesc);
form.append("status_id",this.status_id);
form.append("user_id",this.user_id);
axios.post("http://127.0.0.1:8020/tasks",form,config).then((res)=>{
console.log(res)
})
}else
{
this.displayError = true;
}
}
When i fire this function to send data to controller it gives csrf token mismatch error
If it was a laravel project i could've ha tried
adding {{csrf_field()}}
adding #csrf
adding csrf in meta
but how to do it in vue js
PS I have tried removing auth middleware but it returned the same error and
it will work if i place the route inside the cerifycsrftoken file in backend project
but i want to do it with csrf token

I placed my routes from web.php to api.php and added the prefix api which solved my csrf token mismatch problem
also if i place route url in verifyCsrfToken.php file it solves the issue without moving routes to api.php
I took route
Route::post('tasks', 'TaskController#store')->name('tasks.store');
from the web .php file and then i placed it in api.php file
Route::post('tasks', 'TaskController#store')->name('tasks.store');
also i didnt used auth middleware on them

Related

I used Sanctum for submitting forms with Axios but now I cannot use default Laravel Forms using #CSRF, it redirects me to page 419

Recently, I decided to use Laravel Sanctum to submit forms using Vue JS axios. I use Sanctum CSRF-Cookie to validate CSRF before every form submission.Unfortunately, after making this change and after setting up Laravel Sanctum now, all other forms my website such as sign out button (which is inside a form) doesn't work properly.For example, if I add one new person to database using axios to submit that form, after submission if I want to log out it redirects me to 419 page which says Page expired. In some sections of website, I used Vue JS components and Axios to submit forms without refreshing that page. I also don't use Sanctum SPA for authentication I just want to use it for CSRF validation for every form submission!There are some changes that I made and you may need to know but before that if there is any information that is missing in my question here, please let me know so I can update this thread as soon as possible. Also I found a similar question here but the guy who answered that question, hasn't used Vue JS as frontend and whatever he mentioned looked correct on my end and still, I cannot logout after submitting form using Vue JS component and Axios.If anybody here has any solution please answers below. Thank you.
I changed route middleware from API to WEB in RouteServiceProvider.php file like this:
public function boot() {
$this->configureRateLimiting();
$this->routes(function () {
Route::prefix('api')
->middleware('web')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
});
}
I changed support_credentials to true in config\cors.php:
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'supports_credentials' => true,
In config\sanctum.php file this is stateful value:
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:443,127.0.0.1:8000,::1',
env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),
In .env file I don't actually know what should I set for subdomain because there is no subdomain. I just used 127.0.0.1 for SESSION_DOMAIN
SESSION_DRIVER=cookie
SESSION_LIFETIME=120
SESSION_DOMAIN=127.0.0.1
SANCTUM_STATEFUL_DOMAINS=127.0.0.1
SESSION_SECURE_COOKIE=true
Now in VUE JS component, I use this method to validate Sanctum CSRF before adding new contact:
async addNewContact ({commit})
{
await axios.get('/sanctum/csrf-cookie').then(() => {
axios.post(/api/new/contact/add, '', '')
.then(response => {
comit('newContactAlert', response.data.newContact)
})
.catch(err => {
console.log(err)
})
})
},

How could be Laravel Socialite be integrated with a SPA?

I know we have the stateless() and and getTargetUrl() methods, than i am trying this at my controller:
public function socialRedirect($provider){
return Socialite::with($provider)->stateless()->redirect()->getTargetUrl();
}
The problem is that in my SPA front end, i can't make a sucessfull request to the provided url as like in the code below:
async facebookLogin() {
try {
const url = await this.$axios.$get('/auth/social/facebook')
this.$axios.$get(url)
} catch (error){
console.log(error)
}
},
I get CORS related stuff errors:
OPTIONShttps://www.facebook.com/v3.3/dialog/oauth?client_id=240805606930310&redirect_uri=http://localhost:8000/api/auth/social/facebook/callback&scope=email&response_type=code
CORS Missing Allow Origin
What am i doing wrong? I am specially confused since i can access the URL by copying it and pasting in another browser tab, but i can't sucessfully make the AJAX request to it.

Axios Get request return html not data SPA

need some help. I'm trying to fetch data from my db using axios. My backend is Laravel. I have a 200 status http request but it returns the whole html not the data I'm expecting.
Here is my code for route
Route::get('/home', 'PostController#ajaxCall');
Route::post('/home', 'PostController#store');
Route::get('/{any?}', function () {
return view('welcome');
});
Here is my code for Home.vue for Axios request
export default {
components: {addForm},
data () {
return{
posts:[]
}
},
created() {
axios.get('/home').then(response => this.posts = response.data);
}
}
For my controller
public function ajaxCall(){
return response(Post::all());
}
It looks like you get to the ajaxCall() method by using the route '/home', but with axios, you are hitting "/" which returns a view called Welcome. Maybe you need to change the path you use in axios to '/home'?
It might be late but maybe someone else is looking for the solution
I was also facing this in SPA using laravel and VUE.
Route::get('/{any}', 'SinglePageController#index')->where('any', '.*');
SPA has this route, so whenever you write any other get route your app will redirect you to the home page, to avoid this either move this route at the end of your web.php
or write your other routes in api.php file.
In my case i solved it by changing the GET method to POST method.
Try that. It might help

laravel_token is valid for first request but not subsequent requests

I have installed Laravel Passport and configured it according to the documentation. When calling axios.get from my VueJS file, the first call works as expected. the laravel_session Request Cookie is injected into the request, and the authentication passes, returning the resource.
My problem arises when I try to call the axios.get method again. My use case here is a search function. I'm making a call to /api/banking/accounts/search/{search-term} whenever the user types into a text field, using the code below:
remoteMethod(query) {
if (query !== '') {
this.loading = true;
axios.get(
`/api/banking/accounts/search/${escape(query)}`
).then(res => {
this.destinationAccountDirectory = res.data;
this.loading = false;
});
} else {
this.destinationAccountDirectory = [];
}
},
This code works fine without any auth:api middleware on the route, and for the first time with auth:api middleware. As can be seen from the screenshots below, the laravel_token value changes and is rejected on subsequent calls to the API.
**I've tried to removed the \Laravel\Passport\Http\Middleware\CreateFreshApiToken that was added to the web middleware group during passport installation, which seemed to have temporarily solved the issue, until I receive a 419 on a request shortly after. What could be causing the new laravel_tokens to be rejected? **
I solved this by removing the web middleware from my API route. Why it was there in the first place, I have no idea.
I changed my api.php from
Route::group([
'middleware' => [
'web',
'auth:api']], function() {
Route::post('/banking/transactions', 'TransactionController#store');
Route::get('/banking/accounts', 'BankAccountDirectoryController#index');
Route::get('/accounts/{account}', 'BankAccountDirectoryController#show');
Route::get('/banking/accounts/search/{term?}', 'BankAccountDirectoryController#search');
});
to
Route::group([
'middleware' => [
'auth:api']], function() {
Route::post('/banking/transactions', 'TransactionController#store');
Route::get('/banking/accounts', 'BankAccountDirectoryController#index');
Route::get('/accounts/{account}', 'BankAccountDirectoryController#show');
Route::get('/banking/accounts/search/{term?}', 'BankAccountDirectoryController#search');
});
Should the API routes be under the web group to benefit from the middleware, or is it purely for UI? Am I safe to do this?

VueJS: how to get route url?

I am working in laravel with Vue, and I can't get route url.
For example there is route localhost:8000/chat/3 and I need to get 3 in route
I tried in app.js to write in
data: {
userId: this.$route.params
}
and then in
created() {
console.log(this.userId);
}
So i can send ajax request to that route. But it returns TypeError: this.$route is undefined. I tried also with other things than params but it allways show this error

Resources