vimeo oAth authentication through iPhone app - ipad

I have an iPad app and need to integrate vimeo to it. I'm in the initial stages of integrating it to my app. I first need to authenticate my app through vimeo.
I've gone through the steps for authentication in documentation and I'm able to pass through first 2 steps:
Request Token:
http://vimeo.com/oauth/request_token
User Authorization:
http://vimeo.com/oauth/authorize
But unable to get oauth_token and oauth_token_secret through last step:
Access Token:
http://vimeo.com/oauth/access_token
Vimeo redirects to callback url instead of going back to the app which is fine until I get verifier and authorization token. But once I use these to get oauth_token and oauth_token_secret, console shows following error message:
Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed.
(NSURLErrorDomain error -1012.)" UserInfo=0x18146180 {
NSErrorFailingURLKey=http://vimeo.com/oauth/access_token?oauth_token=141b4ff56c48dc5d03501297bde85ebc&oauth_verifier=land-1886924229,
NSErrorFailingURLStringKey=http://vimeo.com/oauth/access_token?oauth_token=141b4ff56c48dc5d03501297bde85ebc&oauth_verifier=land-1886924229,
NSUnderlyingError=0x181483d0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1012.)"
}
Can anyone please help or atleast provide some directions?
To further give an insight, I'm using OAuthConsumer framework. Below are the lines of code where we place request to get an access token:
- (void)successfulAuthorizationWithToken:(NSString *)token verifier:(NSString *)verifier {
NSLog(#"successfulAuthorizationWithToken");
OAMutableURLRequest *request;
OADataFetcher *fetcher;
//NSURL *url = [NSURL URLWithString:#"https://api.twitter.com/oauth/access_token"];
NSURL *url = [NSURL URLWithString:#"http://vimeo.com/oauth/access_token"];
request = [[[OAMutableURLRequest alloc] initWithURL:url
consumer:self.consumer
token:self.accessToken
realm:nil
signatureProvider:nil autorelease];
OARequestParameter *p0 = [[OARequestParameter alloc] initWithName:#"oauth_token"
value:token];
OARequestParameter *p1 = [[OARequestParameter alloc] initWithName:#"oauth_verifier"
value:verifier];
NSArray *params = [NSArray arrayWithObjects:p0, p1, nil];
[request setParameters:params];
fetcher = [[[OADataFetcher alloc] init] autorelease];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(accessTokenTicket:didFinishWithData:)
didFailSelector:#selector(accessTokenTicket:didFailWithError:)];
[p0 release];
[p1 release];
}
I've also tried solutions specified in below link:
Twitter API + OAuthConsumer.framework
It says to use [[[OAHMAC_SHA1SignatureProvider alloc] init] autorelease] as signatureProvider. But the results are same.
I need to get following values after I get verifier and authorized token using the access token step:
oauth_token=YourAuthorizedOauthToken&oauth_token_secret=YourAuthorizedTokenSecret

You need to provide your own callback in your request, which looks like myapp://... and register myapp handler in iOS, so that when browser is redirected then iOS will give control back to your app. I'm assuming you are using OAuth properly and start a browser from your app for user interaction. Alternatively you could use a WebView (not what OAuth recommends) then in the WebView delegate you can catch a redirect and parse access toke out.

Finally got it working. There were issues in the base string and oAuth Header string format.

Related

How to fix this error in sending emails by Outh2 using MailCore?

Im using mailcore to for sending mails using access token. This work fine in case of using password but by using access tokens its not working. I have changed every combination of ports and connection types but still getting the same issue. I need some help.
MCOSMTPSession * smtpSession = [[MCOSMTPSession alloc] init];
smtpSession.hostname = #"smtp.gmail.com";
smtpSession.port = 465;
smtpSession.username = user; //saved value
smtpSession.connectionType = MCOConnectionTypeTLS;
smtpSession.OAuth2Token = token; //saved value(Validated)
smtpSession.authType = MCOAuthTypeXOAuth2;
smtpSession.checkCertificateEnabled=NO;
MCOMessageBuilder * builder = [[MCOMessageBuilder alloc] init];
MCOAddress *fromAdress=[[MCOAddress alloc]init];
fromAdress = [MCOAddress addressWithMailbox:user];
MCOAddress *toAdress=[[MCOAddress alloc]init];
toAdress = [MCOAddress addressWithMailbox:self.to.text];
[[builder header] setFrom:fromAdress];
[[builder header] setTo:#[toAdress]];
NSString *htmlbody1=#"Body";
[[builder header] setSubject:#"Some_subject"];
[builder setHTMLBody:htmlbody1];
[smtpSession setConnectionLogger:^(void * connectionID, MCOConnectionLogType type, NSData * data) {
NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Response %#",response);
}];
NSData * rfc822Data = [builder data];
MCOSMTPSendOperation *sendOperation = [smtpSession sendOperationWithData:rfc822Data];
[sendOperation start:^(NSError *error) {
if(error) {
NSLog(#"Error sending email: %#", error);
} else {
}
}];
im getting this response
Response 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/answer/14257 gg7sm1578291wjd.10
and getting this error
Error Domain=MCOErrorDomain Code=5 "Unable to authenticate with the current session's credentials.
It's worth noting that if you want to send emails via Gmail, then you need to either:
Use Oauth (more details, see below)
For users with 2-step verification enabled, have them set up an App password that they then enter in the app
Have users enable the Less Secure Apps option on their account
Using OAuth
For OAuth, you can use a library like GTMAppAuth, which allows you to create an OAuth token to use within your app. However, when doing so, you must make sure to set the scope correctly when requesting access. Here's some code taken from the wiki:
OIDAuthorizationRequest *request =
[[OIDAuthorizationRequest alloc] initWithConfiguration:configuration
clientId:kClientID
clientSecret:kClientSecret
scopes:#[OIDScopeOpenID, OIDScopeProfile]
redirectURL:redirectURI
responseType:OIDResponseTypeCode
additionalParameters:nil];
Sending via SMTP
If you want to use SMTP to send email, then you must add #"https://mail.google.com/" to the scopes` argument.
Note that it seems that in 2022, Google really doesn't want you directly accessing SMTP. If you use the scope #"https://mail.google.com/" in your app, then your app is considered Restricted and it'll need to go through a verification process.
Sending via Google APIs
The alternative is to send via the Google APIs. If you want to do this, then you need the #"https://www.googleapis.com/auth/gmail.send" scope. This will allow you to send email e.g. using the GTLR library.
Notes:
If you try to use the #"https://www.googleapis.com/auth/gmail.send" scope then login via SMTP, you'll get the error Username and Password not accepted. You can't use that scope for SMTP, only for the googleapis.
P.S. Why Google can't better document this, is beyond me. I've just volunteered 20 hours of my time to Google for figuring this out.

LinkedIn Login saves the credentials in iOS

I am using LinkedIn to share the images. I need to login at first time after that it needs to save the LinkedIn credentials in the app. When i run the app next time again LinkedIn Login will display. How can i solve this problem.
I have saved the access token and passing that value, but still i am getting the error message like this "The partner did not properly implement the authentication protocol"
When you fetch the accessToken:
self.accessToken = [[OAToken alloc] initWithHTTPResponseBody:responseBody];
Save it in the user defaults so next time you can use it to avoid re-login:
[[NSUserDefaults standardUserDefaults] setObject:responseBody forKey:#"accessToken"];
Access back the accessToken:
NSString* accessToken = [[NSUserDefaults standardUserDefaults] valueForKeyPath:#"accessToken"];
OAMutableURLRequest *request =[[OAMutableURLRequest alloc] initWithURL:url consumer:self.consumer token:[[OAToken alloc] initWithHTTPResponseBody:accessToken]];

AssumeRole - AWS iOS SDK sample

I am using "AssumeRole" api in iOS AWS sdk to generate temporary security credentials. Can anybody tell the steps for this or give sample app for this?
TSC = [[AmazonSecurityTokenServiceClient alloc]initWithAccessKey:#"XXXXXXXXXXXXXXXX" withSecretKey:#"uuuuuuuuuuuyyyyyyyy" ];
request = [[SecurityTokenServiceAssumeRoleRequest alloc]init ];
request.roleArn = #"arn:aws:iam::0000000000:role/test";
request.roleSessionName = #"test";
request.policy =nil;
request.durationSeconds=[NSNumber numberWithInt:3600];
request.externalId=#"test123";
response = [TSC assumeRole:request];
My doubt is to get temporary credentials, the above code will be enough or do i need call the NSURLConnection delegates explicitly to make the web service call? Thanks.
That code should be enough to get credentials. If the request is successful, the credentials will be available in the response object. (API reference).
You'll need to initialize a AmazonCredentials object to use the returned credentials:
AmazonCredentials *credentials =
[[AmazonCredentials alloc] initWithAccessKey:response.credentials.accessKeyId
withSecretKey:response.credentials.secretAccessKey
withSecurityToken:response.credentials.sessionToken];
AmazonS3Client *s3 = [[AmazonS3Client alloc] initWithCredentials:credentials];

MGTwitterEngine for iOS : how to get accessToken? Error 401

I'm using MGTwitterEngine library for my iOS app to post tweets.
NSString *username = dataBase.twiLog;
NSString *password = dataBase.twiPas;
NSString *consumerKey = cons_key;
NSString *consumerSecret = cons_secret;
// 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.
MGTwitterEngine *twitterEngine = [[MGTwitterEngine alloc] initWithDelegate:self];
twitterEngine setClearsCookies:YES];
[twitterEngine setUsesSecureConnection:NO];
[twitterEngine setConsumerKey:consumerKey secret:consumerSecret];
[twitterEngine setUsername:username password:password];
[twitterEngine sendUpdate: #"This message was sent via myApp for iOS"];
However I can't send tweet until I get accessToken. Here's output:
Request failed for connectionIdentifier = 5E7C9D2E-1467-45EF-B748-CCBF8F211F8D, error = The operation couldn’t be completed. (HTTP error 401.) ({
body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<hash>\n <error>Could not authenticate you.</error>\n <request>/1/statuses/update.xml</request>\n</hash>\n";
response = "<NSHTTPURLResponse: 0x6e26a10>";
})
How can I sent tweet using MGTwitterEngine? (without manually getting my access token from dev.twitter.com because other users should be able to send tweets from themselves too)
I had a similar problem and after many hours of searching I found the solution.
My logout button is showing only when the user is logged in by checking if engine isAuthorized. Then after the user taps the button this is the code which is executed.
- (void)logoutTwitter {
if(![_engine isAuthorized]){
UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine:_engine delegate:self];
if (controller){
[self presentModalViewController: controller animated: YES];
}
} else {
[_engine clearAccessToken]; //This is a method called from SA_OAuthTwitterEngine.h
}

Using Flattr API v2 with iOS

I'm currently building an iOS application and want to include Flattr-Support over the Flattr-API v2.
I've already created my application at https://flattr.com/apps/ and got the key and secret.
The problem is that I have to provide a callback-URL in the application-settings at flattr even if I select "client" as application type. In addition only http://... callback-URLs seem to be allowed in the input field so I can't set a callback URL to open my application (something like myApp://...)
How do I implement the Flattr oAuth process for client applications?
Are there any detailed instructions how to implement the flattr-authentication with a non-web-based / iOS application?
I planned to use the JDG OAuthConsumer library but this doesn't seem to work - any other iOS librarys I could use?
A short description of my implementation using the Flattr API v2 to flattr a thing from my iOS application:
I'm currently using the "Google Toolbox for Mac - OAuth 2 Controllers":
http://code.google.com/p/gtm-oauth2/
Create a Token to be authenticated:
- (GTMOAuth2Authentication *)flattrAuth {
NSURL *tokenURL = [NSURL URLWithString:#"https://flattr.com/oauth/token"];
// We'll make up an arbitrary redirectURI. The controller will watch for
// the server to redirect the web view to this URI, but this URI will not be
// loaded, so it need not be for any actual web page.
NSString *redirectURI = #"http://localhost/"; //for me localhost with / didn't work
GTMOAuth2Authentication *auth;
auth = [GTMOAuth2Authentication authenticationWithServiceProvider:#"MyApplication"
tokenURL:tokenURL
redirectURI:redirectURI
clientID:clientKey
clientSecret:clientSecret];
return auth;
}
Create a ViewController to authenticate the token:
- (GTMOAuth2ViewControllerTouch*)getSignInViewController{
GTMOAuth2Authentication *auth = [self flattrAuth];
// Specify the appropriate scope string, if any, according to the service's API documentation
auth.scope = #"flattr";
NSURL *authURL = [NSURL URLWithString:#"https://flattr.com/oauth/authorize"];
GTMOAuth2ViewControllerTouch *viewController;
viewController = [[[GTMOAuth2ViewControllerTouch alloc] initWithAuthentication:auth
authorizationURL:authURL
keychainItemName:keychainItemName
delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)] autorelease];
return viewController;
}
and the delegate method:
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuth2Authentication *)auth
error:(NSError *)error {
if (error != nil) {
DLog(#"Flattr sign-in failed with error: %#", [error localizedDescription]);
} else {
DLog(#"Flattr Signin success");
authToken = [auth retain];
}
}
You can display the Viewcontroller in your application - it displays the flattr-login to the user so he can authenticate the application.
You can flattr a thing with the authentication token this way:
NSString* flattrURL = #"https://api.flattr.com/rest/v2/things/%qi/flattr";
NSURL* u = [NSURL URLWithString:[NSString stringWithFormat:flattrURL, item.flattrThingID]];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:u];
[authToken authorizeRequest:request completionHandler:^(NSError *error){
if (error == nil) {
// the request has been authorized
NSURLConnection* connection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
if(!connection){
//TODO: handle error
} else {
[connection start];
}
} else {
//TODO: handle error
}
}];
Now implement the NSURLConnectection delegate methods and parse the JSON responses.
The GTMOAuth2 library allows you to save the authenticated token to the keychain. Look at their introduction at http://code.google.com/p/gtm-oauth2/wiki/Introduction#Retrieving_Authorization_from_the_Keychain for instructions.
When you wan't to authenticate a desktop/mobile app you would wan't to use the oauth2 implicit grant flow. As you register your flattr application use a application specific URI that will callback to your application, ex. iphone-application://oauth-callback.
When you authenticate the application with us you use the response_type token instead of code. This will create a token at once and redirect you back to your application.
Ex. request URL: https://flattr.com/oauth/authorize?client_id=2134&redirect_uri=iphone-application://oauth-callback&response_type=token
If the resource owner will authorize your application we will send a HTTP 302 and redirect you back to your redirect uri.
Ex. response 302 Location: iphone-application://oauth-callback#access_token=e5oNJ4917WAaJaO4zvoVV2dt3GYClPzp&token_type=bearer
Currently we don't have any detailed documentation explaining how to do the implicit grant but we are working on the documentation. Meanwhile i'm all ears.
https://github.com/nxtbgthng/OAuth2Client is a iOS oauth2 library but I don't know if it's any good.
This one looks good: https://github.com/neonichu/FlattrKit

Resources