I m getting Unauthenticated. on laravel sanctum api - php

so I created the login it worked well but when I want to fetch user posts it returns Unauthenticated even tho I sent the token and used the xsrf cookies but still the same problem
axios call
axios.defaults.withCredentials = true;
axios.get('/sanctum/csrf-cookie').then(response => {
axios.get('/api/posts/20',{headers:{Authorization: `Bearer ${localStorage.getItem('userToken')}`}}).then(res=>{
console.log(res);
})
api route
Route::post('login',"UserController#index");
Route::get('posts/{id}', 'PostController#index')->middleware('auth:sanctum');
please help me guys keep in mind I tried everything out there but nothing works

I had problem in domain as TEFO said I launched the backend on virtual host + adding configuration to cors.php solved the problem

Related

Laravel API (Sanctum) + nuxt auth - weird cookies behaviour, I don't get it

Perhaps what I am looking at is normal and ok but I am not sure. I would love some explanation.
So I have SPA in NuxtJS (separate app) and API in Laravel 8. I have managed to authenticate my SPA with Sanctum and my Laravel API is giving me back data from restricted endpoints. I am using Nuxt Auth to facilitate the whole process.
THE PROBLEM
I've noticed strange behavior. Any request (not just login) pops the xsrf cookie in the browser. I don't understand that, I don't know why. I don't think it's right. Response headers are setting these cookies one is session and one is for xsrf but I have more. I do keep the encrypted vuex store in local storage but these are cookies so I have no clue what that might be.
The second part of the problem, the cookies are changing each time I request something from API. So does that mean if the cookie session has changed the session has been refreshed now and it has new TTL? Should they not remain the same?
Third part I am getting some weird encrypted cookies which I cannot account for. Is this sanctum?
These are my other settings:
/etc/hosts
127.0.0.1 publisher.com #frontend
127.0.0.1 api.publisher.com #backend
nuxt.config.js
auth: {
strategies: {
laravelSanctum: {
provider: 'laravel/sanctum',
url: 'http://api.publisher.com:8080',
endpoints: {
login: { url: '/login', method: 'post' },
// logout: { url: '/api/v1/logout', method: 'post' },
user: { url: '/api/v1/user', method: 'get' }
}
},
},
},
sanctumm.php
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1,local:3000,publisher.com:3000',
Sanctum::currentApplicationUrlWithPort()
))),
session.php
'domain' => env('SESSION_DOMAIN', '.publisher.com'),
My biggest concerns are that I do not understand why the cookies are refreshed with each request to my API.
Apart from that, I can log in, I am just struggling to understand what is happening.
Can someone shed some light on what is up?
P.S UPDATE I think the extra cookies might be due to session driver set to cookie it's gone since I changed it to file but the rest of the problems remains.

Cors nginx and setCookie with JWT token

