hapi.js cors with auth - javascript

Put together the below.
server.route([
{
method: "POST",
path: "/authorize",
config: {
auth: false,
cors: {
origin: ['*']
}
},
handler: (request, reply) => {
...
reply.redirect(redirectUrl)
}
}
])
I want to use with client-side JavaScript browser fetch API. The cors part is necessary to avoid using the no-cors mode for fetch and to get a non-opaque response.
If I use only 'authin the config section or onlycors` they work fine, but together hapi complaints that the configuration is wrong.
Why is that?

inside config object you cannot use key cors. for correct configuration you have to put cors key inside this like this
server.connection({
port: dbConfig.port,
routes: { cors: true } // set cross origin by hapi inbuilt property
// tls: tls
})

Related

CORS redirect issue on a local development environment Laravel and Vue project

I'm having some CORS issues. In my environment I have:
Laravel project running on 127.0.0.1:8000
Vue project running on localhost:8080
This is the configuration of Vue:
const { defineConfig } = require('#vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
proxy: {
'/api': {
target: 'http://127.0.0.1:8000',
changeOrigin: true
},
'/sanctum': {
target: 'http://127.0.0.1:8000',
changeOrigin: true,
}
}
}
})
I'm trying to do the following requests to the Laravel server:
axios.get('sanctum/csrf-cookie').then(() => {
axios.post('api/login', {
email: email,
password: password
}).then(response => {
this.user = response.data.user
this.token = response.data.token
})
})
In the first request, the XSRF token is being set. The second request to 'api/login', however, is receiving a 302 redirection to 127.0.0.1:8000 (the /api/login route is not being considered).
The Javascript console is showing the following error:
Access to XMLHttpRequest at 'http://127.0.0.1:8000/' (redirected from 'http://localhost:8080/api/login') from origin 'http://localhost:8080' 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've tried changing both client and server side configurations but I'm always going back to where I started from.
Some additional details:
if I do the login request directly toward 127.0.0.1:8000/api/login, I receive a CSRF mismatch error from Laravel (so there is not a CORS issue)
this is how the API login route is configured:
Route::post('login', '\App\Http\Controllers\Auth\LoginController#apiLogin');

Error React Proxy error: Could not proxy request

Why do I got this error:
Proxy error: Could not proxy request /api/v1/management/me from localhost:3000 to http://localhost:8080 (ECONNREFUSED).
Got this axios setting:
axios.defaults.baseURL = "http://localhost:3000/";
And set this in package.json:
"proxy": "http://localhost:8080"
tried also:
"proxy": "http://localhost:8080/"
And have following call:
axios({
method: "get",
url: "api/v1/management/me",
data: {},
headers: { crossDomain: true },
})
When I call directly http://localhost:8080/api/v1/management/me I got response from server.
I have following backend, Vapor route setting. Maybe something wrong / specific here?
let protectedAPIRouter = authSessionRouter.grouped("api/v1").grouped(User.guardAuthMiddleware())
let managementAPIRouter = protectedAPIRouter.grouped("management")
I would suggest the following solutions:
Try to change localhost to IP address: "proxy": "http://your_IP_address:8080"
Try this construction also:
"proxy": {
"/api/*": {
"target": "http://localhost:8080",
"secure": false
}
}
You need to set up a proxy to the backend service you want to access.
First install (http-proxy-middleware) package.
Remove the ("proxy": "http://localhost:8080/") or the Url behind the proxy in the package json file.
In the src folder create a file (setupProxy.js) and and the following code.
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:8080',
changeOrigin: true,
})
);
};
I solved this issue change localhost to 127.0.0.1 in the package.json over the client project.

Webpack devserver proxy not working to get round CORS issue

I have a React app which is running webpackdevserver on port 3000.
I have an AWS .NetCore Lambda server running localhost on port 5050.
When I try and make a request I am getting the cors error:
Access to fetch at 'http://localhost:5050/' from origin
'http://localhost:3000' 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. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
I was hoping to use a proxy, as per the documtation here in order to forward my requests on using the same domain to get round this.
https://medium.com/#drgenejones/proxying-an-external-api-with-webpack-serve-code-and-a-restful-data-from-separate-endpoints-4da9b8daf430
However it is not working, I don't see any difference at all with the settings applied, can anyone help?
devServer: {
port: 3000,
disableHostCheck: true,
compress: true,
host: 'localhost',
proxy: {
'/': {
target: 'http://localhost:5050',
secure: false,
},
},
},
My JavaScript to call the server is like this... I have also tried with the url http://localhost:3000 but this just returns a bad request error.
const result = await fetch('http://localhost:5050', {
method: 'POST',
headers: new Headers({ 'Access-Control-Allow-Origin': '*' }),
body: JSON.stringify({
method: 'upload',
test: 'test',
}),
});
I guess the issue is to set / which could just fetch the current server so you might need to differentiate between your web app vs your server (most likely via a specific path such as /api, but you can choose to pass this path to your proxy server or not).
So you would change as following:
Your configuration of proxy first to take api to go through proxy:
proxy: {
'/api': {
target: 'http://localhost:5050',
pathRewrite: {'^/api' : ''}, // In this case we don't pass `api` path
}
}
Next thing is to change your code to call the same domain + port 3000 normally (proxy would do the rest for you by passing to your server with port 5050 which you configured):
const result = await fetch('http://localhost:3000/api', {
// ...
});

Hapi - enabling CORS

I am writing BE application using Node JS and Hapi (v17). While the server is running and I try to call an endpoint using POST method I keep receiving an error message:
Failed to load http://localhost:8001/login: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
I wanted to enable CORS on the server site, but nothing works for me.
here is how I enable CORS on the server site:
const hapi = require('hapi')
const server = hapi.server({
port: 8001,
host: 'localhost',
routes: {
cors: true
}
})
I was also trying to enable cors for the specific route but this also has no effect:
server.route({
method: 'POST',
path: '/login',
config: {
cors: {
origin: ['*'],
additionalHeaders: ['cache-control', 'x-requested-with']
}
},
handler: async (request, reply) => {
return User.login(request, reply)
}
})
Does anyone know what should I do to enable CORS and get rid of the problem?
Additionally, there is a screenshot from the browser's network tab:
EDIT:
I have added route that handles OPTIONS method and now I have another issue.
Failed to load http://localhost:8001/login: Request header field access-control-allow-credentials is not allowed by Access-Control-Allow-Headers in preflight response.
And here is how things look like in the network tab:
cors: {
origin: [
'*'
],
headers: ["Access-Control-Allow-Headers", "Access-Control-Allow-Origin","Accept", "Authorization", "Content-Type", "If-None-Match", "Accept-language"],
additionalHeaders: ["Access-Control-Allow-Headers: Origin, Content-Type, x-ms-request-id , Authorization"],
credentials: true
}
You should also probably define a qualified domain, instead of just * wildcard

Sails ignoring CORS settings

I've been trying to set up CORS in Sails 0.12.0 on a per route basis. According to the documentation, it should only be a matter of adding a "cors" object to the routes where you want to override the global settings. I did it like this:
routes.js
module.exports.routes = {
'/': {
view: 'homepage'
},
'GET /widget/render/:id': {
controller: 'WidgetController',
action: 'render',
cors: {
origin: '*',
credentials: false
}
}
};
I'm not sure if the headers should be added inside the controller, or if it's enough to use the route configuration, but I'm only getting empty CORS headers in every request.

Categories