Wednesday, October 4, 2017

Oauth1 iOS get data from API

Leave a Comment

How to get data from API with Oauth1? I just tried like this but it did not work.

import UIKit import OAuthSwift  class TestLogin: UIViewController {  var oauthswift: OAuthSwift? final let urlString = "https://conversation.8villages.com/1.0/contents/articles"   override func viewDidLoad() {     super.viewDidLoad()      self.doOAuth() }   func doOAuth() {       let oauthswift = OAuth1Swift(         consumerKey:    "******",         consumerSecret: "******",         requestTokenUrl: "https://oauth.8villages.com/tokens/request-token",         authorizeUrl:    "https://accounts.8villages.com/oauth/request-token",         accessTokenUrl:  "https://accounts.8villages.com/oauth/access-token"     )       oauthswift.authorize(         withCallbackURL: URL(string: "https://8villages.com")!,         success: { credential, response, parameters in             print(credential.oauthToken)             print(credential.oauthTokenSecret)             print(parameters["userId"])     },         failure: { error in             print(error.localizedDescription)     }                  ) }  func getHandleURL () {     let url = NSURL(string: urlString)     URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: { (data, response, error) -> Void in          if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {              print(jsonObj!.value(forKey: "data"))          }      }).resume() }  } 

so, how must I do or I need a reference example get data from API with Oauth1? I just don't know how to start to build project with OAuth because I search in google, only tutorial OAuth for login with social media.

1 Answers

Answers 1

In order to send oAuth 1.0 request basically you need to calculate proper query string and body parameter which actually based on your server implementation.

You need to get following query param:

  • oauth_consumer_key
  • oauth_nonce
  • oauth_signature_method
  • oauth_timestamp
  • oauth_version

You can check this blog where all the params are explained in very good detail and also the signature process. Also this answer guide you how to create HMAC-SHA1 signature in iOS

In the end of this process you need to create signature based on signature method which your app and server both agreed upon.

Then a sample POST request should look like following: Which is taken from oAuth1 guide

POST /wp-json/wp/v2/posts Host: example.com Authorization: OAuth                oauth_consumer_key="key"                oauth_token="token"                oauth_signature_method="HMAC-SHA1"                oauth_timestamp="123456789",                oauth_nonce="nonce",                oauth_signature="..."  {     "title": "Hello World!" } 

Hope it helps.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment