Flutter:Google 在 Passport Nodejs 中使用 REST API 服务器登录

问题描述 投票:0回答:2

我已使用护照在我的 REST api 服务器上设置 Google 登录。它在浏览器中工作得很好,但是在尝试将其与 flutter 客户端集成时,它在响应中返回 html body,这与 Google 的 Oauth Page 的 html 相同,但是如何通过 flutter 与其交互?

我不想使用 firebase,我想使用我自己的 REST api 服务器,那么有没有办法使用相同的服务器端护照 Google oauth 实现从我的 flutter 客户端通过 google 登录?谢谢!

我在服务器端使用以下代码: 调用护照谷歌策略:

router.get("/auth/google", passport.authenticate("google", {
  scope: [
    "profile",
    "https://www.googleapis.com/auth/userinfo.email",
    "https://www.googleapis.com/auth/user.gender.read",
    "https://www.googleapis.com/auth/user.birthday.read",
  ],
}));

在护照中设置Google策略:

passport.use(
  new GoogleStrategy(
    {
      // Options for Google Strategy
      clientID: keys.google.clientID,
      clientSecret: keys.google.clientSecret,
      callbackURL: "/auth/google/redirect",
    },
    (accessToken, refreshToken, profile, done) => {
      // Getting the profile info in the profile object here
      // Processing and saving to database and returning token here
    }));

当服务器运行时,此代码可以在浏览器中正常工作。 在使用flutter客户端访问时,我使用以下代码:

      var client = http.Client();
      // Setting host to server url
      var host = ServerConfigurations.serverUrl;

      // Sending the request to url
      var url = Uri.parse(host + '/auth/google');
      var response = await client.get(url);
      print(response.body)

我在response.body中得到以下输出:

window.WIZ_global_data = {"Mo6CHc":-1837354689584917033,"OewCAd":"%.@."xsrf",null,[""],"AFoagUULlmYCAAPS_i54RaA1IYHMtpObpA:1629146249091"]","Qzxixc" :“S-15920024 :1629146249091588","thykhd":"AKH95etLw808YNsVCgaUCE1PDuZ-9LWIBpdXwNoEGupH-bJFW7ote5ATz8bZB2iQ0DBiB-q7XELpdkCrfXHUe68OcXo091I3LI-CHAQICAFqdeziYoXgFe I\u003d","w2btAe":"%[电子邮件受保护],null,"",false,null,null,null,false] "};登录 – Google 帐户(function(H) {H.className="CMgTXc";})(document.documentElement);(function(){var z=function(x,O,J,w,S, q,f,u,k,D,X,C,K,b,r,e,P,c,W,p,y){r

node.js flutter express passport.js passport-google-oauth
2个回答
1
投票

抱歉我的英语不好,我认为你可以使用网络视图, 我认为你可以使用 webview 来显示你的登录信息,你必须在节点服务器中创建这个 url,然后将其传递给 webview,然后在 flutter 中,当你退出该 webview 时,你会使用其他端点再次检查你的 api,所以你知道如果我登录或不登录,此端点必须返回 jwt 令牌


0
投票

你能解决这个问题吗?我现在也面临着同样的问题

Goes 不允许 webview,因为它不安全。因此,我使用了 url 启动器,它可以完成注册过程并将用户添加到数据库中,但在尝试使用深层链接重定向回应用程序时出现错误

错误信息如下: flutter:启动 Google 登录时出错:PlatformException(错误,启动时出错 https://app-api.onrender.com/api/auth/google,null,null) flutter:错误消息:启动时出错https://app-api.onrender.com/api/auth/google

这是颤振代码:

Future<void> initiateGoogleSignIn() async {
    final backendUrl = Uri.parse('$liveUrl/auth/google');
    try {
      if (await canLaunchUrl(backendUrl)) {
        await launchUrl(
          backendUrl,
          webViewConfiguration: WebViewConfiguration(
            headers: headers!,
          ),
        );
      } else {
        throw 'Could not launch $backendUrl';
      }
    } catch (e) {
      print("Error launching Google Sign-In: $e");
      if (e is PlatformException) {
        print("Error Message: ${e.message}");
        print("Error Details: ${e.details}");
      }
    }
  }


  Future<void> googleRegister(BuildContext context) async {
    try {
      await initiateGoogleSignIn();

      if (context.mounted) {
        final redUrl = ModalRoute.of(context)!.settings.name!;
        if (redUrl.startsWith("app://auth/successScreen")) {
          // Parse token and email from the deep link
          Uri uri = Uri.parse(redUrl);
          String? token = uri.queryParameters['token'];
          String? email = uri.queryParameters['email'];

          if (token != null && email != null) {
            Navigator.pop(context);
          }
        }

        print("Google Login Token: $redUrl");
      }
    } catch (e) {
      debugPrint('Error during Google registration: $e');
    }
  }

这是nodejs代码:

const express = require("express");
const passport = require("passport");
const router = express.Router();

// Middleware to check if the user is authenticated
function isAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.redirect("/");
}

router.get("/auth/google", (req, res, next) => {
  console.log(next);
  // Log the full redirect URI
  const redirectUri = req.protocol + "://" + req.get("host") + req.originalUrl;
  console.log("Redirect URI:", redirectUri);

  // Generate the authentication URL with Google
  passport.authenticate("google", {
    scope: ["profile", "email"],
    session: false,
  })(req, res, next);
});



router.get(
  "/auth/google/callback",
  passport.authenticate("google", { failureRedirect: "/" }),
  (req, res) => {
    // Successful authentication, redirect to dashboard or desired route
    res.redirect(
      `app://auth/successScreen?token=testtoken&email=myemail`
    );
  }
);

router.get("/logout", (req, res) => {
  req.logout((err) => {
    if (err) {
      return next(err);
    }
    res.redirect("/");
  });
});

module.exports = router;
© www.soinside.com 2019 - 2024. All rights reserved.