【问题标题】:How to get Linkedin access token in iOS to call API?如何在 iOS 中获取 Linkedin 访问令牌以调用 API?
【发布时间】:2013-10-11 22:29:42
【问题描述】:

我有一个 REST API,它允许客户端使用 Linkedin 登录,并传递来自 Linkedin 的访问令牌。

我通过从Javascript API 获取访问令牌并发送登录来创建此服务,然后 api 调用 LinkedIn API 来检索用户数据。这工作正常,但我们在使用 iOS 生成的访问令牌时遇到了问题。

我们使用LinkedIn OAuth Sample Client 在移动设备上登录领英,然后获得访问令牌。使用该访问令牌,我们的 API 无法调用 LinkedIn。

我的问题是:这是在 API 中使用 LinkedIn API 的正确方法吗?而且,如果是,我如何在 iOS 集成中生成正确的访问令牌到我的 API 可以使用它?

【问题讨论】:

    标签: ios api rest oauth linkedin


    【解决方案1】:

    您需要遵循简单的步骤。
    1.您需要向LinkedIn申请用户授权。 (此处将收到authorisation code 作为回复。)
    2. 使用授权码,您需要使用上面收到的authorisation code 向linkedIn 发出POST 请求。

    ViewDidLoad

    -(void)viewDidLoad  
    {  
    #warning:- Please provide your clientID and clientSecret
    linkedInKey = @"YOUR_CLIENT_ID_HERE";
    linkedInSecret = @"YOUR_CLIENT_SECRET_HERE";
    authorizationEndPoint = @"https://www.linkedin.com/uas/oauth2/authorization";
    accessTokenEndPoint = @"https://www.linkedin.com/uas/oauth2/accessToken";  
    #warning:- Please provide your redirectUrl here.
    NSString *redirectURL = @"http://REDIRECT_URL_THAT_YOU_HAVE_PROVIDED_WHILE_REGISTERING_YOUR_APP";
    encodedRdirectURL = [redirectURL stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.alphanumericCharacterSet];
    _webView.delegate = self;
    [self startAuthorisation];
    }
    
    -(void)startAuthorisation
    {
    // Specify the response type which should always be "code".
    NSString *responseType = @"code";
    // Create a random string
    NSString *state = @"anyRandomString";
    // Set preferred scope. It depends on your preference.
    NSString *scope = @"w_share";
    // Create the authorization URL string.
    NSString *authorizationURL = [NSString stringWithFormat:@"%@?response_type=%@&client_id=%@&redirect_uri=%@&state=%@&scope=%@",authorizationEndPoint,responseType,linkedInKey,encodedRdirectURL,state,scope];
    
    NSLog(@"%@",authorizationURL);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:authorizationURL]];
    [_webView loadRequest:request];
    }
    
    #pragma mark- WebView Delegate.
    
    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
    {
    NSURL *url = request.URL;
    //here we will catch the response of the server which will redirect to our redirect url. Hence we first check for the host(which is our redirect url) then only extract the code.  
    #warning:- Please provide your redirectUrl here.
    if ([url.host isEqualToString:@"www.Your_redirect_url.com"])
    {
        if ([url.absoluteString rangeOfString:@"code"].length)
        {
    
    //response containing the authorisation code looks somehow like below.
        //http://www.Your_redirect_url.com?<strong>code=AQSetQ252oOM237XeXvUreC1tgnjR-VC1djehRxEUbyZ-sS11vYe0r0JyRbe9PGois7Xf42g91cnUOE5mAEKU1jpjogEUNynRswyjg2I3JG_pffOClk</strong>&state=linkedin1450703646
    
       //......obtaining the code from the response......//
            NSArray *urlParts = [url.absoluteString componentsSeparatedByString:@"?"];
            NSString *codePart = [urlParts objectAtIndex:1];
            NSArray *codeParts = [codePart componentsSeparatedByString:@"="];
            NSString *code = [codeParts objectAtIndex:1];
            [self requestforAccessToken:code];
        }
    }
    return YES;
    }
    
    - (void)requestforAccessToken:(NSString *)authorisationCode
    {
    NSString *grantType = @"authorization_code";
    NSString *postParameter = [NSString stringWithFormat:@"grant_type=%@&code=%@&redirect_uri=%@&client_id=%@&client_secret=%@",grantType,authorisationCode,encodedRdirectURL,linkedInKey,linkedInSecret];
    NSData *postdata = [postParameter dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:accessTokenEndPoint]];
    request.HTTPMethod = @"POST";
    request.HTTPBody = postdata;
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    
    manager.responseSerializer = [AFJSONResponseSerializer
                                  serializerWithReadingOptions:NSJSONReadingAllowFragments];
    
    
    [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse  * response, id  responseObject, NSError * error )
      {
          if (!error)
          {
              NSLog(@"Reply JSON: %@", responseObject);
              NSString *accessToken = [responseObject objectForKey:@"access_token"];
              NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
              [defaults setObject:accessToken forKey:@"linkedInAccessToken"];
              [defaults synchronize];
          }
    
      }] resume];
    
    }  
    

    我在这里使用了 AFNetworking 库。因此,请从 gitHub 获取库并将其添加到您的项目中。为此,您需要在 viewController 中导入 AFHTTPSessionManager.h

    #warning:- please declare these following strings as global variable under interface as.  
    @interface WebViewController ()<UIWebViewDelegate>  
    {
    NSString *linkedInKey;
    NSString *linkedInSecret;
    NSString *authorizationEndPoint;
    NSString *accessTokenEndPoint;
    NSString *encodedRdirectURL;    
    }
    

    我还拿了一个UIWebView 并用名称为webViewIBOutlet 连接到它,你可以在上面的代码中找到它。

    别忘了确认 UIWebViewDelegate。

    希望这会有所帮助。
    祝你好运。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-07
      • 2021-03-30
      • 1970-01-01
      • 2012-04-09
      • 2020-02-29
      • 2012-09-26
      • 2021-05-07
      相关资源
      最近更新 更多