[英]How Azure AD B2C can authenticate with GraphQL (Apollo Server) API and ReactJs
In the documentation there is a sample react app is authenticating with nodejs ( expressJs - REST API ) link is here: https://docs.microsoft.com/en-us/azure/active-directory-b2c/configure-authentication-sample -反应水疗应用
但是没有任何关于使用 Nodejs(GraphQL-Apollo 服务器)API 身份验证的 react App 的文章。 请帮助我,因为我想应用与 REACT -NODEJS 文档中所写相同的身份验证(但使用 graphQL-Apollo Server API ),但互联网上没有关于它的线索。
解决方案因此,在尝试了几件事后,我找到了问题的解决方案。 所以首先使用 apollo-server-express。 该库使您能够将 Apollo Server 连接到 Express 服务器。
const { ApolloServer, gql } = require(apollo-server-express);
const http =require(http)
const {ApolloServerPluginDrainHttpServer, ApolloServerPluginLandingPageLocalDefault,ApolloServerPluginLandingPageGraphQLPlayground,
ApolloServerPluginLandingPageDisabled,ApolloServerPluginLandingPageProductionDefault} = require(apollo-server-core)
const express = require(express)
const BearerStrategy = require(passport-azure-ad).BearerStrategy;
const config = require(./config.json);
const passport = require(passport);
const cors = require(cors)
const options = {
identityMetadata: `https://${config.metadata.b2cDomain}/${config.credentials.tenantName}/${config.policies.policyName}/${config.metadata.version}/${config.metadata.discovery}`,
clientID: config.credentials.clientID,
audience: config.credentials.clientID,
policyName: config.policies.policyName,
isB2C: config.settings.isB2C,
validateIssuer: config.settings.validateIssuer,
loggingLevel: config.settings.loggingLevel,
passReqToCallback: config.settings.passReqToCallback,
scope: config.protectedRoutes.hello.scopes
}
const bearerStrategy = new BearerStrategy(options, (token, done) => {
// Send user info using the second argument
done(null, { }, token);
console.log(token)
}
);
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`;
const books = [
{
title: 'The Awakening',
author: 'Kate Chopin',
},
{
title: 'City of Glass',
author: 'Paul Auster',
},
];
const resolvers = {
Query: {
books: () => books,
},
};
async function startApolloServer(typeDefs, resolvers) {
// Required logic for integrating with Express
const app = express();
app.use(cors({ origin: true }))
passport.use(bearerStrategy)
const getUser = (req, res) =>
new Promise((resolve, reject) = {
passport.authenticate('oauth-bearer', { session: false }, (err, user) = {
if (err) reject(err)
resolve(user)
console.log(user)
})(req, res)
})
const httpServer = http.createServer(app);
const server = new ApolloServer({
typeDefs,
resolvers,
context: async ({ req, res }) => {
const user = await getUser(req, res)
if (!user) throw new AuthenticationError('No user logged in')
console.log('user found'; user)
return { user }
},
csrfPrevention: true,
cache: bounded
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
ApolloServerPluginLandingPageLocalDefault({ embed: true }),
process.env.NODE_ENV === production;
? ApolloServerPluginLandingPageDisabled() // turning playground off in production isn't really a thing anymore
: ApolloServerPluginLandingPageGraphQLPlayground(),
],
});
// More required logic for integrating with Express
await server.start();
server.applyMiddleware({
app,
path:/hello;
});
await new Promise(resolve =httpServer.listen({ port: 5000 }, resolve));
console.log(`Server ready at http://localhost:5000${server.graphqlPath}`);
}
startApolloServer(typeDefs,resolvers)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.