When user Log In I am creating Login using pyjwt and setting Httponly cookie but not able to set the cookie because of CROS.
When user Log In I am creating Login using pyjwt and setting httponly cookie like this.
def create_jwt(user_id: str, ip_address: str=None):
payload = {
"sub": str(user_id),
"ip": ip_address,
"iat": datetime.now(),
"exp": datetime.now() + timedelta(minutes=30)
}
return jwt.encode(payload, PRIVATE_KEY, algorithm="RS256)
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
database = self.client["test"]
@login_router.post("/login", response_model=SuccessResponse, tags=("Login",))
async def login(request: LoginRequest, response: Response):
try:
username = request.username
password = request.password
user = database.find_one(
"user",
filter={"username": username},
)
if not user or not login_instance.verify_password(
password, user.get("password"), user.get("salt")
):
raise InvalidUser()
from ..authentication import create_jwt
response.set_cookie(
key="access_token",
value=create_jwt(username),
httponly=True,
samesite="None",
secure=False,
path="/",
)
response_content = {
"status": status.HTTP_200_OK,
"success": True,
"message": "User Logged In successfully",
"data": {},
}
return response_content
except InvalidUser:
raise InvalidUser()
except Exception as e:
raise InternalServerError(e)
When i hit this API in frontend (my frontend is written in VueJS) it is saying not able to set the cookie.
Error Image
I have add CROS in FastAPI main.py
main.py
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:8081"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
My front end is running on port **8081.
Frontend**
api.js
import axios from 'axios';
const apiURL = process.env.VUE_APP_BASE_URL;
const apiClient = axios.create({
baseURL: apiURL,
headers: {
'Content-Type': 'application/json',
},
withCredentials: true,
});
export const get = (endpoint, params = {}) => {
return apiClient.get(endpoint, { params });
};
export const post = (endpoint, payload) => {
return apiClient.post(endpoint, payload);
};