Vue 3 and cookies - vue.js

I am building a frontend in Vue 3 and backend with fastAPI. I'd like to use httponly in the authentication process but I don't see in the browser that the cookie is received. I have checked with Postman the request to backend and I see the "set-cookie" with the data from backend.
Frontend:
Vue 3
Axios 0.18.1
url: 127.0.0.1:8080
Backend:
FastAPI
uvicorn
url: 127.0.0.1:8000
In the frontend the post message with Axios is like:
axios
.post(process.env.VUE_APP_API_URL + '/login', this.auth, {withCredentials: true})
.then(res => {
console.log(res.data);
})
.catch(e => {
console.log(e);
});
and in backend I configure explicit origins:
origins = [
"http://localhost",
"http://localhost:8080",
"http://127.0.0.1",
"http://127.0.0.1:8080",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
and when I return the response to frontend:
response.set_cookie(
key="Authorization",
value=f"Bearer {token}",
domain="127.0.0.1",
path="/login",
httponly=True,
secure=False,
max_age=1800,
expires=1800,
)
thanks for advance.

I have done the following changes and now it is working:
Frontend:
.env.development file:
NODE_ENV=development
VUE_APP_API_URL=http://localtest.me:8000
Backend:
origins = [
"http://localhost",
"http://localhost:8080",
"http://localtest.me",
"http://localtest.me:8080"
]
response.set_cookie(
key="Authorization",
value=f"Bearer {token}",
domain="localtest.me",
path="/",
httponly=True,
secure=False,
max_age=1800,
expires=1800,
)

Related

Axios NextJS to Express CORS blocked

I'm calling a my express server in NextJS like this:
const { data } = await axios.post(
url,
body,
{
withCredentials: true,
}
);
and in the server I have this configuration:
app.use(
cors({
origin: "*",
credentials: true,
})
);
When I make requests using Nextjs in any browser I get CORS error no allow credentials.
I call the same endpoint in Insomnia and don't get any issue

Backend api call not working in Vue(front)

My environment
front - windows, port 3000
backend - linux (ubuntu) in docker container, port 5000
Vue(front) tsconfig.json
export default defineConfig({
plugins: [vue(), vueJsx()],
resolve: {
alias: {
"#": fileURLToPath(new URL("./src", import.meta.url)),
},
},
server: {
host: true,
port: 3000,
proxy: {
"/api": {
target: "http://127.0.0.1:5000",
changeOrigin: true,
secure: false,
rewrite: (path) => path.replace(/^\/api/, ""),
},
},
},
});
front api call code
const response = await axios.post("http://127.0.0.1:5000/users/login?email=" + code);
backend(Nestjs) - main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: 'http://localhost:3000',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
credentials: true,
});
await app.listen(5000);
}
bootstrap();
I expect the api call to go to the backend, localhost:5000
but i get a 404 error
When I tried with postman, I got normal return, but when I sent the request using axios in Vue with the same request, I got 404 not found.
The most incomprehensible thing is that with the current settings, it was normally requested when developing in the past.
I don't know how to fix this
please help a lot
Repositories currently being edited: https://github.com/PracticeofEno/ft_transcendence
thanks
omg... I send POST message..
But api is GET Message

API Requests that need Authorization return CORS error

