I am using Laravel Sanctum with Vuejs SPA. Both reside on same top level domain
Laravel backend : app.demo.localhost
Vue SPA : app-spa.demo.localhost
Login and logout (endpoints) are working correctly when called from VueJS SPA using axios and XSRF-TOKEN is succesfully set, but when I call other api end points it gives me 401 unauthorized.
In axios this is being set
axios.defaults.withCredentials = true;
I have the below configurations
In Laravel .env
SESSION_DRIVER=cookie
SESSION_DOMAIN=.demo.localhost
SANCTUM_STATEFUL_DOMAINS=app-spa.demo.localhost
In Routes/Api.php
Route::middleware('auth:sanctum')->get('api/user', function (Request $request) {
return $request->user();
});
In cors.php
'paths' => ['api/*', 'sanctum/csrf-cookie', 'login', 'logout'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
Could someone help me out please?
If you are using php artisan serve add the port number to SANCTUM_STATEFUL_DOMAINS. So if your port number is 8000:
SESSION_DRIVER=cookie
SESSION_DOMAIN=.demo.localhost
SANCTUM_STATEFUL_DOMAINS=app-spa.demo.localhost:8000
Your SANCTUM_STATEFUL_DOMAINS must match the url in your browser. The port number should not be on the SESSION_DOMAIN.
Following are the 8 steps that I follow while setting up Laravel sanctum check if you missed anything
Step1 composer require laravel/sanctum
Step2 php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider
Step3 php artisan migrate (you can ignore this if you're using spa)
Step4 uncomment this line from app/http/kernel.php \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
Step5 In config/cors.php update 'supports_credentials' => true,
Step6 In .env file update SESSION_DRIVER=cookie & add new line of SESSION_DOMAIN=localhost (even if your using any port like 8080 just mention localhost in session_domain)
Step7 In config/sanctum.php add your client domain along with port(if local) in stateful as follows, in my case for vue CLI it's usually localhost:8080 & for nuxt its localhost:3000 , code is as follows
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:8000,localhost:8080,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),
Mostly if your stateful (step7) is not setup properly you will get 401 unauthorized or it will try to redirect you to the home page along with cors policy error
Step8 Do not forget to await until sanctum/csrf-cookie promise is resolved
async login() {
await axios.get("http://localhost:8000/sanctum/csrf-cookie");
await axios.post("http://localhost:8000/login", {
email: "kunal#gmail.com",
password: "password",
});
let response = await axios.get("http://localhost:8000/api/user");
console.log(response.data);
},
For anyone dealing with localhost:
SESSION_DRIVER=cookie
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:8080(port number you use)
I just encountered the same problem. I configured all the options according to the official documentation, but I couldn't get the authorization.
Then I use routes/web.php instead of routes/api.php, so I can use sanctum middleware very well.
Now the problem seems obvious,Axios withCredentials maybe need to place in the correct way.
const http = axios.create({
baseURL: API_URL,
withCredentials: true
})
maybe not work. So I add {withCredentials: true} like
http.get('/api/whoami', {withCredentials: true})
.then(res => {
console.log(res.data)
})
Then it works.
But the very strange thing is that it is normal now, no matter whether I clear the browser cache, cookies or Laravel's various caches, there is no previous situation
For me i just had to place the host with port number:
SANCTUM_STATEFUL_DOMAINS=127.0.0.1:5173
and it started working.
Maybe this helps someone.
My problema was.... (no read with attention)
If your SPA needs to authenticate with private / presence broadcast channels, you should place the Broadcast::routes method call within your routes/api.php file:
Hi i found a solution.
My SPA is Vue v3 working on 3000 port.
Also my backend is working on 80 port. (laravel 8.1)
Make Stateful Domains in config/sanctum.php like that
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost:3000',
env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),
Adding only one and correct domain on their, worked for me magically. I wrote before there whole possible variant of ports, it made me crazy and cost a couple days and nights.
My issue was I setup the domain in the wrong place.
I thought was an array of domains, in config/sanctum.php, but not, needs to be placed within the string:
OK:
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1,myownlocaldomain.test,myownlocaldomain.test:8080', <-------- OK
env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : ''
))),
BAD:
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
env('APP_URL') ? ','.parse_url(env('APP_URL'), PHP_URL_HOST) : '',
'myownlocaldomain.test', <----- BAD
'myownlocaldomain.test:8080', <---- BAD
))),
I hope I save days of work to someone else...
Related
I have built a real estate site that makes a an api request to "https://completecriminalchecks.com" In development mode I was getting the dreaded blocked by Cors error. Through some research I found that I needed to use a proxy to solve the issue, which it did in development mode on my local host. But now I have deployed the site to netlify, I am getting a 404 error when making the request. when I look at the request from the network devtools its says
Request URL: https://master--jessehaven.netlify.app/api/json/?apikey=6s4xxxxx13xlvtphrnuge19&search=radius&miles=2¢er=98144
I dont think this is right. How do i make netlify make the proper request to the api that was having cors issues in development?
Have you tried netify documentation about it?
Proxy to another service Just like you can rewrite paths like /* to
/index.html, you can also set up rules to let parts of your site proxy
to external services. Let's say you need to communicate from a
single-page app with an API on https://api.example.com that doesn't
support CORS requests. The following rule will let you use /api/ from
your JavaScript client:
/api/* https://api.example.com/:splat 200
Now all requests to /api/... will be proxied through to
https://api.example.com straight from our CDN servers without an
additional connection from the browser. If the API supports standard
HTTP caching mechanisms like ETags or Last-Modified headers, the
responses will even get cached by our CDN nodes.
You do not need to use a proxy, you enable CORRS in your server. Are you using a onde server?
If you use express something like this:
npm install --save cors
And then use it as middleware:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
Also in your netlify.toml file this will do the trick:
# The following redirect is intended for use with most SPAs that handle
# routing internally.
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
[[headers]]
# Define which paths this specific [[headers]] block will cover.
for = "/*"
[headers.values]
Access-Control-Allow-Origin = "*"
I also faced the same issue and solved by creating a netlify.toml file in root directory.
Here is a sample code for redirect which worked for me.
Place this inside the netlify.toml file.
Documentation guide for proxy :
[[redirects]]
from = "/api/users/tickets/"
to = "https://some-external-site.com/api/users/tickets/"
status = 200
force = true
headers = {Access-Control-Allow-Origin = "*"}
[[redirects]]
from = "/api/users/cars/*"
to = "https://some-external-site.com/api/users/cars/:splat"
status = 200
force = true
headers = {Access-Control-Allow-Origin = "*"}
I also faced the same issue , so I removed the "proxy" from the "package.json" file and created a variable to store the IP addess or URL for backend , then used it with the URL parameter for calling API. The CORS issue is solved in backend by allowing "All origins".
File to store base URL:
constant.js :
export const baseUrl = "https://backEndUrl";
File to call API:
getDataApi.js:
import { baseUrl } from "./constant";
export const getProfileData = () => (dispatch) => {
axios
.get(`${baseUrl }/api/profile`)
.then((res) =>
dispatch({
type: GET_PROFILE,
payload: res.data,
})
)
.catch((err) =>
dispatch({
type: GET_PROFILE,
payload: null,
})
);
};
I am developing a new frontend using Vue to access my existing Laravel 7 app, which uses Sanctum for authentication.
The frontend sits on app.example.com, with the backend being moved to api.example.com. The CORS middleware and Sanctum are properly configured to allow app.example.com, and so far so good.
The GET to /sanctum/csrf-cookie looks fine, however, it doesn't seem to be actually setting the cookies, causing the subsequent request to the API to return a 419.
const config = { withCredentials: true };
const api = process.env.NODE_ENV === 'production' ? 'https://api.example.com' : 'http://localhost:9000';
axios.get(api + '/sanctum/csrf-cookie', config)
.then(() => axios.post(api + '/login', data, config))
.then(response => response.json())
.then(response => { console.log('json', response); });
Console log:
Response headers from /sanctum/csrf-cookie:
No cookies are listed in devtools:
UPDATE 1: Didn't notice this earlier; the warning icons next to each Set-Cookie in the response headers display "This set-cookie's Domain attribute was invalid with respect to the current host url."
Short answer: Ports should not be specified in cookie domain attributes.
Long answer: Laravel Sanctum uses the VerifyCsrfToken middleware to both send and verify the CSRF token, which uses session config values when adding the cookie to the response:
protected function addCookieToResponse($request, $response)
{
$config = config('session');
if ($response instanceof Responsable) {
$response = $response->toResponse($request);
}
$response->headers->setCookie(
new Cookie(
'XSRF-TOKEN', $request->session()->token(), $this->availableAt(60 * $config['lifetime']),
$config['path'], $config['domain'], $config['secure'], false, false, $config['same_site'] ?? null
)
);
return $response;
}
In config/session.php:
'domain' => env('SESSION_DOMAIN', null),
In .env:
SESSION_DOMAIN=localhost:8080
Cookies on the same host ARE NOT distinguishable by ports. Because I had specified the port in the cookie domain, the browser had flagged the cookie as having an invalid domain. Removing the port did the trick.
For me to solve the problem I changed my vue cli host which was 127.0.0.1:8080 to localhost:8080 in browser,and within axios the base url is now http://localhost:7000 which is for laravel api.
after that I then set SESSION_DOMAIN=localhost in .env laravel
I've got a problem with axios and heroku. Maybe some short introduction before.
The problem with CORS has been solved and i my apps run on localhost and on herokuapp.com. The only thing which is currently not working is my app running with heroku local web.
For the backend call I using axios which is referencing my backend api from an environment file:
axios
.get(process.env.VUE_APP_ROOT_API + "/resource")
.then(response => (this.receipt = response.data));
}
.env.local:
VUE_APP_ROOT_API=http//:0.0.0.0:5002 #5002 is my backend
This produces the following wrong axios call:
GET http://0.0.0.0:5001/http//:0.0.0.0:5002/resource #5001 is my frontend
I cannot explain how this GET is generated. Printing out the request url with
axios.interceptors.request.use(request => {
console.log("Starting Request", request);
return request;
});
is showing the correct URL http//:0.0.0.0:5002/resource...
Any solutions?
This is embarassing, I had a type:
http:// instead of http//:
See: Quasar Axios request wrong URL (Double URL)
I have created an API endpoint using the Django python framework that I host externally. I can access my endpoint from a browser (mydomain.com/endpoint/) and verify that there is no error. The same is true when I run my test django server on locally on my development machine (localhost:8000/endpoint/). When I use my localhost as an endpoint, my json data comes through without issue. When I use my production domain, axios gets caught up with a network error, and there is not much context that it gives... from the debug console I get this:
Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)
at XMLHttpRequest.dispatchEvent (event-target.js:172)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:554)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:387)
at XMLHttpRequest.js:493
at RCTDeviceEventEmitter.emit (EventEmitter.js:181)
at MessageQueue.__callFunction (MessageQueue.js:353)
at MessageQueue.js:118
at MessageQueue.__guardSafe (MessageQueue.js:316)
This is my axios call in my react native component:
componentDidMount() {
axios.get('mydomain.com/get/').then(response => { // localhost:8000/get works
this.setState({foo:response.data});
}).catch(error => {
console.log(error);
});
}
If you are trying to call localhost on android simulator created with AVD, replacing localhost with 10.0.2.2 solved the issue for me.
It seems that unencrypted network requests are blocked by default in iOS, i.e. https will work, http will not.
From the docs:
By default, iOS will block any request that's not encrypted using SSL.
If you need to fetch from a cleartext URL (one that begins with http)
you will first need to add an App Transport Security exception.
change from localhost to your ip(192.168.43.49)
add http://
http://192.168.43.49:3000/user/
If you do not find your answer in other posts
In my case, I use Rails for the backend and I tried to make requests to http://localhost:3000 using Axios but every time I got Network Error as a response. Then I found out that I need to make a request to http://10.0.2.2:3000 in the case of the android simulator. For the iOS simulator, it works fine with http://localhost:3000.
Conclusion
use
http://10.0.2.2:3000
instead of
http://localhost:3000
update
might worth trying
adb reverse tcp:3000 tcp:3000
For me, the issue was because my Remote URL was incorrect.
If you have the URL is a .env file, please crosscheck the naming and also ensure
that it's prefixed with REACT_APP_ as react might not be able to find it if named otherwise.
In the .env file Something like REACT_APP_BACKEND_API_URL=https://appurl/api
can be accessed as const { REACT_APP_BACKEND_API_URL } = process.env;
Try
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json"
If you are using android then open your command prompt and type ipconfig. Then get your ip address and replce it with localhost.
In my case, first I used http://localhost:8080/api/admin/1. Then I changed it to http://192.168.1.10:8080/api/admin/1. It worked for me.
Make sure to change localhost to your_ip_address which you can find by typing ipconfig in Command Prompt
Trying adding to your AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I was facing the same issue.
i looked deeper and my
endpoint url was not correct.
By giving axios right exact url, my api worked like charm.
Hope it may help anyone
Above mentioned answers only works if you are using localhost but if your code is hosted on a server and Axios throwing Network Error then you can solve this by adding one line.
const config = {
method: 'post',
url: `${BASE_URL}/login`,
headers: {
'Content-Type': 'multipart/form-data'. <----- Add this line in your axios header
},
data : formData
};
axios(config).then((res)=> console.log(res))
I'm using apisauce dependancy & Adding header work for me with React Native Android.
Attach header with request like below:
import { create } from 'apisauce';
const api = create({
baseURL: {baseUrl},
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
});
export async function empLogin(data) {
try {
const response = api.post('Login', data);
return await response;
} catch (error) {
console.log(error);
return [];
}
}
before:
axios.get("http://localhost:3456/apt")
.then(
response => {
alert(JSON.stringify(response));
....
}
)
.catch(function(error) {
alert(error.message);
console.warn(error.response._response);
});
I get Error "Network error" Failed to connect to the localhost after that, I make some steps to resolved the error.
Network Error related to axios resloved by the disabling the system firewall and access from the system IP Address like
axios.get("http://192.168.12.10:3456/apt")
.then(
response => {
alert(JSON.stringify(response));
....
}
)
.catch(function(error) {
alert(error.message);
console.warn(error.response._response);
});
For me adding "Accept" in headers resolved the problem:
Accept: 'application/json'
I use the REST api in my nodejs application.
All is working good with sandbox but when i update with live credentials i get:
{ [Error: Response Status : 401]
response:
{ error: 'invalid_client',
error_description: 'The client credentials are invalid',
httpStatusCode: 401 },
httpStatusCode: 401 }
I updated my account to buisness but still not working, i use the live endpoint and Live credentials.
What should i do in order to make this work?
I had the same issue using PayPalSDK/rest-sdk-nodejs and solved passing with the configuration parameters (host, client_id, client_secret, ...) also the parameter 'mode' set to 'live'. Otherwise the default mode used by the library is 'sandbox' and hence the impossibility to use the live credentials.
As matteo said, if you switch from dev to live environment, only updateing the client id and secret isn't enough. You need to set the ApiContext-Mode to "live".
PayPals PHP REST-API-SDK comes with some great samples. Take a look at the bootstrap.php in /vendor/paypal/rest-api-sdk-php/sample/ in line 84. There are some configurations happening, after getting the api context.
<?php
$apiContext = new ApiContext(
new OAuthTokenCredential(
$clientId,
$clientSecret
)
);
// Comment this line out and uncomment the PP_CONFIG_PATH
// 'define' block if you want to use static file
// based configuration
$apiContext->setConfig(
array(
'mode' => 'sandbox',
'log.LogEnabled' => true,
'log.FileName' => '../PayPal.log',
'log.LogLevel' => 'DEBUG', // PLEASE USE `INFO` LEVEL FOR LOGGING IN LIVE ENVIRONMENTS
'cache.enabled' => true,
// 'http.CURLOPT_CONNECTTIMEOUT' => 30
// 'http.headers.PayPal-Partner-Attribution-Id' => '123123123'
//'log.AdapterFactory' => '\PayPal\Log\DefaultLogFactory' // Factory class implementing \PayPal\Log\PayPalLogFactory
)
);