簡體   English   中英

Azure AD B2C 如何使用 GraphQL(Apollo 服務器)API 和 Z85BBEF56E2905610299Z836 進行身份驗證

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM