首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在第二次尝试尝试refreshToken时,如何修复“格式错误的auth代码”?

在第二次尝试尝试refreshToken时,如何修复“格式错误的auth代码”?
EN

Stack Overflow用户
提问于 2019-10-02 21:37:04
回答 7查看 17.1K关注 0票数 10

我正在开发一个Android应用程序,附带了插件,我想将它与Google身份验证集成在一起。我已经安装了cordova-plugin-googleplus并成功地集成到了应用程序中。当用户登录时,我会得到一个响应,在那里我可以获得accessToken、profile用户信息和refreshToken。

现在,我想实现一个特性来刷新令牌,而不需要每小时使用一个新的提示屏幕来干扰用户。

我已经成功地更新了accessToken,但它只在第一次起作用

我用过以下两种方法:

  1. 发送具有以下数据的curl请求
代码语言:javascript
运行
复制
curl -X POST \
  'https://oauth2.googleapis.com/token?code=XXXXXXXXXXXXXXXX&client_id=XXXXXXXXXXXXXXXX.apps.googleusercontent.com&client_secret=YYYYYYYYYYYY&grant_type=authorization_code' \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/x-www-form-urlencoded'
  1. 使用for Java在服务器端实现它,并主要遵循以下代码

关键是当用户第一次登录时(使用cordova-plugin-googleplus),我会收到一个具有这种格式的refreshToken。

代码语言:javascript
运行
复制
4/rgFU-hxw9QSbfdj3ppQ4sqDjK2Dr3m_YU_UMCqcveUgjIa3voawbN9TD6SVLShedTPveQeZWDdR-Sf1nFrss1hc

如果过了一段时间,我尝试以上述任何一种方式刷新令牌,我将使用一个新的accessToken和一个新的refreshToken获得成功的响应。而新的refreshToken有另一种格式

代码语言:javascript
运行
复制
1/FTSUyYTgU2AG8K-ZsgjVi6pExdmpZejXfoYIchp9KuhtdknEMd6uYCfqMOoX2f85J

在第二次尝试更新令牌时,我用在第一个请求中返回的令牌替换令牌。

代码语言:javascript
运行
复制
curl -X POST \
  'https://oauth2.googleapis.com/token?code=1/FTSUyYTgU2AG8K-ZsgjVi6pExdmpZejXfoYIchp9KuhtdknEMd6uYCfqMOoX2f85J&client_id=XXXXXXXXXXXXXXXX.apps.googleusercontent.com&client_secret=YYYYYYYYYYYY&grant_type=authorization_code' \
  -H 'Cache-Control: no-cache' \
  -H 'Content-Type: application/x-www-form-urlencoded'

但是这一次,这两种方法(Curl和Java)我都得到了相同的错误。

代码语言:javascript
运行
复制
{
  "error" : "invalid_grant",
  "error_description" : "Malformed auth code."
}

我在这个线程上读到,将clientId指定为电子邮件是个问题,但我还没有发现如何解决它,因为它的第一次登录是用客户端id 'XXXXXXX.apps.googleusercontent.com‘完成的,如果我从google帐户设置了一封电子邮件,它说这是一个“未知的Oauth客户端”

我希望任何人都能帮助我,因为我被困了好几天

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2020-03-15 23:19:38

最后,我实现了在需要时刷新访问令牌。问题是人们对谷歌Api的工作方式产生了误解。