Initial Problem
I work on a web application (react) that accesses data via an API. The API runs for development reasons on a docker container on my local machine. Simple GET requests (via axios) got me CORS complications (...has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.).
A bit of researching solved my problem by running a nginx reverse proxy in another container. I basically used this configuration for the nginx server.
New Problem
As I progress in building my application, I come to a point where I need to send the JWT to the API to access and alter some entries. Requests that need sending a JWT again get me CORS error messages.
The API checks the JWT signature (RS256 generated). I just have to forward it to the API server.
ALSO: simple curl requests with the JWT from the console are working.
Configuration
axios
const axiosConfig = {
responseType: "json",
withCredentials: false,
mode: "no-cors",
headers: {
'Access-Control-Allow-Origin': "*",
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE,PATCH,OPTIONS',
'Content-Type': 'application/json',
'Authorization': 'Bearer <JWT as string>',
},
};
const apiGetRequest = async (route, callback) => {
try {
const apiUrl = URL + route;
axios.get(apiUrl, {
axiosConfig
})
.then(res => {
callback(res);
})
.catch(function (error) {
console.log(error);
});
} catch (error) {
console.log(error);
}
}
nginx configuration
Docker Image for api
version: "3.9"
services:
db:
image: mariadb:latest
container_name: db
env_file:
- ./mariadb/.env
volumes:
- ./mariadb/create-schema-docker.sh /docker-entrypoint-initdb.d
- db-data:/var/lib/mysql
ports:
- 3306:3306
rest:
image: mds4ul/station-registry:latest
container_name: api
environment:
- DB_HOST=db
- CONTEXT_PATH=api
env_file:
- ./rest/.env
depends_on:
- db
ports:
- 80:8080
volumes:
db-data:
Questions
Why do I get CORS errors for requests where a jwt is needed and not for requests that do not require one?
Which part do I have to change to make this work?
So answer another question to an embarrassing easy problem of mine.
I switched to an express.js proxy server with the following configuration:
const express = require('express')
const app = express()
const axios = require('axios')
const cors = require('cors')
var bodyParser = require('body-parser')
app.use(cors({
origin: '*'
}))
app.use(bodyParser.json())
require('dotenv').config()
const headers = {
"X-Authorization": <token>,
}
app.get(':endpoint([\\/\\w\\.-]*)', function (req, res) {
const endpoint = (process.env.API_BASE_URL).replace(/\/$/, "") + req.params.endpoint;
axios.get(endpoint, { headers }).then(response => {
res.json(response.data)
}).catch(error => {
res.json(error)
})
})
app.listen(3001)
I assume I just could not figure out my nginx configuration for this use case. So with express.js I can access now resources which need authorization.

Nuxt: wrong Axios base URL in client side API requsets

I have set axios Base_url like this in Nuxt config
axios: {
baseURL: process.env.API_URL,
},
the problem is that when i requset api in client side, axios uses default base_url ,
i mean it sends requests to http://localhost:3000/ not to my backend server .
But for requests in server side everything is ok .
the below pic shows client side request .
Try setting Up proxy for the APIs . (In network tab the url will show up as it is shown in the question image)
axios: {
baseURL: process.env.API_URL, // Must be base url
proxy: process.env.NODE_ENV === 'development'
}
proxy:
process.env.NODE_ENV === 'development'
? {
'/': {
target: process.env.API_URL,
changeOrigin: true,
logLevel: 'debug',
secure: false
}
}
: false,

Apache frontend can't request to express backend

I'm hosting my vueJS frontend on an apache server. Without running the apache just by calling "npm run serve" and visiting my page over http (https is enabled on express backend), I can successfully request to the backend.
When starting apache and visiting the page over https (self-signed SSL certificates), I can't send requests.
Firefox error:
Cross-source (cross-origin) request blocked: The same source rule prohibits reading the external resource on https://143.93.46.35:60702/user/login. (Reason: CORS request failed).
And chrome:
xhr.js:160 POST https://143.93.46.35:60702/user/login net::ERR_SSL_PROTOCOL_ERROR
I enabled https on my express backend like:
https.createServer({
key: fs.readFileSync('certs/apache-selfsigned.key'),
cert: fs.readFileSync('certs/apache-selfsigned.crt')
}, app)
.listen(nconf.get('port'), function() {
console.log(`App listening on port lalala! Go to https://localhost:3000/`)
});
Enabled cors in app.js like:
const cors = require('cors');
...
// Enable CORS (cross origin resource sharing)
app.use(cors({
credentials: true,
origin: true
}));
app.options('*', cors());
And the vue service which handles the axios calls is:
const apiClient = axios.create({
baseURL: `https://inf-education-47.umwelt-campus.de:60702`,
withCredentials: false, // This is the default
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
})
export default {
// user Endpoints
getUser (email) {
return apiClient.get(`/user/${email}`)
},
registerUser (user) {
return apiClient.post(`/user/register`, user)
},
loginUser (user) {
return apiClient.post(`/user/login`, user)
},
...
In apache I edited the vhost conf to enable cors like:
<VirtualHost *:80>
ServerAdmin webmaster#test.de
DocumentRoot /var/www/client/pvapp-client/dist
Header set Access-Control-Allow-Origin "*"
....
What can be the reason for the errors when hosting vue with apache over https?