GTM OAuth不会下载刷新令牌-iOS [英] GTM OAuth does not download Refresh Token - iOS

查看:92
本文介绍了GTM OAuth不会下载刷新令牌-iOS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google的iOS / Mac SDK GTMOAuth,以便能够与YouTube API和Instagram API之类的APIS连接。一切正常,但是当用户进行身份验证时,我只能获得访问令牌。一切都很好,但是一段时间后,访问令牌过期,用户必须重新登录,这很糟糕。

I am using Google's GTMOAuth for iOS/Mac SDK in order to be able to connect with APIS such as YouTube API and Instagram API. It all works fine, however when the user authenticates, I can only get access token. This is all well and good, but after a while the access tokens expire and the user has to re-login which is awful.

我的问题是,当用户进行身份验证时,我只能取回访问令牌,而没有其他任何东西...

My problem is that when the user authenticates, I ONLY GET back an access token and nothing else...

感谢您的帮助:)

推荐答案

可能是这个帮助您..!

May be this one help you..!

我正在使用Google oauth 2.0进行Google驱动器身份验证。

I am using Google oauth 2.0, for google drive authentication.

在Google完成身份验证方法后,保存accesstoken和刷新令牌值

In the Google finished with authentication method save the accesstoken and refresh token values in NSUSerDefaults like this.

 - (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController finishedWithAuth:(GTMOAuth2Authentication *)authResult

           error:(NSError *)error
    {

        if (error != nil)
        {

          [self showAlert:@"Authentication Error" message:error.localizedDescription];

            self.driveService.authorizer = nil;

        }
        else
        {
            self.driveService.authorizer = authResult;

            self.auth = authResult;

            NSLog(@"\n accessToken value is %@",self.auth.accessToken);

            [[NSUserDefaults standardUserDefaults] setValue:self.auth.refreshToken forKey:@"refreshToken"];

            [[NSUserDefaults standardUserDefaults] setValue:self.auth.accessToken forKey:@"accessToken"];

            [[NSUserDefaults standardUserDefaults] synchronize];


        }

    }

之后,无论何时要使用acces令牌执行api调用,都请先使用NSUSERDefaults中的现有accesstoken值进行调用,然后在URL响应中检查状态代码。如果您收到状态码 401,则表示您的访问令牌已过期,并且无效。然后,您必须使用这样保存在NSUserDefaults中的刷新令牌值来请求刷新令牌。

After that when ever you want to use the acces token for performing api call first make a call using existing accesstoken value from the NSUSERDefaults, after that in the url response check the status code. If you are getting status code '401' means your access token is expired, and not valid. Then you have to request for refresh token using saved refresh token value in NSUserDefaults like this.

这是您的第一个api调用,用于检查访问令牌是否有效。

This is your first api call to check accesstoken valid or not.

    - (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
    {
        NSLog(@"Did Receive Response %@", response);
        NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
        //int responseStatusCode = [httpResponse statusCode];
        if (httpResponse.statusCode == 200) {
//Your api call success and accesstoken is valid.


        } else if(httpResponse.statusCode == 401 && connection == self.conn2) {

            [[self appDelegate] refreshAccessToken];
        } 
    }

这是从刷新令牌中请求新的访问令牌。 / p>

This is for request new accesstoken from refresh token.

-(void)refreshAccessToken {


    NSString *requestString = [NSString stringWithFormat:@"https://accounts.google.com/o/oauth2/token"];
        NSString *string = [NSString stringWithFormat:@"client_id=%@&client_secret=%@&refresh_token=%@&grant_type=refresh_token",kClientID,kClientSecret,[[NSUserDefaults standardUserDefaults] valueForKey:@"refreshToken"]];
    NSData *postData = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestString]];
    NSLog(@"\n request str : %@",request);

    NSLog(@"\n refresh token value is %@",[[NSUserDefaults standardUserDefaults] valueForKey:@"refreshToken"]);
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];//connectionWithRequest:request delegate:self];
    if(connection)
    {
        NSLog(@"Connection Successful");
    }
    else
    {
        NSLog(@"Connection could not be made");
    }

    [connection start];


}

作为响应,再次检查状态码,然后如果状态码为200,则更新用户错误中的值。

In response check for status code again and if status code is 200.Then update the value in userdafaults.

- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"Did Receive Response %@", response);
    //NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
    self.data = [NSMutableData data];
}

- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
    NSLog(@"Did Receive Data %@", data);
    [self.data appendData:data];
}

- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
    NSLog(@"Did Fail %@",error);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Did Finish");
    // Do something with responseData
    NSError *err;
    id JSon = [NSJSONSerialization JSONObjectWithData:self.data options:kNilOptions error:&err];
    if (err) {
        NSLog(@"%@",err);
    }
    else {
        NSLog(@"Json %@",JSon);
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"accessToken"];
        [[NSUserDefaults standardUserDefaults] setObject:[JSon valueForKey:@"access_token"] forKey:@"accessToken"];
        [[NSUserDefaults standardUserDefaults] synchronize];

    }
}

这是我在堆栈上的第一个答案溢出。抱歉,有任何错误。

This is my first answer on stack overflow. Sorry for any mistakes.

更新如下-由Supertecnoboff撰写

这一点。对于某些API(例如Google),如果您想为其提供刷新令牌,则需要添加 approval_prompt = force和 access_type = offline。为了添加这些参数,您必须编辑GTMOAuth2SignIn.m文件,并用此NSMutableDictionary替换 paramsDict:

Also keep this in mind. For some API's such as Google, you need to add "approval_prompt=force" and "access_type=offline" if you want it to give you a refresh token. In order to add these parameters, you have to edit the GTMOAuth2SignIn.m file and replace the "paramsDict" with this NSMutableDictionary:

NSMutableDictionary *paramsDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                 @"code", @"response_type",
                                 clientID, @"client_id",
                                 scope, @"scope", // scope may be nil
                                 @"force", @"approval_prompt",
                                 @"offline", @"access_type",
                                 nil];

这篇关于GTM OAuth不会下载刷新令牌-iOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