Не работает авторизация через гугл
Есть код на node typescript
import express, { Request, Response } from 'express';
import { google } from 'googleapis';
import cors from 'cors';
const app = express();
const CLIENT_ID = 'CLIENT_ID';
const CLIENT_SECRET = 'CLIENT_SECRET';
const REDIRECT_URI = 'http://localhost:3000/';
const oAuth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);
// Middleware для разрешения CORS запросов
app.use(cors({
origin: 'http://localhost:3000',
credentials: true
}));
// Маршрут для инициации аутентификации через Google OAuth
app.get('/auth/google', (req: Request, res: Response) => {
const url = oAuth2Client.generateAuthUrl({
access_type: 'offline',
scope: ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile']
});
res.redirect(url);
});
// Маршрут обратного вызова для обработки ответа от Google OAuth
app.get('/auth/google/callback', async (req: Request, res: Response) => {
const code = req.query.code as string;
try {
const { tokens } = await oAuth2Client.getToken(code);
oAuth2Client.setCredentials(tokens);
const userInfo = await google.oauth2({ version: 'v2', auth: oAuth2Client }).userinfo.get();
res.send(userInfo.data);
} catch (error) {
console.error('Ошибка при получении токена доступа', error);
res.status(500).send('Ошибка при получении токена доступа');
}
});
app.listen(5000, () => {
console.log('Сервер запущен на порте 5000');
});
Код рабочий при переходе на прямую на http://localhost:5000/auth/google, но при подключении через frontend выдаёт ошибку Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&response_type=code&client_id=789517930265-9d8g5orqgtnc2eidn7ftvqt18hanqdss.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2F' (redirected from 'http://localhost:5000/auth/google') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Прикрепляю код из frontend
// reg.tsx
import React, { useContext, useState } from 'react'
import { Context } from '..'
export const Reg = () => {
const { store } = useContext(Context)
const handleGoogle = async () => {
try {
await store.googleAuth();
} catch (error) {
console.error('Error during Google authentication', error);
}
}
return (
<div>
<button onClick={handleGoogle}>Google</button>
</div>
)
}
// store.ts
import { makeAutoObservable } from "mobx"
import { User } from "../model/User"
import AuthService from "../service/AuthService"
import api from "../http"
export default class Store{
user = {} as User
error? = []
isAuth = false
isLoading = false
constructor(){
makeAutoObservable(this)
}
setAuth(bool:boolean){
this.isAuth = bool
}
setUser(user: User){
this.user = user
}
setLoading(bool: boolean){
this.isLoading = bool
}
setError(error?: []){
this.error = error
}
async googleAuth(): Promise<void> {
try {
await api.get('auth/google');
} catch (error) {
throw new Error('Error during Google authentication');
}
}
}
//http/index.ts
import axios from 'axios';
import { AuthRespose } from '../model/AuthResponse';
export const API_URL = `http://localhost:5000/`
const api = axios.create({
withCredentials: true,
baseURL: API_URL
})