AccessToken is not valid error : iOS Obj C - objective-c

I am developing an iOS application in objective C where when a user logins to the App, it will return an access token in son format. I need to query other server api with the access token. My son response is like :
{
accessToken = "$2a$10$6Tu7e.fsKQxp4cw/SkRBS.65wsA.Pagt2EwdpBjXRdaUQb6yNxTtS";
id = 12;
message = "login successful";
success = 1;
}
I am retrieving this via
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
[jsonDict valueForKey:#"accessToken"];
Whenever i try with the accessToken get from this, it shows invalid access token.(I use the same access token in postman.and got the same response).
When I copy the access token from postman and use the same in iOs code, it works fine. What is happening? Any help will be appreciated.
The code I am using to call the http request is:
// NSString *accessToken = [[NSUserDefaults standardUserDefaults] valueForKey:#"accessToken"];
//Send JSON data to cloud using HTTP POST
NSURL *url1 = [NSURL URLWithString:urlString];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url1
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request1 setHTTPMethod:#"GET"];
// [request1 setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 setValue:accessToken forHTTPHeaderField:#"Authorization"];
NSLog(#"access :: %#",accessToken);
NSURLConnection *conn1 = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];

Related

.NET Web Api Token Authentication Rest Service "Get" Method in Objective-C

I'm trying to access the following URL:
http://appointmentreminder4.azurewebsites.net/Profile
This URL uses a "Get" method, and is supposed to provide JSON results. Before accessing the URL, you need to login using your Email Address and Password. After logging in successfully, the Web API issues a token. This token is used in ALL communications going forward.
I am currently unable to retrieve the token in Objective-C. I have attempted to google this problem, but I cannot figure out:
1) How to get the token
2) How to get the JSON output from the URL.
Here is the code I have written so far that returns neither the JSON, nor the token:
NSDictionary *postDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"Email Adress", #"MyEmailAddress",
#"Password", #"MyPassword",
nil];
NSError *error = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:kNilOptions error:&error];
NSURLResponse *response;
NSData *localData = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://appointmentreminder4.azurewebsites.net/home"]];
[request setHTTPMethod:#"POST"];
if (error == nil)
{
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
// Send the request and get the response
localData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result = [[NSString alloc] initWithData:localData encoding:NSASCIIStringEncoding];
NSLog(#"Post result : %#", result);
}
If the above link fails, use this link to navigate to the specific page:
http://appointmentreminder4.azurewebsites.net/home

iOS json: put request with token

I have a question concerning json authentication with tokens. I have a server with a database. When I want to POST or PUT to the database I need to have a token with the request, which is unique for every user. I have tried this with a rest client and it works fine. I will attach a print screen of the rest client. But when I want to do it from the app I get the response "Access denied". What am I doing wrong?
Here is my objective-c code:
NSString *jsonRequest = [NSString stringWithFormat:#"{\"name\":\"%#\",\"skills\":\"%#\",\"description\":\"%#\",\"expectation\":\"%#\",\"mail\":\"%#\"}",profileName.text,profileSkills.text,profileDescription.text,profileExpectations.text,profileMail.text];
NSString *testToken = #"6ecf0fe735487bcaab74c0fcd3ed57dc";
NSURL *url = [NSURL URLWithString:#"https://31.208.72.233:3000/persons/63"];
NSData *JSONBody = [jsonRequest dataUsingEncoding:NSUTF8StringEncoding];
NSString *headerValue = [NSString stringWithFormat:#"Authorization: Token %#" , testToken];
NSMutableURLRequest *loginRequest = [[NSMutableURLRequest alloc] initWithURL:url];
loginRequest.HTTPMethod = #"PUT";
loginRequest.HTTPBody = JSONBody;
[loginRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[loginRequest addValue:headerValue forHTTPHeaderField:#"Authorization"];
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:loginRequest returningResponse:&response error:nil];
NSString *txt = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
In the headers you have key value pairs. The Authorization is the key part and everything after the : is the value.
It looks like what you may actually be sending is Authorization: Authorization: Token 6ecf0fe735487bcaab74c0fcd3ed57dc. You should remove Authorization from headerValue

How to get a new access token after expiration using OAuth 2.0 along with Youtube API in iOS application

I am using the Youtube Api in my iPad application. i managed to get authenticated and get the access token using the OAuth 2.0.
my problem is that the token expires after one hour and i don't know how to get a new one using the refresh-token without going through the authentication process again.
i am using XCode 4.5 and iOS 5.1 & 6
According do the documentation
If your application obtains a refresh token during the authorization process, then you will need to periodically use that token to obtain a new, valid access token. Server-side web applications, installed applications, and devices all obtain refresh tokens.
So if you already have your refresh token, you just need to perform a POST request configured as follows
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
client_id=21302922996.apps.googleusercontent.com&
client_secret=<YOUR CLIENT SECRET>
refresh_token=<YOUR REFRESH TOKEN>
grant_type=refresh_token
and you'll get back a response like
{
"access_token":<A NEW ACCESS TOKEN>,
"expires_in":<AN EXPIRING TIME>,
"token_type":"Bearer"
}
Here is the full code to refresh the accessToken using AFNetworking to make the request:
NSString *refreshToken = <YOUR_REFRESH_TOKEN>;
NSString *post = [NSString stringWithFormat:#"client_secret=%#&grant_type=refresh_token&refresh_token=%#&client_id=%#",kYouTubeClientSecret,refreshToken,kYouTubeClientID];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url = [NSURL URLWithString:#"https://accounts.google.com/o/oauth2/token"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
AFHTTPRequestOperation *httpRequest = [httpClient HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
NSString *newAccessToken = json[#"access_token"];
NSLog(#"received new accessToken = %#",newAccessToken);
// store accessToken here
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"error refreshing token: %#",[error localizedDescription]);
}];
[httpClient enqueueHTTPRequestOperation:httpRequest];

Basic authorization in NSMutableURLRequest isn't working

I'm trying to add basic authorization to my request header. The code below compiles and I dont get any runtime errors. However, on the server side I do not see the "Authorization" in the header at all.
I was able to implement the didReceiveAuthenticationChallenge method and that works, but I dont understand why I have to do it this way. I simply want to always add basic auth to every request.
I'm not interested in using ASIHTTPRequest.
Thanks for the help!
This is my code below:
NSURL *url = [[NSURL alloc] initWithString:#"http://localhost:8000/MyWebService"];
self.userName = #"myusername";
self.password = #"mypassword";
NSMutableString *credentials = [[NSMutableString alloc] initWithFormat:#"%#:%#", userName, password];
NSString *encodedCredentials = [[credentials dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
NSString *authHeader = [NSString stringWithFormat:#"Basic %#", encodedCredentials];
NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5];
[req addValue:authHeader forHTTPHeaderField:#"Authorization"];
self.urlConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
if (self.urlConnection) {
self.receivedData = [NSMutableData data];
}
else {
errorLabel.text = #"Error connecting to the server";
}
The didReceiveAuthenticationChallenge is the way it works in iOS and the easiest way to do it. It will be submitted with every request (with the challenge). Guess that's not what you want to hear=)
I guess you have tried using different tutorials. I've used this one to authenticate before:
Basic access Auth, iOS

How to authenticate on twitter from iphone using asihttp?

I used the asihttp library to connect to twitter.
The idea is to send a login request, get the response and extract the session ID/auth code from the response's cookie header. Then you can use that session ID/auth code for consecutive calls.
I don't obtain the auth_code because the authentication fails. how can I fix this?
the code is below:
- (void) login {
NSString *username = #"user";
NSString *password = #"pass";
NSURL *url = [NSURL URLWithString:#"https://twitter.com/sessions?phx=1"];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request addRequestHeader:#"User-Agent" value: #"ASIHTTPRequest"];
[request setPostValue:username forKey:#"session[username_or_email]"];
[request setPostValue:password forKey:#"session[password]"];
[request setDelegate: self];
[request setDidFailSelector: #selector(loginRequestFailed:)];
[request setDidFinishSelector: #selector(loginRequestFinished:)];
[request startAsynchronous];
}
- (void)loginRequestFailed:(ASIHTTPRequest *)request {
NSError *error = [request error];
NSLog(#"login request failed with error: %#", [error localizedDescription]);
}
- (void)loginRequestFinished:(ASIHTTPRequest *)request {
NSString *responseString = [[request responseHeaders] objectForKey:#"Set-Cookie"];
NSLog(#"%#",responseString);
}
I tried to connect from shell and it works.
curl -d 'session[user_or_emai]=user&session[password]=pass' https://twitter.com/sessions
Don't scrape twitter.com. It will end with you getting suspended. Instead use the approved API to integrate with Twitter. You can read about how authentication works with Twitter's API, how you can use xAuth to jumpstart authentication with a users password, and the open source code to help get you started.