How can i implement GTMOAuth in iOS - iphone

i need to implement GTMOAuth to my iOS app..for this i have downloaded the OAuth Library and write some code
- (GTMOAuthAuthentication *)myCustomAuth {
NSString *myConsumerKey = #"f964039f2d7bc82054"; // pre-registered with service
NSString *myConsumerSecret = #"c9a749c0f1e30c9246a3be7b2586434f"; // pre-assigned by service
GTMOAuthAuthentication *auth;
auth = [[[GTMOAuthAuthentication alloc] initWithSignatureMethod:kGTMOAuthSignatureMethodHMAC_SHA1
consumerKey:myConsumerKey
privateKey:myConsumerSecret] autorelease];
// setting the service name lets us inspect the auth object later to know
// what service it is for
auth.serviceProvider = #"Custom Auth Service";
return auth;
}
- (void)signInToCustomService {
NSURL *requestURL = [NSURL URLWithString:#"http://alpha.easyreceipts.com/api/v1/oauth/request_token"];
NSURL *accessURL = [NSURL URLWithString:#"http://alpha.easyreceipts.com/api/v1/oauth/access_token"];
NSURL *authorizeURL = [NSURL URLWithString:#"http://alpha.easyreceipts.com/api/v1/oauth/authorize"];
NSString *scope = #"http://alpha.easyreceipts.com/api/v1/";
GTMOAuthAuthentication *auth = [self myCustomAuth];
// set the callback URL to which the site should redirect, and for which
// the OAuth controller should look to determine when sign-in has
// finished or been canceled
//
// This URL does not need to be for an actual web page
[auth setCallback:#"http://alpha.easyreceipts.com/api/v1/"];
// Display the autentication view
GTMOAuthViewControllerTouch *viewController;
viewController = [[[GTMOAuthViewControllerTouch alloc] initWithScope:scope
language:nil
requestTokenURL:requestURL
authorizeTokenURL:authorizeURL
accessTokenURL:accessURL
authentication:auth
appServiceName:#"My App: Custom Service"
delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)] autorelease];
viewController = [self.storyboard instantiateViewControllerWithIdentifier:#"myID"];
[[self navigationController] pushViewController:viewController
animated:YES];
}
but further i don't know how to implement it.Please help me Thanks in advance

First, if you want to implement an OAuth authentication system with the GTM library, you should get this one.
You can find the complete sources of GTMOAuth here.
Secondly, you can find an example of how to use it in the git repository too. You should find everything you need to at least authenticate.
If you have any more problem, please provide more informations.

Related

iPhone:Error occurs while uploading image on twitter using sharekit

I am using sharekit to upload the image on twitter.
I have set keys and callback URL perfectly.
But after entering my login and password credentials
to upload image on twitter I got following error message.
"There was a problem requesting access from Twitter."
Earlier before few months in the same app I was able to upload
the image with same code.
But right now I am facing the problem
can you tell me what is the exact problem
thanks in advance.
There is some changes occur in share kit. To resolve this issue. You have to change some piece of lines in SHKTwitter.mfile under this method:
- (void)tokenAccessModifyRequest:(OAMutableURLRequest *)oRequest
For detail info follow this link & make changes according to this link & then check:
https://github.com/SteveLeviathan/ShareKit/commit/7aab77655c1cbb1bf79092fcb3bb24dd80ab6380
UPDATE:
Replace your this method with my & then check:
- (void)tokenAccessModifyRequest:(OAMutableURLRequest *)oRequest
{
if (xAuth)
{
NSDictionary *formValues = [pendingForm formValues];
OARequestParameter *username = [[[OARequestParameter alloc] initWithName:#"x_auth_username"
value:[formValues objectForKey:#"username"]] autorelease];
OARequestParameter *password = [[[OARequestParameter alloc] initWithName:#"x_auth_password"
value:[formValues objectForKey:#"password"]] autorelease];
OARequestParameter *mode = [[[OARequestParameter alloc] initWithName:#"x_auth_mode"
value:#"client_auth"] autorelease];
[oRequest setParameters:[NSArray arrayWithObjects:username, password, mode, nil]];
}
else {
if (self.pendingAction == SHKPendingRefreshToken)
{
if (accessToken.sessionHandle != nil)
[oRequest setOAuthParameterName:#"oauth_session_handle" withValue:accessToken.sessionHandle];
}
else
[oRequest setOAuthParameterName:#"oauth_verifier" withValue:[authorizeResponseQueryVars objectForKey:#"oauth_verifier"]];
}
}
You can switch to ShareKit 2 - it is being updated frequently.

GTM OAuth2 retrieving access_token via Keychain not successful

I'm following Google's examples on how to authorize an app to access one or more APIs.
The problem is that when i authorise successfully i get the access_token, but after this i can't get it from the keychain it is stored into. I read somewhere that iPhone Simulator doesn't work with Keychain, is it because of that, and if it is can you tell me some other way to store my access token?
Here is my code:
static NSString *const kKeychainItemName = #"OAuthGoogleReader";
GTMOAuth2Authentication *auth;
auth = [GTMOAuth2ViewControllerTouch authForGoogleFromKeychainForName:kKeychainItemName
clientID:kClientID
clientSecret:kClientSecret];
BOOL isSignedIn = [auth canAuthorize];
if (isSignedIn) {
NSLog(#"Signed");
self.window.rootViewController = self.viewController;
auth.accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"accessToken"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://www.google.com/reader/api/0/subscription/list?access_token=%#", [auth accessToken]]]];
GTMHTTPFetcher* myFetcher = [GTMHTTPFetcher fetcherWithRequest:request];
// optional upload body data
//[myFetcher setPostData:[postString dataUsingEncoding:NSUTF8StringEncoding]];
[myFetcher setAuthorizer:auth];
[myFetcher beginFetchWithDelegate:self
didFinishSelector:#selector(myFetcher:finishedWithData:error:)];
// - (void)myFetcher:(GTMHTTPFetcher *)fetcher finishedWithData:(NSData *)retrievedData error:(NSError *)error;
}else{
NSString *scope = #"https://www.google.com/reader/api/";
GTMOAuth2ViewControllerTouch *viewController;
viewController = [[GTMOAuth2ViewControllerTouch alloc] initWithScope:scope
clientID:kClientID
clientSecret:kClientSecret
keychainItemName:kKeychainItemName
delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)];
self.window.rootViewController = viewController;
}
I get error:
2012-08-22 16:54:47.253 greader[20833:c07] Signed
2012-08-22 16:54:47.705 greader[20833:c07] Cannot authorize request with scheme http (<NSMutableURLRequest http://www.google.com/reader/api/0/subscription/list?access_token=(null)>)
as you can see access_token is just nil.
Also some simple examples on how to use this library would be great.
Thank you!
The gtm-oauth2 library handles storing and retrieving the access token and other auth values on the keychain. The app should not need to use the access token string directly, nor should the app put the authorization tokens into NSUserDefaults, as that is insufficiently secure.
gtm-auth2 also by default will refuse to attach an access token to a URL with an http: scheme. OAuth 2 is secure only when used with https: scheme URLs.

How To Use OAuth in My iPhone App?

I'm trying to configure OAuth into my iPhone app to connect to another web service but I'm having problems with it.
I have downloaded the google gtm-oauth files and added them to my project.
- (GTMOAuthAuthentication *)myCustomAuth {
NSString *myConsumerKey = #"2342343242"; // pre-registered with service
NSString *myConsumerSecret = #"324234234242"; // pre-assigned by service
GTMOAuthAuthentication *auth;
auth = [[[GTMOAuthAuthentication alloc] initWithSignatureMethod:kGTMOAuthSignatureMethodHMAC_SHA1
consumerKey:myConsumerKey
privateKey:myConsumerSecret] autorelease];
// setting the service name lets us inspect the auth object later to know
// what service it is for
auth.serviceProvider = #"RunKeeper";
return auth;
}
- (void)signInToCustomService {
NSURL *requestURL = [NSURL URLWithString:#"https://runkeeper.com/apps/token"];
NSURL *accessURL = [NSURL URLWithString:#"https://runkeeper.com/apps/token"];
NSURL *authorizeURL = [NSURL URLWithString:#"https://runkeeper.com/apps/authorize"];
NSString *scope = #"http://example.com/scope";
GTMOAuthAuthentication *auth = [self myCustomAuth];
// set the callback URL to which the site should redirect, and for which
// the OAuth controller should look to determine when sign-in has
// finished or been canceled
//
// This URL does not need to be for an actual web page
[auth setCallback:#"http://www.example.com/OAuthCallback"];
// Display the autentication view
GTMOAuthViewControllerTouch *viewController;
viewController = [[[GTMOAuthViewControllerTouch alloc] initWithScope:scope
language:nil
requestTokenURL:requestURL
authorizeTokenURL:authorizeURL
accessTokenURL:accessURL
authentication:auth
appServiceName:#"RunKeeper"
delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)] autorelease];
[[self navigationController] pushViewController:viewController
animated:YES];
}
This is the API I am trying to connect with: http://developer.runkeeper.com/healthgraph/registration-authorization
First, read up on oauth. it's a bit different from your normal login/pw type auth.
Second, you can use Google's oauth library at http://code.google.com/p/gtm-oauth/

Using tweet search with Twitter+OAuth on iPhone

Originally I needed the ability to use the search API with twitter. I did this using Matt Gemmell's great MGTwitterEngine. That code was very very simple and looked something like this:
- (void)viewDidLoad {
[super viewDidLoad];
tweetArrays = nil;
tweetNameArray = nil;
NSString *username = #"<username>";
NSString *password = #"<password>";
NSString *consumerKey = #"<consumerKey>";
NSString *consumerSecret = #"<consumerSecret>";
// Most API calls require a name and password to be set...
if (! username || ! password || !consumerKey || !consumerSecret) {
NSLog(#"You forgot to specify your username/password/key/secret in AppController.m, things might not work!");
NSLog(#"And if things are mysteriously working without the username/password, it's because NSURLConnection is using a session cookie from another connection.");
}
// Create a TwitterEngine and set our login details.
twitterEngine = [[MGTwitterEngine alloc] initWithDelegate:self];
[twitterEngine setUsesSecureConnection:NO];
[twitterEngine setConsumerKey:consumerKey secret:consumerSecret];
// This has been undepreciated for the purposes of dealing with Lists.
// At present the list API calls require you to specify a user that owns the list.
[twitterEngine setUsername:username];
[twitterEngine getSearchResultsForQuery:#"#HelloWorld" sinceID:0 startingAtPage:1 count:100];
}
This would end up calling the function:
- (void)searchResultsReceived:(NSArray *)searchResults forRequest:(NSString *)connectionIdentifier
And then I could do what I wanted with the searchResults. This required me to include the yajl library.
I then wanted to expand my code to allow users to tweet. I downloaded Ben Gottlieb's great code Twitter-OAuth-iPhone
So there's only one problem. The getSearchResultsForQuery returns a requestFailed with the following error:
Error Domain=HTTP Code=400 "The operation couldn’t be completed. (HTTP error 400.)"
To call this code I simply took the demo project in Twitter-OAuth-iPhone and added a call to getSearchResultsForQuery as seen here:
- (void) viewDidAppear: (BOOL)animated {
if (_engine) return;
_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate: self];
_engine.consumerKey = kOAuthConsumerKey;
_engine.consumerSecret = kOAuthConsumerSecret;
UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine: _engine delegate: self];
if (controller)
[self presentModalViewController: controller animated: YES];
else {
[_engine getSearchResultsForQuery:#"HelloWorld"];
// [_engine sendUpdate: [NSString stringWithFormat: #"Already Updated. %#", [NSDate date]]];
}
}
This as stated above returns a 400 error. Every other twitter API call I add here does work such as:
- (NSString *)getRepliesStartingAtPage:(int)pageNum;
Am I doing anything wrong? Or does getSearchResultsForQuery no longer work? The two code bases seem to use different versions of MGTwitterEngine, could that be causing the problem?
Thanks!
The problem is that you have to instantiate the twitter engine as an instance of SA_OAuthTwitterEngine, instead of MGTwitterEngine. When you call getSearchResultsForQuery, it uses a call to _sendRequestWithMethod to actually send the search request. SA_OAuthTwitterEngine overrides the MGTwitterEngine's implementation, but its version of that function doesn't work with getSearchResultsForQuery.
So, you need to go to getSearchResultsForQuery and make it use the MGTwitterEngine's version of the function.

Twitter + oAuth nightmare

I'm trying to implement a custom login view to Twitter (I don't want that UIWebView).
I've downloaded many classes, and I'm so far having a nightmare with this. Now I'm trying to make Twitter + oAuth work. Here's the demo code (that works):
_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate: self];
_engine.consumerKey = kOAuthConsumerKey;
_engine.consumerSecret = kOAuthConsumerSecret;
[_engine requestRequestToken];
UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine: _engine delegate: self];
if (controller)
[self presentModalViewController: controller animated: YES];
else
[_engine sendUpdate: [NSString stringWithFormat: #"Already Updated. %#", [NSDate date]]];
Now what I wanna do is replace that SA_OAuthTwitterController with custom UITextFields. So I'm trying this:
_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate: self];
_engine.consumerKey = kOAuthConsumerKey;
_engine.consumerSecret = kOAuthConsumerSecret;
[_engine requestRequestToken];
[_engine requestAccessToken];
[_engine setUsername:#"username" password:#"password"];
[_engine sendUpdate:#"tweet"];
But I keep getting error 401. I'm probably missing a step. Anyone?
The view controller you are eliminating loads a webview that prompts the user to authenticate your application with twitter. If you don't ever have the user authenticate, you won't be able to make authenticated twitter calls. There is a way to do what you are wanting, however, you have to go through all of the OAuth steps yourself. Here are the steps as specified from a different web service (Vimeo), but the same rules apply:
Your application sends a request
with your consumer key, and signed
with your consumer secret, for a
something called a request token. If
we verify your application
correctly, we'll send you back a
request token and a token secret.
You'll then create a link for the user to click on with the request token.
When the user gets to Vimeo, they'll be prompted to allow your
application access to their account.
If they click yes, we'll send them
back to your application, along with
a verifier.
You'll then use the request token, verifier, and token secret to make
another call to us to get an access
token. The access token is what
you'll use to access the user's
information on Vimeo.
OAuth is a real pain in the rump, so good luck. ;-)
I think the bit you're missing is here, SA_OAuthTwitterEngine.m:103:
//This generates a URL request that can be passed to a UIWebView. It will open a page in which the user must enter their Twitter creds to validate
- (NSURLRequest *) authorizeURLRequest {
if (!_requestToken.key && _requestToken.secret) return nil; // we need a valid request token to generate the URL
OAMutableURLRequest *request = [[[OAMutableURLRequest alloc] initWithURL: self.authorizeURL consumer: nil token: _requestToken realm: nil signatureProvider: nil] autorelease];
[request setParameters: [NSArray arrayWithObject: [[[OARequestParameter alloc] initWithName: #"oauth_token" value: _requestToken.key] autorelease]]];
return request;
}
You will have to "fake" this user login out yourself, I believe by sending twitter the login credentials as a separate request. It appears that the setUsername method you're calling is actually called as a post operation once a valid access token has been received. See SA_OAuthTwitterEngine.m:185
//
// access token callback
// when twitter sends us an access token this callback will fire
// we store it in our ivar as well as writing it to the keychain
//
- (void) setAccessToken: (OAServiceTicket *) ticket withData: (NSData *) data {
if (!ticket.didSucceed || !data) return;
NSString *dataString = [[[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding] autorelease];
if (!dataString) return;
if (self.pin.length && [dataString rangeOfString: #"oauth_verifier"].location == NSNotFound) dataString = [dataString stringByAppendingFormat: #"&oauth_verifier=%#", self.pin];
NSString *username = [self extractUsernameFromHTTPBody:dataString];
if (username.length > 0) {
[[self class] setUsername: username password: nil];
if ([_delegate respondsToSelector: #selector(storeCachedTwitterOAuthData:forUsername:)]) [(id) _delegate storeCachedTwitterOAuthData: dataString forUsername: username];
}
[_accessToken release];
_accessToken = [[OAToken alloc] initWithHTTPResponseBody:dataString];
}
So the steps are as follows:
Request request token
Fake user login to twitter and get the pin value
Set the pin on the engine
Request access token
You can see where SA_OAuthTwitterController parses the pin out of the webview content in SA_OAuthTwitterController.m:156
#pragma mark Webview Delegate stuff
- (void) webViewDidFinishLoad: (UIWebView *) webView {
NSError *error;
NSString *path = [[NSBundle mainBundle] pathForResource: #"jQueryInject" ofType: #"txt"];
NSString *dataSource = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
if (dataSource == nil) {
NSLog(#"An error occured while processing the jQueryInject file");
}
[_webView stringByEvaluatingJavaScriptFromString:dataSource]; //This line injects the jQuery to make it look better
NSString *authPin = [[_webView stringByEvaluatingJavaScriptFromString: #"document.getElementById('oauth_pin').innerHTML"] stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (authPin.length == 0) authPin = [[_webView stringByEvaluatingJavaScriptFromString: #"document.getElementById('oauth_pin').getElementsByTagName('a')[0].innerHTML"] stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
[_activityIndicator stopAnimating];
if (authPin.length) {
[self gotPin: authPin];
}
if ([_webView isLoading] || authPin.length) {
[_webView setHidden:YES];
} else {
[_webView setHidden:NO];
}
}
hope this helps.
You have to use xAuth for custom user/pass controls. But it requires the permission from Twitter.