Reputation: 1
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource a github oauth api using fastify-oauth2 from react
Giving the error below:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://github.com/login/oauth/authorize?response_type=code&client_id=<client_id>&redirect_uri=http%3A%2F%2Flocalhost%3A4000%2Foauth2%2Fgithub%2Fcallback&scope=user&state=<state>. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 404.
fastify-oauth2 config options:
const oAuthOptions: FastifyOAuth2Options = {
name: "githubOAuth2",
scope: ["user"],
credentials: {
client: {
id: "<CLIENT_ID>",
secret: "<CLIENT_SECRET",
},
auth: oAuth2Plugin.GITHUB_CONFIGURATION,
},
startRedirectPath: "/oauth2/github/login",
callbackUri: "http://localhost:4000/oauth2/github/callback",
};
callback route:
app.get(
"/github/callback",
async (req: FastifyRequest, reply: FastifyReply) => {
try {
const { token } =
await app.githubOAuth2.getAccessTokenFromAuthorizationCodeFlow(req);
console.log({ userAuthToken }, "Authenticated successfully!");
reply.send({ token });
} catch (error) {
reply.code(500).send("Failed to authenticate");
}
}
);
cors config options: tried multiple options
const corsOptions: FastifyCorsOptions = {
origin: "*",
// ["https://github.com", "http://localhost:5173"],
credentials: true,
// allowedHeaders: [
// "Access-Control-Allow-Origin",
// "Access-Control-Allow-Headers",
// "Origin, X-Requested-With, Content-Type, Accept",
// ],
};
React code to call the api:
const handleOAuth = async () => {
try {
const response = await axios.get("http://localhost:4000/oauth2/github/login");
console.log(response.data);
history("/user");
} catch (error) {
console.error(error);
}
};
when I am calling the api from the index.html srcipt window.location.assign
its working as if its replacing the url and calling it.
But when calling from a react app using axios its showing cors error
Upvotes: 0
Views: 236
Reputation: 1
You should include credentials in your axios request
here is how you might implement this:
const response = await axios.get("http://localhost:4000/oauth2/github/login", {
withCredentials: true
});
See if it helps !
By the way does anyone knows why @fastify/cors is not setting session-cookie in my case:
Upvotes: 0