Google Oauth 错误:redirect_uri_mismatch

Fra*_*ser 2 oauth google-calendar-api amazon-ec2

我正在尝试使用 google Oauth 2 通过 google calendar API 对在 AWS EC2 上运行的 Web 服务器进行身份验证。

当我生成凭据时,我选择了“OAuth 客户端 ID”,然后选择“Web 应用程序”。对于我输入的授权重定向 URI:

http://ec2-XX-XX-XX-XXX.eu-west-1.compute.amazonaws.com (我已将 EC2 实例的 IP 清空)。我已经检查过这是我希望回调转到的正确 URL。

服务器日志中生成的链接的形式为:

https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=XXXXXXXXXXXX-XXXXXXXXXXXXXX.apps.googleusercontent.com&redirect_uri=http://localhost:47258/Callback&response_type=code&scope=https://www.googleapis。 com/auth/calendar.readonly

当我点击链接时,出现错误“错误:redirect_uri_mismatch”。

我已经阅读了这个问题,并检查了我正在使用 HTTP 并且没有试用“/”

我怀疑生成的 URL 中不应包含“localhost”,但我已多次重置 client_secret.json,每次使用新的客户端密钥重新启动 tomcat 时,我仍然会获得与 localhost 的链接,但只是通过不同的端口。

在本地,我之前选择了“其他”凭据类型,并且没有提供授权重定向 URI 的选项。我确实在 EC2 实例上尝试过此操作,但这不会让我获得我想要的对重定向 URI 的控制并通过 localhost 发送重定向。

abd*_*eel 5

如果您在从服务器进行 API 调用以获取令牌时看到此错误。

简短回答 - 是什么解决了我的问题

使用字符串postmessage代替redirectUri您在云控制台上配置的实际字符串。

这是我对 OAuth2 客户端的初始化,对我有用。

// import {Auth, google} from 'googleapis`;

const clientID = process.env.GOOGLE_OAUTH_CLIENT_ID;
const clientSecret = process.env.GOOGLE_OAUTH_CLIENT_SECRET;
oauthClient = new google.auth.OAuth2(clientID,clientSecret,'postmessage');

Run Code Online (Sandbox Code Playgroud)

我的情况

在前端,我使用 React 来提示用户使用 google 登录authentication-code。成功后,这会返回到需要发布到 google API 服务器以获取- 、等的code有效负载中。tokenAccess TokenRefresh TokenID Token

我在我的服务器上使用googleapis包。这是我从谷歌检索用户信息的方法

// import {Auth, google} from 'googleapis`;

const clientID = process.env.GOOGLE_OAUTH_CLIENT_ID;
const clientSecret = process.env.GOOGLE_OAUTH_CLIENT_SECRET;
oauthClient = new google.auth.OAuth2(clientID,clientSecret,'postmessage');

/*
    get tokens from google to make api calls on behalf of user.
    @param: code -> code posted to backend from the frontend after the user successfully grant access from consent screen
*/
const handleGoogleAuth = (code: string) => {
    oauthClient.getToken(code, async (err, tokens: Auth.Credentials) {
        if (err) throw new Error()

        // get user information
        const tokenInfo = await oauthClient.verifyIdToken({
          idToken: tokens.id_token
        });
    
        const {email, given_name, family_name, email} = tokenInfo.getPayload();
        // do whatever you want to do with user informaton
    }
}

Run Code Online (Sandbox Code Playgroud)