iPhone Objective C oauth 2.0 Login - unsupported_g

2019-05-28 21:15发布

问题:

I am brand new to salesforce development and am trying to connect to Salesforce to get the token.

I guess my question is 2 fold: 1) Do I have to use a webpage to authenticate with SF?

2) If not, why is this not working? When I try to use the username and password method of authenticating, I get: {"error":"unsupported_grant_type","error_description":"grant type not supported"}

Here is my code:

NSString *post = [NSString stringWithFormat:@"grant_type=basic-credentials&client_id=%@&client_secret=%@&redirect_uri=%@",
                  kOAuthClientID,
                  kOAuthClientSecret,
                  kOAuthClientAuthURL
                  ];


NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:kOAuthClientTokenUrl]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSError *error;
NSURLResponse *response;
NSLog(@"%@", request);
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"%@", data);

Any thoughts would be welcome.

I did try using grant_type = authorization_code but got another error:

{"error":"invalid_grant","error_description":"invalid authorization code"}

回答1:

If you want to use the username/password grant type, then its type is password not basic-credentials, the correct set of parameters to send are

grant_type=password
client_id=xxxxxxxxxx
client_secret=1234567890
username=noreply@salesforce.com
password=XXXXXXXXX

As i mentioned in your previous question, although this works, you really do want to use the web based flow so as to support salesforce customers that are using alternative login services like SAML.



回答2:

1) Yes you do, with OAuth you need to sign into Salesforce and grant your application access. For an iOS app, you'd be looking at the client flow Salesforce OAuth Client Flow Doc

2) Take a look at the Toolkit for iOS on the Force.com developer site. There is a class called ZKOAuthViewController that pretty much does it all for you. The rest of the tooklit is based around Force.com's SOAP API but I just made my own OAuth login controller based on the toolkits and use the REST API instead.



回答3:

Superfell's answer is nearly correct. The password needs to be set to:

password + security token

See http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_concepts_security.htm for extra info.