Graphql 在服务器-客户端应用程序中使用passport-google-oauth2身份验证
我有一个与mongodb数据库连接的TypeOrm/React应用程序,其中服务器位于端口4000,客户端位于端口3000。 在客户端上,我创建了文件googleAuth:Graphql 在服务器-客户端应用程序中使用passport-google-oauth2身份验证,graphql,passport.js,react-apollo,google-authentication,passport-google-oauth,Graphql,Passport.js,React Apollo,Google Authentication,Passport Google Oauth,我有一个与mongodb数据库连接的TypeOrm/React应用程序,其中服务器位于端口4000,客户端位于端口3000。 在客户端上,我创建了文件googleAuth: import passport from 'passport'; import {User} from './entity/User'; const GoogleStrategy = require('passport-google-oauth20').Strategy; const googleOptions = {
import passport from 'passport';
import {User} from './entity/User';
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const googleOptions = {
clientID: process.env.clientID,
clientSecret: process.env.clientSecret,
callbackURL: 'http://localhost:4000/auth/google/callback',
profileFields: ['id', 'email', 'first_name', 'last_name'],
};
const googleCallback = (_accessToken: any, _refreshToken: any, profile: any, done: any) => {
const matchingUser = User.findOne({googleId: profile.id});
if (matchingUser) {
done(null, matchingUser);
return;
}
const newUser = {
googleId: profile.id,
firstName: profile.name.givenName,
lastName: profile.name.familyName,
email: profile.emails && profile.emails[0] && profile.emails[0].value
};
User.create(newUser);
done(null, newUser);
}
export const googleAuth = () => passport.use(new GoogleStrategy(
googleOptions,
googleCallback
));
我的index.ts(服务器)文件如下所示:
import "reflect-metadata";
import {createConnection} from "typeorm";
import "dotenv/config"
import express from "express";
import { ApolloServer } from "apollo-server-express";
import { buildSchema } from "type-graphql";
import cors from "cors";
import { PostResolver } from "./resolvers/PostResolver";
import { UserResolver } from "./resolvers/UserResolver";
import path from 'path';
import passport from "passport";
import { googleAuth} from './googleAuth';
(async () => {
await createConnection();
googleAuth();
passport.serializeUser(function(user: any, done: any) {
done(null, user);
});
passport.deserializeUser(function(user: any, done: any) {
done(null, user);
});
const app = express();
app.use(cors());
app.use(passport.initialize());
app.get('/auth/google', passport.authenticate('google', { scope: ['email'] }));
app.get('/auth/google/callback', passport.authenticate('google', {
successRedirect: 'http://localhost:4000/graphql',
failureRedirect: 'http://localhost:4000/graphql',
}));
const apolloServer = new ApolloServer({
schema: await buildSchema({
resolvers: [ PostResolver, UserResolver ]
}),
context: ({ req }) => ({
getUser: () => req.user,
logout: () => req.logout()
})
// context: ({ req, res }) => ({ req, res })
});
apolloServer.applyMiddleware({ app });
app.use(express.static('public'));
app.get('*', (_, res) => {
res.sendFile(path.resolve(__dirname, '../public', 'index.html'))
});
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Server started on port ${port}`));
})();
我的用户解析程序:
import {
Resolver,
Query,
Ctx
} from "type-graphql";
import { User } from "../entity/User";
import { MyContext } from '../MyContext';
import { ExpressContext } from "apollo-server-express/dist/ApolloServer";
@Resolver()
export class UserResolver {
@Query(() => [User])
users() {
return User.find();
}
@Query(() => String)
getUser(@Ctx() { req }: ExpressContext) {
console.log(req);
return `your user id is: ${req.user}`;
}
}
在credenatials我加上
授权的JavaScript来源:http://localhost:4000
在授权重定向URI中:http://localhost:4000/auth/google/callback
我可以登录,但无法获取任何数据。我知道这是一段非常混乱的代码,但我需要组织并重写它。
首先,我想知道我应该在凭证中添加哪些域和重定向。
二是配置服务器。
第三,创建用户解析器。
第四,与客户一起获取数据