2013-10-04 146 views
2

我有一個REST API,允許客戶端使用Linkedin從Linkedin傳遞訪問令牌。如何在iOS中獲取Linkedin訪問令牌以調用API?

我通過從Javascript API獲取訪問令牌併發送登錄,而不是通過API調用LinkedIn API來檢索用戶數據,從而創建了此服務。這工作正常,但我們遇到了iOS生成的訪問令牌的問題。

我們使用LinkedIn OAuth Sample Client在移動設備上登錄LinkedIn,並獲取訪問令牌。使用該訪問令牌,我們的API不能調用LinkedIn。

我的問題是:這是在API內使用LinkedIn API的正確方法嗎?而且,如果是這樣,我怎麼才能在iOS中集成正確的訪問令牌給我的API使用呢?

回答

2

你需要遵循簡單的步驟。
1.您需要向LinkedIn申請授權用戶。 (將會收到一個authorisation code作爲迴應。)
2.使用授權碼,您需要向linkedIn發送POST請求,上面收到authorisation code

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並連接到它與IBOutlet的名稱webView,你可以在上面的代碼中找到它。

不要忘記確認UIWebViewDelegate。

希望這會有所幫助。
祝你好運。

相關問題