第一次更新令牌时,需要使用这些参数调用此端点,并将从同意屏幕调用(serverAuthCode)的响应中获得的值设置为{serverAuthCode}{{}。

代码语言:javascript
运行
复制
https://oauth2.googleapis.com/token?code={{refreshToken}}&client_id={{googleClientId}}&client_secret={{googleClientSecret}}&grant_type=authorization_code

第一次刷新之后,任何对令牌的更新都需要调用到另一个端点,方法是将从第一个调用的响应中获得的属性{{tokenUpdated}设置为{{refresh_token}。

代码语言:javascript
运行
复制
https://oauth2.googleapis.com/token?refresh_token={{tokenUpdated}}&client_id={{googleClientId}}&client_secret={{googleClientSecret}}&grant_type=refresh_token

这里我向您展示了我的AuthenticationService的一个例子

代码语言:javascript
运行
复制
import { Injectable} from '@angular/core';
import { Router } from '@angular/router';
import { GooglePlus } from '@ionic-native/google-plus/ngx';

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {


static AUTH_INFO_GOOGLE = 'auth-info-google';
static CLIENT_ID = 'XXXXX-XXXX.apps.googleusercontent.com';
static CLIENT_SECRET = 'SecretPasswordClientId';


public authenticationState = new BehaviorSubject(false);

  constructor(
    private router: Router,
    private googlePlus: GooglePlus) {

  }

public isAuthenticated() {
    return this.authenticationState.value;
}

public logout(): Promise<void> {
    this.authenticationState.next(false);   
    return this.googlePlus.disconnect()
    .then(msg => {
      console.log('User logged out: ' + msg);
    }, err => {
      console.log('User already disconected');
    }); 
}

/**
* Performs the login
*/
public async login(): Promise<any> {
    return this.openGoogleConsentScreen().then(async (user) => {
      console.log(' ServerAuth Code: ' + user.serverAuthCode);
      user.updated = false;
      await this.setData(AuthenticationService.AUTH_INFO_GOOGLE, JSON.stringify(user));
      this.authenticationState.next(true);
      // Do more staff after successfully login
    }, err => {
        this.authenticationState.next(false);
        console.log('An error ocurred in the login process: ' + err);
        console.log(err);
    });

}

  /**
   * Gets the Authentication Token
   */
public async getAuthenticationToken(): Promise<string> {
      return this.getAuthInfoGoogle()
        .then(auth => {
          if (this.isTokenExpired(auth)) {
            return this.refreshToken(auth);
          } else {
            return 'Bearer ' + auth.accessToken;
          }
        });
}



private async openGoogleConsentScreen(): Promise<any> {
  return this.googlePlus.login({
    // optional, space-separated list of scopes, If not included or empty, defaults to `profile` and `email`.
    'scopes': 'profile email openid',
    'webClientId': AuthenticationService.CLIENT_ID,
    'offline': true
  });
}

private isTokenExpired(auth: any): Boolean {
    const expiresIn = auth.expires - (Date.now() / 1000);
     const extraSeconds = 60 * 59 + 1;
    // const extraSeconds = 0;
    const newExpiration = expiresIn - extraSeconds;
     console.log('Token expires in ' + newExpiration + ' seconds. Added ' + extraSeconds + ' seconds for debugging purpouses');
    return newExpiration < 0;
}

private async refreshToken(auth: any): Promise<any> {
      console.log('The authentication token has expired. Calling for renewing');
      if (auth.updated) {
        auth = await this.requestGoogleRefreshToken(auth.serverAuthCode, auth.userId, auth.email);
      } else {
        auth = await this.requestGoogleAuthorizationCode(auth.serverAuthCode, auth.userId, auth.email);
      }
      await this.setData(AuthenticationService.AUTH_INFO_GOOGLE, JSON.stringify(auth));
      return 'Bearer ' + auth.accessToken;
}


private getAuthInfoGoogle(): Promise<any> {
    return this.getData(AuthenticationService.AUTH_INFO_GOOGLE)
    .then(oauthInfo => {
      return JSON.parse(oauthInfo);
    }, err => {
      this.clearStorage();
      throw err;
    });
}

private async requestGoogleAuthorizationCode(serverAuthCode: string, userId: string, email: string): Promise<any> {
    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/x-www-form-urlencoded');
    let params: HttpParams = new HttpParams();
    params = params.set('code', serverAuthCode);
    params = params.set('client_id', AuthenticationService.CLIENT_ID);
    params = params.set('client_secret', AuthenticationService.CLIENT_SECRET);
    params = params.set('grant_type', 'authorization_code');
    const options = {
      headers: headers,
      params: params
    };
    const url = 'https://oauth2.googleapis.com/token';
    const renewalTokenRequestPromise: Promise<any> = this.http.post(url, {}, options).toPromise()
      .then((response: any) => {
        const auth: any = {};
        auth.accessToken = response.access_token;
        console.log('RefreshToken: ' + response.refresh_token);
        auth.serverAuthCode = response.refresh_token;
        auth.expires = Date.now() / 1000 + response.expires_in;
        auth.userId = userId;
        auth.email = email;
        auth.updated = true;
        return auth;
      }, (error) => {
        console.error('Error renewing the authorization code: ' + JSON.stringify(error));
        return {};
      });
    return await renewalTokenRequestPromise;
}

private async requestGoogleRefreshToken(serverAuthCode: string, userId: string, email: string): Promise<any> {
    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/x-www-form-urlencoded');
    let params: HttpParams = new HttpParams();
    params = params.set('refresh_token', serverAuthCode);
    params = params.set('client_id', AuthenticationService.CLIENT_ID);
    params = params.set('client_secret', AuthenticationService.CLIENT_SECRET);
    params = params.set('grant_type', 'refresh_token');
    const options = {
      headers: headers,
      params: params
    };
    const url = 'https://oauth2.googleapis.com/token';
    const renewalTokenRequestPromise: Promise<any> = this.http.post(url, {}, options).toPromise()
      .then((response: any) => {
        const auth: any = {};
        auth.accessToken = response.access_token;
        console.log('RefreshToken: ' + serverAuthCode);
        auth.serverAuthCode = serverAuthCode;
        auth.expires = Date.now() / 1000 + response.expires_in;
        auth.userId = userId;
        auth.email = email;
        auth.updated = true;
        return auth;
      }, (error) => {
        console.error('Error renewing refresh token: ' + JSON.stringify(error));
        return {};
      });
    return await renewalTokenRequestPromise;
}

private setData(key: string, value: any): Promise<any> {
    console.log('Store the value at key entry in the DDBB, Cookies, LocalStorage, etc')
}

private getData(key: string): Promise<string> {
    console.log('Retrieve the value from the key entry from DDBB, Cookies, LocalStorage, etc')
}

private clearStorage(): Promise<string> {
    console.log('Remove entries from DDBB, Cookies, LocalStorage, etc related to authentication')
}



}
票数 4
EN

Stack Overflow用户

发布于 2021-08-25 06:35:51

在我的例子中,这是相当愚蠢的: google更改请求之间的auth代码编码。

步骤1-在获取令牌的第一个请求中,google返回非常正常的字符串,而不是编码的字符串作为代码。

步骤2-在获取令牌的第二次和第N次请求(如果没有被撤销)期间,google返回以url编码的auth代码。在我的例子中,杀死的更改是'/‘-> '%2F’。

解决方案:始终是URL-在交换访问令牌之前对auth代码进行解码!

票数 9
EN

Stack Overflow用户

发布于 2022-02-20 14:35:01

这是授权授予流。为了保持简单,它遵循。我请求访问令牌的web应用程序。在我的例子中,杀死的更改是'%2F‘到'/’。这应该能行

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58209700

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档