ios authentication with facebook and server side verification - iphone

My iOs app authenticates user with Facebook using facebook-sdk.
Now application connects to server and has to confirm that the user identity. Which is recommended way?
Probably iphone has to send some kind of token to server and server has to confirm it with facebook api call
do you have link to these docs?

hello u want to login with Facebook in your ios Application i have use this code for it pls check it
first take web view in you r Application and do connection with Nib file .and enter your facebook Appl
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *client_id = #"Enter your Application ";
NSString *redirect_uri = #"http://www.facebook.com/connect/login_success.html";
NSString *url_string = [NSString stringWithFormat:#"https://graph.facebook.com/oauth/authorize?client_id=%#&redirect_uri=%#&type=user_agent&display=touch", client_id, redirect_uri];
NSURL *url = [NSURL URLWithString:url_string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
-(IBAction)getText:(id)sender{
NSLog(#"%#",[webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.outerHTML"]);
}
- (void)webViewDidFinishLoad:(UIWebView *)_webView {
NSString *url_string = [((_webView.request).URL) absoluteString];
NSLog(#"%#",url_string);
NSRange access_token_range = [url_string rangeOfString:#"access_token="];
//coolio, we have a token, now let's parse it out....
if (access_token_range.length > 0) {
int from_index = access_token_range.location + access_token_range.length;
NSString *access_token = [url_string substringFromIndex:from_index];
NSLog(#"access_token: %#", access_token);
htmldata=[webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.outerHTML"];
NSLog(#"%#",htmldata);
NSLog(#"%#",url_string);
NSArray *arr1=[htmldata componentsSeparatedByString:#"<title>"];
NSString *data=[arr1 objectAtIndex:1];
NSArray *arr2=[data componentsSeparatedByString:#"</title>"];
value=[[NSString alloc]initWithString:[arr2 objectAtIndex:0]];
NSLog(#"%#",value);
if([value isEqualToString:#"Success"])
{
MainScreenController *C = [[MainScreenController alloc]init];
[self.navigationController pushViewController:C animated:YES];
[C release];
}
}
}
thanks

Related

Redirecting Url to app in iphone for linkedIn

I am trying to authorize LinkedIn with iPhone..
I am using following code to redirect url
NSString *authUrl = [NSString stringWithFormat:#"https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=%#&scope=%#&state=%#&redirect_uri=%#" ,
API_KEY ,
#"r_fullprofile",
#"ASDKASIIWER23432KKQ",
#"http://www.myappname.com"
];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: authUrl]];
In my Url types, i have added URL Scheme as http:// and url identifier as
www.myappname.com
however after authorizing , i don't get back to my application from browser.
Any ideas where i am wrong?
i have used a diff approach now, i have used webView inside app and is using it. Works perfect so far.
- (void)viewDidLoad
{
[super viewDidLoad];
[self.myWebView setDelegate:self];
self.indicator = [[CustomActivityViewer alloc] initWithView:self.view];
NSString *authUrl = [NSString stringWithFormat:#"https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=%#&scope=%#&state=%#&redirect_uri=%#" ,
API_KEY ,
#"r_fullprofile rw_nus r_emailaddress r_network w_messages",
SCOPE_CODE
REDIRECT_URI
];
authUrl = [authUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[self.myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:authUrl]]];
}
-(void)webViewDidStartLoad:(UIWebView *)webView
{
[self.indicator startAnimating];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[self.indicator stopAnimating];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
[self.indicator stopAnimating];
}
- (BOOL) webView: (UIWebView *) webView shouldStartLoadWithRequest: (NSURLRequest *) request navigationType: (UIWebViewNavigationType) navigationType
{
NSURL *url = request.URL;
NSLog(#"%#", url.absoluteString);
if ( [url.host isEqualToString:HOST])
{
URLParser *parser = [[URLParser alloc] initWithURLString:url.absoluteString];
NSString *code = [parser valueForVariable:#"code"];
if (code != nil)
{
NSString *authUrl = [NSString stringWithFormat:#"https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code=%#&redirect_uri=%#&client_id=%#&client_secret=%#",
code,
REDIRECT_URI_OAUTH,
API_KEY,
SECRET_KEY];
NSLog(#"%#" , authUrl);
authUrl = [authUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[Utilities responseFromURL:[NSURL URLWithString:authUrl] completionBlock:^(NSString *response, NSError *err)
{
if (err != nil)
{
[Utilities errorDisplay];
}
else
{
NSDictionary *results = [response JSONValue];
[defaults setObject:[results objectForKey:#"access_token"] forKey:#"access_token"];
}
}];
}
}
return YES;
}
You are going to need to register a custom URL scheme, as iOS and OS X don't have a way to redirect a specific host within a URL scheme.
Generally, you can use something like x-myapp: as the url scheme.
Further, the URL Identifier is not a host, but an identifier that describes the URL scheme, much like a UTI identifier for a file type describes a specific file type. For example, you could use com.myCompany.myApp.url or something similar as the identifier.
You should be fine if you create a scheme of form x-myapp: and then use that as the redirect URL.
An example from a proposed Info.plist would be:
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>com.myCompany.myApp.url</string>
<key>CFBundleURLSchemes</key>
<array>
<string>x-myapp</string>
</array>
</dict>
The CFBundleURLName corresponds in the Xcode GUI to URL Identifier.

Google oauth 2.0 refreshing access token

How to get a new access token in Google Oauth 2.0?
I tried this:
NSString * urlString1 = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token?client_id=my_client_id&client_secret=my_client_secret&refresh_token=%#&grant_type=refresh_token",auth.refreshToken];
NSURL * url = [NSURL URLWithString:urlString1];
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSURLConnection * connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[connection start];
But result is: Method Not Allowed (Error 405)
Maybe there is another way to get new access token?
Please help!
Thanks!
HTTP 405 means that you are trying to use a verb that is not allowed by the resource. For example using a POST on a read-only GET resource or PUT on a write resource that only accepts POSTs.
See abraham's answer : Google with oauth 2
please use following code to get access token in Google Plus
First Replase you - (NSString *)description method in GTMOAuth2Authentication.h file and you will surely get G+ Acccess token
- (NSString *)description
{
NSArray *props = [NSArray arrayWithObjects:#"accessToken",nil];//[NSArray arrayWithObjects:#"accessToken", #"refreshToken",#"code", #"assertion", #"expirationDate", #"errorString",nil];
NSMutableString *valuesStr = [NSMutableString string];
NSString *separator = #"";
for (NSString *prop in props) {
id result = [self valueForKey:prop];
if (result)
{
[valuesStr appendFormat:#"%#",result];
separator = #", ";
}
}
return [NSString stringWithFormat:#"%#",valuesStr];
}
in .h file
#class GPPSignInButton;
#interface GPlusView : UIViewController <GPPSignInDelegate>
{
IBOutlet GPPSignInButton *signInButton;
}
#property (retain, nonatomic) IBOutlet GPPSignInButton *signInButton;
in .m file
signInButton_.shouldFetchGoogleUserEmail = TRUE;
signInButton_.delegate = self;
signInButton_.clientID = [SamacharAppDelegate clientID];
signInButton_.scope = [NSArray arrayWithObjects:
#"https://www.googleapis.com/auth/plus.me",
nil];
-(void)finishedWithAuth:(GTMOAuth2Authentication *)auth error:(NSError *)error
{
if (error) {
NSLog(#"Error = %#",error.localizedDescription);
return;
}
NSLog("Auth Data = %#",auth);
/* Auth Data = {accessToken="ya29.AHES6ZQYLmSBc9n4pLj9U8OQrFoTDZnGLH8okPkxbda7B0Q", refreshToken="1/puItTB-sqHupfp9qPCKcb6_gWUjgcxwzc9TKJvUwMEI", expirationDate="2012-11-24 13:30:55 +0000"} */
}

UIwebview doesn't load the PDF file at firdt time

I am developing one application. In that I'am loading the pdf in uiwebview like below.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filename1 = [[paths objectAtIndex:0] stringByAppendingPathComponent:[default1 objectForKey:#"KeyToSelectedFile"]];
NSString *fileName=[filename1 stringByAppendingPathComponent:[default1 objectForKey:#"keyToAppearfile"]];
NSLog(#"%#",fileName);
//NSString *bookpath=[filename1 stringByAppendingPathComponent:book];
NSURL *url = [NSURL fileURLWithPath:fileName];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
web=[[UIWebView alloc]initWithFrame:CGRectMake(20,80, 980, 690)];
web.delegate=self;
[web loadRequest:request];
web.backgroundColor=[UIColor clearColor];
[self.view addSubview:web];
At first time this will crash the application. From second time onwards it will be showing the pdf correctly. It was not shown any error when the app was crashed. I didn't understand what's the problem.
You can also use Documents interaction controller. it is a better approach to view pdf files using that. and its implementation is quite simple too.
here is a reference link to it: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIDocumentInteractionController_class/Reference/Reference.html
I hope it helps you. Cheers!!
- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL) fileURL
usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate {
UIDocumentInteractionController *interactionController =
[UIDocumentInteractionController interactionControllerWithURL: fileURL];
interactionController.delegate = interactionDelegate;
return interactionController;
}
Just give some time to load the PDF from the web server.. On that loading process u can add a ACTIVITY INDICATOR too...

NSMutableRequest and Flickr API for upload images

I use Flickr API for my app to manage user's photo. I decided to make authentication using Apple's classes and it works fine for me. Now my app is authenticated and has all necessary tokens and secret keys so it's possible to perform GET requests with authentication for methods like flickr.photos.search, flickr.test.login and so on.
But I spent a few days trying to perform upload using http://api.flickr.com/services/upload/
and their instructions here.
They say that request should have argument 'photo' and this parameter should not be included in the signature. That is clear, but I have no idea how to implement this parameter the request.
#import "FlickrUploader.h"
#import "HMACSH1.h"
#import "Prefs.h"
#import "NSString+URLEncode.h"
#implementation FlickrUploader
- (void)uploadPhotoAtPath:(NSString*)filePath {
NSString *upload_api_url = #"http://api.flickr.com/services/upload/";
NSString *oauth_nonce = [NSString stringWithFormat:#"%d", 10000000 + arc4random()%1000000];
NSString *oauth_timestamp = [NSString stringWithFormat:#"%d", (long)[[NSDate date] timeIntervalSince1970]];
NSString *oauth_consumer_key = CONSUMER_KEY;
NSString *oauth_signature_method = #"HMAC-SHA1";
NSString *oauth_version = #"1.0";
NSString *oauth_token = [[NSUserDefaults standardUserDefaults] objectForKey:OAUTH_ACCESS_TOKEN_KEY];
//creating basestring to make signature without a 'photo' argument according to API
NSMutableString *basestring = [[NSMutableString alloc] initWithCapacity:8];
[basestring appendFormat:#"&oauth_consumer_key=%#",oauth_consumer_key];
[basestring appendFormat:#"&oauth_nonce=%#",oauth_nonce];
[basestring appendFormat:#"&oauth_signature_method=%#",oauth_signature_method];
[basestring appendFormat:#"&oauth_timestamp=%#",oauth_timestamp];
[basestring appendFormat:#"&oauth_token=%#", oauth_token];
[basestring appendFormat:#"&oauth_version=%#",oauth_version];
//this is may class to make HMAC-SHA1 signature (it works for authentication and for GET requests)
HMACSH1 *hMACSH1 = [[HMACSH1 alloc] init];
NSMutableString *urlEncodedBaseString = [[NSMutableString alloc] initWithCapacity:3];
[urlEncodedBaseString appendString:#"POST"];
[urlEncodedBaseString appendFormat:#"&%#",[upload_api_url urlEncodedString]];
[urlEncodedBaseString appendFormat:#"&%#",[basestring urlEncodedString]];
NSString *oauth_token_secret = [[NSUserDefaults standardUserDefaults] objectForKey:OAUTH_TOKEN_SECRET_KEY];
NSString *hash_key = [CONSUMER_SECRET stringByAppendingFormat:#"&%#",oauth_token_secret];
NSString *oauth_signature = [hMACSH1 hmacSH1base64ForData:urlEncodedBaseString keyValue:hash_key];
//creating url for request
NSMutableString *urlString = [[NSMutableString alloc] initWithCapacity:8];
[urlString appendFormat:#"%#",upload_api_url];
[urlString appendFormat:#"?"];
[urlString appendString:basestring];
[urlString appendFormat:#"&oauth_signature=%#", oauth_signature];
NSURL *authURL = [[NSURL alloc] initWithString:urlString];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:authURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
request.HTTPMethod = #"POST";
UIImage *img = [UIImage imageNamed:filePath];
NSData *imgData = UIImageJPEGRepresentation(img, 0.8);
//here I don't know what to do :((( perhaps NSOutputStream
}

Modify URL request in shouldStartLoadWithRequest method and displaying in Webview

I have one webview and 3 url.
So when application starts i am showing URL1 in webview.
Now when i select any portion of webview it will redirect to URL2.
But only i want to fetch some data from URL2 and dont want to show it to user.
Which i can able to do by using shouldStartLoadWithRequest: method with return NO.
but Now i need to show URL 3 with data received from URL2 in my Webview.
But it is not showing anything ,how can i do it ?
For this i am using following code
-(void)viewDidLoad
{
//Normal showing of URL1 in webview
}
- (BOOL)webView:(UIWebView*)webViewRef shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
{
if(selectedDataExist){
//get data from URL2
//Make New URL3 string
[webView loadRequest: [NSURLRequest requestWithURL:[NSURL URLWithString:myNewUrlString]]];
return NO;
}
else
{
//by default URL1 comes
return YES;
}
i did this:
i was trying to send a info via GET method so i substring the last 10 characters (in my case) of any url requested, if it doesn't have the GET method, it make a new request appending the GET method to the url and return NO, next time this function get called it will have the GET method so it will continue.
-(BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *urls = [request.URL absoluteString];
NSString *code = [urls substringFromIndex: [urls length] - 10];
if (![code isEqualToString:#"?iphone=si"]) {
NSURL *nueva = [NSURL URLWithString:[NSString stringWithFormat:#"%#?iphone=si",urls]];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:nueva];
[self.mywebview loadRequest:requestObj];
return NO;
}
return YES;
}
This is how I do it
NSURL *LocalUrl = [[NSURL alloc] initWithString:[newUrl stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding]];
NSURLRequest *objNSURLRequest;
objNSURLRequest = [NSURLRequest requestWithURL:LocalUrl];
[yourwebview loadRequest:ObjNSURLRequest];
[LocalUrl release];
return NO;