I have project divided into frontend and backend. Backend is available on mydomain.com/api and I need to develop frontend project which cooperate with backend on mydomaion.com/api.
First problem was CORS - It`s ok. I allowed CORS.
But now I am facing to second problem. When I sign-in in frontend, backend set BEARER token.
setcookie('BEARER', $token, 0, '/', '', false, true);
I expect when I send next request to API, cookie BEARER header automatically attached. Unfortunatelly no headers attached and therefore I get response 401 Unauthorized because I am not logged in.
I think that problem is domain. Frontend running on my local PC mydomain.test and API running on mydomain.com.
I think I need something like this:
setcookie('BEARER', $token, 0, '/', '*', false, true);
But this is not working too.
Solve somebody same problem?
I dont know what are you using in your backend, but i think your problem is on your CORS config. Normally you need to allow the origin you are using, headers and credentials. In ASP.NET CORE it would look something like this:
builder.WithOrigins("http://localhost:8080")
.AllowAnyHeader()
.AllowAnyMethod()
.SetIsOriginAllowed(origin => true)
.AllowCredentials();
And since you are using jwt token you need to add it:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
//your jwt options config
})
)

Laravel (v5.7) Passport (v7.0) is redirecting me to the login screen when trying to open auth api route

I have read this question: Laravel Passport Route redirects to login page and it is not working for me. I am sending the request using Accept: application/json and Authorization: Bearer [access-token], but i am redirected to the login screen of my app. This is the route i am trying https://passportdemo.test/api/products and this is my api route file
Route::post('register', 'API\RegisterController#register');
Route::middleware('auth:api')->group( function () {
Route::resource('products', 'API\ProductController');
});
I am able to register a new user and login a user without any problems, but when trying to use the products route i am redirected to the login screen.
I also tried to see what will dd($request->expectsJson()); return from namespace Illuminate\Foundation\Exceptions#unauthenticated and it is returning false which is strange right? it should return true i think. I am using nginx server so the trick with .htaccess i think its not appellable for me and also i tried to add protected static $serialize = true; inside the class Illuminate\Cookie\Middleware\EncryptCookies, but this dosent work for me too.
Someone can help me?
A noob mistake. It turn out that sending the request using Postman or Insomnia need to be done with the Auth tab and not from the data/form tap (which i was using).
For Postman just go to Authorization and choose Bearer token and paste the token and fill any data in the Params tab if you need to
For Insomnia just click on Bearer token and paste your token and then in Multipart if you have some form data paste/write it there
and voila!
after 3 days of researching what is the problem!

Laravel and Passport, random 401 errors

I'm writing a single page web application.
I'm using Vue.js in the frontend and Laravel in the backend.
I included Passport token authentication and I'm getting the auth token sending
var login_data = {
client_id : 2,
client_secret : "SECRET_KEY",
grant_type : "password",
username : "mail",
password : "pass"
}
To this Passport endpoint http://IPADDRESS/oauth/token. Then I authenticate my AJAX requests including this header
{ 'Authorization': 'Bearer ' + ACC_TOKEN }
Most of the time everything works fine but sometimes I get 401 unauthorized. Usually, if I simply do it again the request goes through.
I removed the VerifyCsrfToken middleware from Kernel.php and also added the API route to the exceptions so I don't think that's the problem.
The frequency the error appears seems to change from network to network, meaning when connected to certain networks it almost never happens while sometimes it's constant.
I honestly have no idea why this happens.
My problem was in PROJECTDIR/vendor/lcobucci/jwt/src/Signer/Rsa.php.
Here an openssl function (openssl_get_publickey) sometimes returns something wrong despite the certificate being valid.
I did not manage to find a real solution.
My hack for now is simply changing the code to always return 1.
This does not change the way the token auth works but removes the Rsa check and the 401 errors caused by such malfunction.

Random 400 "token_invalid" errors with Laravel / jwt-auth and Angular / Satellizer app

I have an Angular app that consumes an API I built in Laravel, and I use jwt-auth for token management and satellizer on the front end to send the token with each request.
My live environment (for both the front end and the API - which will be moved to a different server once the app is finished) at the moment consists of 2 AWS EC2 instances running nginx with a load balancer. Both servers have the same jwt secret key.
However, and at the moment I can't work out any pattern to it, I randomly get 400 "token_invalid" errors returned from my api. It is not one particular api route, nor is it on every load of the app. When I get a 400 error, from my /clients endpoint for example, other requests will have returned 200's. Next time, all will return 200's. The time after that I may get 200 returned for /clients but a 400 error for /users.
Could this be an issue with me using a load balancer? The jwt secret key, as I said, is the same on both servers - as all the code is in GIT.
I am not using the jwt.refresh middleware.
One other thing to mention is that I don't ever get 400 errors returned when running the app locally via Homestead, ony in production.
EDIT - it seems as though logging out (which clears both my user object (basic details only) and the token from local storage, clearing my cache, then logging back in most often causes the error - is this helpful?
Below is an example of one of my api calls.
App.js
.service('ClientsService', function($http, $q, __env) {
this.index = function () {
var deferred = $q.defer();
$http.get(__env.apiUrl + '/clients')
.then(function successCallback(response) {
console.log(response.data);
deferred.resolve(response.data);
},
function errorCallback(response) {
console.log(response);
});
return deferred.promise;
}
})
ClientsController.js
.controller('ClientsController', function(ClientsService, $stateParams, $mdDialog, $mdToast) {
var vm = this;
ClientsService.index().then(function(clients) {
console.log('ClientsCtrl init');
vm.clients = clients.data;
});
// other controller code
})
I'm really struggling to debug this, so any help would be much appreciated. If any more info is needed, please let me know.
https://github.com/tymondesigns/jwt-auth/issues/1583
solution: use the same jwt secret in .env file

Categories