GithubHelp home page GithubHelp logo

oauthswiftalamofire's Introduction

OAuthSwift

OAuthSwift

Swift based OAuth library for iOS and macOS.

Support OAuth1.0, OAuth2.0

Twitter, Flickr, Github, Instagram, Foursquare, Fitbit, Withings, Linkedin, Dropbox, Dribbble, Salesforce, BitBucket, GoogleDrive, Smugmug, Intuit, Zaim, Tumblr, Slack, Uber, Gitter, Facebook, Spotify, Typetalk, SoundCloud, Twitch, Reddit, etc

Installation

OAuthSwift is packaged as a Swift framework. Currently this is the simplest way to add it to your app:

  • Drag OAuthSwift.xcodeproj to your project in the Project Navigator.
  • Select your project and then your app target. Open the Build Phases panel.
  • Expand the Target Dependencies group, and add OAuthSwift framework.
  • import OAuthSwift whenever you want to use OAuthSwift.

Support Carthage

github "OAuthSwift/OAuthSwift" ~> 2.2.0
  • Run carthage update.
  • On your application targets’ “General” settings tab, in the “Embedded Binaries” section, drag and drop OAuthSwift.framework from the Carthage/Build/iOS folder on disk.

Support CocoaPods

  • Podfile
platform :ios, '10.0'
use_frameworks!

pod 'OAuthSwift', '~> 2.2.0'

Swift Package Manager Support

import PackageDescription

let package = Package(
    name: "MyApp",
    dependencies: [
        .package(name: "OAuthSwift",
            url: "https://github.com/OAuthSwift/OAuthSwift.git",
            .upToNextMajor(from: "2.2.0"))
    ]
)

Old versions

Swift 3

Use the swift3 branch, or the tag 1.1.2 on main branch

Swift 4

Use the tag 1.2.0 on main branch

Objective-C

Use the tag 1.4.1 on main branch

How to

Setting URL Schemes

In info tab of your target Image Replace oauth-swift by your application name

Handle URL in AppDelegate

  • On iOS implement UIApplicationDelegate method
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey  : Any] = [:]) -> Bool {
  if url.host == "oauth-callback" {
    OAuthSwift.handle(url: url)
  }
  return true
}
  • On iOS 13, UIKit will notify UISceneDelegate instead of UIApplicationDelegate.
  • Implement UISceneDelegate method
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
        guard let url = URLContexts.first?.url else {
            return
        }
        if url.host == "oauth-callback" {
            OAuthSwift.handle(url: url)
        }
}

⚠️ Any other application may try to open a URL with your url scheme. So you can check the source application, for instance for safari controller :

if options[.sourceApplication] as? String == "com.apple.SafariViewService" {
  • On macOS you must register a handler on NSAppleEventManager for event type kAEGetURL (see demo code)
func applicationDidFinishLaunching(_ aNotification: NSNotification) {
    NSAppleEventManager.shared().setEventHandler(self, andSelector:#selector(AppDelegate.handleGetURL(event:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}
func handleGetURL(event: NSAppleEventDescriptor!, withReplyEvent: NSAppleEventDescriptor!) {
    if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue, let url = URL(string: urlString) {
        OAuthSwift.handle(url: url)
    }
}

Authorize with OAuth1.0

// create an instance and retain it
oauthswift = OAuth1Swift(
    consumerKey:    "********",
    consumerSecret: "********",
    requestTokenUrl: "https://api.twitter.com/oauth/request_token",
    authorizeUrl:    "https://api.twitter.com/oauth/authorize",
    accessTokenUrl:  "https://api.twitter.com/oauth/access_token"
)
// authorize
let handle = oauthswift.authorize(
    withCallbackURL: "oauth-swift://oauth-callback/twitter") { result in
    switch result {
    case .success(let (credential, response, parameters)):
      print(credential.oauthToken)
      print(credential.oauthTokenSecret)
      print(parameters["user_id"])
      // Do your request
    case .failure(let error):
      print(error.localizedDescription)
    }             
}

OAuth1 without authorization

No urls to specify here

// create an instance and retain it
oauthswift = OAuth1Swift(
    consumerKey:    "********",
    consumerSecret: "********"
)
// do your HTTP request without authorize
oauthswift.client.get("https://api.example.com/foo/bar") { result in
    switch result {
    case .success(let response):
        //....
    case .failure(let error):
        //...
    }
}

Authorize with OAuth2.0

// create an instance and retain it
oauthswift = OAuth2Swift(
    consumerKey:    "********",
    consumerSecret: "********",
    authorizeUrl:   "https://api.instagram.com/oauth/authorize",
    responseType:   "token"
)
let handle = oauthswift.authorize(
    withCallbackURL: "oauth-swift://oauth-callback/instagram",
    scope: "likes+comments", state:"INSTAGRAM") { result in
    switch result {
    case .success(let (credential, response, parameters)):
      print(credential.oauthToken)
      // Do your request
    case .failure(let error):
      print(error.localizedDescription)
    }
}

Authorize with OAuth2.0 and proof key flow (PKCE)

// create an instance and retain it
oauthswift = OAuth2Swift(
    consumerKey:    "********",
    consumerSecret: "********",
    authorizeUrl: "https://server.com/oauth/authorize",
    responseType: "code"
)
oauthswift.accessTokenBasicAuthentification = true

guard let codeVerifier = generateCodeVerifier() else {return}
guard let codeChallenge = generateCodeChallenge(codeVerifier: codeVerifier) else {return}

let handle = oauthswift.authorize(
    withCallbackURL: "myApp://callback/",
    scope: "requestedScope", 
    state:"State01",
    codeChallenge: codeChallenge,
    codeChallengeMethod: "S256",
    codeVerifier: codeVerifier) { result in
    switch result {
    case .success(let (credential, response, parameters)):
      print(credential.oauthToken)
      // Do your request
    case .failure(let error):
      print(error.localizedDescription)
    }
}

See demo for more examples

Handle authorize URL

The authorize URL allows the user to connect to a provider and give access to your application.

By default this URL is opened into the external web browser (ie. safari), but apple does not allow it for app-store iOS applications.

To change this behavior you must set an OAuthSwiftURLHandlerType, simple protocol to handle an URL

oauthswift.authorizeURLHandler = ..

For instance you can embed a web view into your application by providing a controller that displays a web view (UIWebView, WKWebView). Then this controller must implement OAuthSwiftURLHandlerType to load the URL into the web view

func handle(_ url: NSURL) {
  let req = URLRequest(URL: targetURL)
  self.webView.loadRequest(req)
  ...

and present the view (present(viewController, performSegue(withIdentifier: , ...) You can extend OAuthWebViewController for a default implementation of view presentation and dismiss

Use the SFSafariViewController (iOS9)

A default implementation of OAuthSwiftURLHandlerType is provided using the SFSafariViewController, with automatic view dismiss.

oauthswift.authorizeURLHandler = SafariURLHandler(viewController: self, oauthSwift: oauthswift)

Of course you can create your own class or customize the controller by setting the variable SafariURLHandler#factory.

Make signed request

Just call HTTP functions of oauthswift.client

oauthswift.client.get("https://api.linkedin.com/v1/people/~") { result in
    switch result {
    case .success(let response):
        let dataString = response.string
        print(dataString)
    case .failure(let error):
        print(error)
    }
}
// same with request method
oauthswift.client.request("https://api.linkedin.com/v1/people/~", .GET,
      parameters: [:], headers: [:],
      completionHandler: { ...

See more examples in the demo application: ViewController.swift

OAuth provider pages

Images

Image Image Image

Contributing

See CONTRIBUTING.md

Add a new service in demo app

Integration

OAuthSwift could be used with others frameworks

You can sign Alamofire request with OAuthSwiftAlamofire

To achieve great asynchronous code you can use one of these integration frameworks

License

OAuthSwift is available under the MIT license. See the LICENSE file for more info.

License Platform Language Cocoapod Carthage compatible Build Status

oauthswiftalamofire's People

Contributors

e-marchand avatar hsousa avatar jobinsjohn avatar jodrescher avatar konstk1 avatar maxdesiatov avatar patricks avatar phimage avatar sanchexx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

oauthswiftalamofire's Issues

Running Carthage Update Fails - Apple Silicon

I am using Apple Silicon. The Carthage website suggests the use of flag --use-xcframeworks.

carthage update --use-xcframeworks

*** Cloning OAuthSwiftAlamofire
*** Cloning OAuthSwift
*** Cloning Alamofire
*** Checking out Alamofire at "5.4.1"
*** Checking out OAuthSwiftAlamofire at "0.2.0"
*** Checking out OAuthSwift at "2.1.2"
*** xcodebuild output can be found in /var/folders/n0/yy5pk5ns3pb6v2hdqf_pwsv00000gn/T/carthage-xcodebuild.XKiEWr.log
*** Building scheme "Alamofire watchOS" in Alamofire.xcworkspace
*** Building scheme "Alamofire tvOS" in Alamofire.xcworkspace
*** Building scheme "Alamofire iOS" in Alamofire.xcworkspace
^[[C*** Building scheme "Alamofire macOS" in Alamofire.xcworkspace
*** Building scheme "OAuthSwiftTVOS" in OAuthSwift.xcworkspace
*** Building scheme "OAuthSwiftWatchOS" in OAuthSwift.xcworkspace
*** Building scheme "OAuthSwift" in OAuthSwift.xcworkspace
*** Building scheme "OAuthSwiftMacOS" in OAuthSwift.xcworkspace
*** Building scheme "OAuthSwift-Alamofire" in OAuthSwift-Alamofire.xcworkspace
Build Failed
	Task failed with exit code 65:
	/usr/bin/xcrun xcodebuild -workspace /Users/robertnash/Code/Monster/Carthage/Checkouts/OAuthSwiftAlamofire/OAuthSwift-Alamofire.xcworkspace -scheme OAuthSwift-Alamofire -configuration Release -derivedDataPath /Users/robertnash/Library/Caches/org.carthage.CarthageKit/DerivedData/12.4_12D4e/OAuthSwiftAlamofire/0.2.0 -sdk iphoneos ONLY_ACTIVE_ARCH=NO CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES archive VALIDATE_WORKSPACE=NO -archivePath /var/folders/n0/yy5pk5ns3pb6v2hdqf_pwsv00000gn/T/OAuthSwiftAlamofire SKIP_INSTALL=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=NO CLANG_ENABLE_CODE_COVERAGE=NO STRIP_INSTALLED_PRODUCT=NO (launched in /Users/robertnash/Code/Monster/Carthage/Checkouts/OAuthSwiftAlamofire)

This usually indicates that project itself failed to compile.

After import, compiling is not possible.

I am trying to use OAuthSwiftAlamofire using cocoapod.

However, after pod install, the following error occurs in the HTTPMethod.swift file of the OAuthSwiftAlamofire framework.

HTTPMethod.swift

(Line10) import Alamofire
->
Compiling for iOS 9.0, but module 'Alamofire' has a minimum deployment target of iOS 10.0

I tried changing the ios version to 10 in OAuthSwiftAlamofire's Build Setting, but this time a source error occurred in several files.

The version of each library I use is as follows.

Alamofire
5.1.0

OAuthSwift
2.0.0

OAuthSwiftAlamofire
0.2.0

Swift5
Xcode Ver: 11.4.1

Is there a combination of versions that can be used reliably?

Documentation Suggestion

I think it would be helpful to explicitly state in the wiki page that the OAuth2 adapter will also automatically refresh the access token on a per request basis. Thank you for making these libraries available, I look forward to using them!

Error 400 in Twitter API - Need help

Kindly excuse me if this is not OAuthSwiftAlamofire issue.
I'm trying to access Twitter API and getting Error 400. Below is my code. Any idea what I'm doing wrong here?
OAuth URL Callback is successful. But when I try to access the API I'm getting 400. Thank you in advance.

OAuth Setup and Authorize:

func doAuthService() {
        currentParameters["consumerKey"] = "************"
        currentParameters["consumerSecret"] = "**************"
        let oauthswift = OAuth1Swift(
            consumerKey:     currentParameters["consumerKey"]!,
            consumerSecret:  currentParameters["consumerSecret"]!,
            requestTokenUrl: "https://api.twitter.com/oauth/request_token",
            authorizeUrl:    "https://api.twitter.com/oauth/authorize",
            accessTokenUrl:  "https://api.twitter.com/oauth/access_token"
        )
        oauthswift.authorizeURLHandler = self.getUrlHandler()
        oauthswift.authorize(
            withCallbackURL: URL(string: "https://tinyurl.com/q5cr9wz")!,
            success: { (credential, response, parameters) in
                print(response)       
        }) { (error) in
            print(error.description)
        }
        
    }

Function to test Twitter:

func testTwitter(){
        let headers: HTTPHeaders = [
            "Content-Type" : "application/json",
            "Accept": "application/json"
        ]
       let sessionManager = Alamofire.SessionManager.default
        sessionManager.adapter = OAuthSwiftRequestAdapter.init(oauthSwift!)
       sessionManager.request(URL(string: "https://api.twitter.com/1.1/statuses/mentions_timeline.json")!,
                              method: .get,
                              parameters: [:],
                              encoding: JSONEncoding.default,
                              headers: headers)
        .responseData { (response) in
            print(response)
        }
        }
}

Request HTTP Headers are:


▿ Optional<Dictionary<String, String>>
  ▿ some : 3 elements
    ▿ 0 : 2 elements
      - key : "Accept"
      - value : "application/json"
    ▿ 1 : 2 elements
      - key : "Content-Type"
      - value : "application/json"
    ▿ 2 : 2 elements
      - key : "Authorization"
      - value : "OAuth oauth_consumer_key=FN0mBsoNEBecDp1E7wxCHjmLa, oauth_nonce=F8813241, oauth_signature=vFliY51x1GuHyDL%2F8lmxLpx%2BL0E%3D, oauth_signature_method=HMAC-SHA1, oauth_timestamp=1531840882, oauth_token=6Jz9lwAAAAAA7yKpAAABZKjUp1o, oauth_version=1.0"

refresh_token shouldn't send Authorization header

Thank you for a great framework.

I think there is a problem with OAuthSwift2RequestAdapter.refreshTokens().
Currently an Authorization header is inserted in the refresh_token request.

However none of the RFC examples show an Authorization header.

This is causing me problems. The server rejects my attempt at refreshing, because the access_token is expired. I have made a workaround, but I would very much prefer that this got fixed in OAuthSwiftAlamofire.

Here are examples of the refresh_token request:
https://tools.ietf.org/html/rfc6749#page-17
https://tools.ietf.org/html/rfc6749#page-47

The RFC doesn't mention if the Authorization header is optional in the refresh_token request. I'm unsure if it's allowed. I think the Authorization header shouldn't be there. Forgive me if I'm wrong about this.

I have made 2 workarounds.

Current behavior

Here the request has an Authorization header.

Request

:method: POST
:scheme: https
:path: /oauth
:authority: sandbox.alamofire.org
accept: */*
content-type: application/x-www-form-urlencoded; charset=utf-8
accept-encoding: br, gzip, deflate
authorization: Bearer xTKx8LNvDCmS570GiqmqVGMuciv
user-agent: Install/1 CFNetwork/887 Darwin/16.7.0
accept-language: en-us
content-length: 141

grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA&client_secret=CLIENT_SECRET&client_id=CLIENT_ID

Response

:status: 401
content-type: text/plain; charset=utf-8
x-content-type-options: nosniff
content-length: 20
date: Thu, 24 Dec 1984 23:59:59 GMT

Authorization error

New behavior with workaround

Here the request is without the Authorization header.

Request

:method: POST
:scheme: https
:path: /oauth
:authority: sandbox.alamofire.org
accept: */*
content-type: application/x-www-form-urlencoded; charset=utf-8
accept-encoding: br, gzip, deflate
user-agent: Install/1 CFNetwork/887 Darwin/16.7.0
content-length: 141
accept-language: en-us

grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIA&client_secret=CLIENT_SECRET&client_id=CLIENT_ID

Response

:status: 200
content-type: application/json
content-length: 177
date: Thu, 24 Dec 1984 23:59:59 GMT

{"access_token":"2YotnFZFEjr1zCsicMWpAA","expires_in":3600,"refresh_token":"tGvz3JOkFX0G5Q2xTlKWIA"}

Workaround A

private func refreshTokens(completion: @escaping RefreshCompletion) {
    guard !isRefreshing else { return }
    
    isRefreshing = true
    
    print("reset access_token")
    oauth2Swift.client.credential.oauthToken = ""
    oauth2Swift.client.credential.oauthTokenExpiresAt = nil
    
    oauth2Swift.renewAccessToken(
        withRefreshToken: oauth2Swift.client.credential.oauthRefreshToken,
        success: { [weak self] (credential, response, parameters) in
            guard let strongSelf = self else { return }
            completion(true)
            strongSelf.isRefreshing = false
        }, failure: { [weak self] (error) in
            guard let strongSelf = self else { return }
            completion(false)
            strongSelf.isRefreshing = false
        }
    )
}

Workaround B

class OAuth2SwiftWorkaround: OAuth2Swift {
    override func renewAccessToken(withRefreshToken refreshToken: String, parameters: OAuthSwift.Parameters?, headers: OAuthSwift.Headers?, success: @escaping OAuthSwift.TokenSuccessHandler, failure: OAuthSwift.FailureHandler?) -> OAuthSwiftRequestHandle? {

        print("reset access_token")
        client.credential.oauthToken = ""
        client.credential.oauthTokenExpiresAt = nil
        
        return super.renewAccessToken(withRefreshToken: refreshToken, parameters: parameters, headers: headers, success: success, failure: failure)
    }
}

Alamofire version compatibility

What's the version of Alamofire that is compatible with this utility.
I've tried 5.0.0-beta.4, but it doesn't seem to work with it.

Using OAuth1 with .Post request does not work

I get this response from the server when using OAuth with .post request

{
code = "woocommerce_rest_authentication_error";
data = {
status = 401;
};
message = "Invalid signature - provided signature does not match.";
}


public func fetchObjectWithOAuth(type: APIMethodType, params: KBHTTPParameters? = nil, handler: @escaping (T?, _ error: AlertMessage?)->()) where T: Codable {

    session = SessionManager( configuration: .default )
    session?.adapter = oauthswift.requestAdapter
    self.session.request(type.url, method: type.httpMethod, parameters: params, encoding: URLEncoding.default,headers: type.headers).responseJSON { data in
                            switch data.result {
                            case .success(let value):
                                print("The value is : \n\(value)")
                                let decoder = JSONDecoder()
                                
                                guard let jsonData = data.data else {
                                    handler(nil, AlertMessage(title: NetworkingStrings.baseErrorTitle.localized, body: NetworkingStrings.baseErrorMessage.localized))
                                    break
                                }
                                
                                do {
                                    let result = try decoder.decode(T.self, from: jsonData)
                                    handler(result, nil)
                                }
                                catch {
                                    print("JSON SERIALIZATION error!: \(error)")
                                    handler(nil, AlertMessage.dataParseErrorAlertMessage)
                                }
                                break
                            case .failure(let error):
                                //handler(nil, self.parseApiError(data: data.data))
                                handler(nil, AlertMessage(title: NetworkingStrings.baseErrorTitle.localized, body: error.localizedDescription))
                                break
                            }
    }
}

Note: It works for other request types (.GET , .PUT ,.DELETE)

Xcode8.3.1 warnings

There are these 4 warnings. Please fix

OAuthSwiftError.swift:98:58: String interpolation produces a debug description for an optional value; did you mean to make this explicit?
String+OAuthSwift.swift:88:24: Forced cast from 'CFString?' to 'String' only unwraps and bridges; did you mean to use '!' with 'as'?
String+OAuthSwift.swift:50:30: Conditional downcast from 'NSString?' to 'String' is a bridging conversion; did you mean to use 'as'?
String+OAuthSwift.swift:50:60: Conditional downcast from 'NSString?' to 'String' is a bridging conversion; did you mean to use 'as'?

Thank you for this awesome framework

Question: how to make an Alamofire request without the consumerSecret?

Today, I am using SessionManager to make my OAuth1 URL requests via Alamofire.

sessionManager = SessionManager( configuration: .default )
sessionManager?.adapter = oauth!.requestAdapter
sessionManager?.request( ... ) ...

This works just fine, except that it requires the consumerSecret to create my OAuth1 object/requestAdapter, even though the OAuth1-authenticated API request only needs the consumerKey and token in the headers.

Is there a straightforward way to create an Alamofire/OAuth1 request without the consumerSecret?

Invalid Signature

Description

I'm trying to use OAuthSwiftAlamofire to make API Calls protected with OAuth 1.0. The authorization with OAuthSwift is already working and giving me a token and a token secret. Sadly if I'm sending a request using the requestAdapter as described in the Readme, i get a 401 invalid_signature back. Looking at the made request and checking an online signature generator, I see that the generated signatures indeed differ. I just don't know why, because I have no experience with the matter so far. What do you need from me to help me out?

OAuth Provider

  • Custom: Car2Go

OAuth Version:

  • Version 1
  • Version 2

OS (Please fill the version) :

  • iOS :
  • OSX :
  • TVOS :
  • WatchOS :

Installation method:

  • Carthage
  • CocoaPods
  • Manually

Library version:

  • head
  • v1.0.0
  • v0.6
  • other: (Please fill in the version you are using.)

Xcode version:

  • 8.0 (Swift 3.0)

  • 8.0 (Swift 2.3)

  • 7.3.1

  • other: (Please fill in the version you are using.)

  • objective c

Refresh token not firing automatically

Do I need to write some extra code to refresh my access token?

I have the following (Swift 4) code and it's not refreshing...

let sessionManager = SessionManager.default
sessionManager.adapter = OAuthSwiftRequestAdapter(AppDelegate.datalogOAuth)
sessionManager.retrier = OAuthSwiftRequestAdapter(AppDelegate.datalogOAuth) as? RequestRetrier

Thanks in advance

Building via Carthage fails

If I try to build this project via carthage, I get the following error:

** BUILD FAILED **


The following build commands failed:
    PhaseScriptExecution Check\ Pods\ Manifest.lock /Users/foobar/Library/Developer/Xcode/DerivedData/OAuthSwift-Alamofire-cigghtqwmzhspicxohffrdiuuurg/Build/Intermediates/OAuthSwift-Alamofire.build/Release-iphoneos/OAuthSwift-Alamofire.build/Script-02AF90F7E1483DE793EE256B.sh
(1 failure)
error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.
A shell task (/usr/bin/xcrun xcodebuild -workspace /Users/foobar/Developer/tmp/TestProject/Carthage/Checkouts/OAuthSwift-Alamofire/OAuthSwift-Alamofire.xcworkspace -scheme OAuthSwift-Alamofire -configuration Release -sdk iphoneos ONLY_ACTIVE_ARCH=NO BITCODE_GENERATION_MODE=bitcode CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES clean build) failed with exit code 65:
** BUILD FAILED **


The following build commands failed:
    PhaseScriptExecution Check\ Pods\ Manifest.lock /Users/foobar/Library/Developer/Xcode/DerivedData/OAuthSwift-Alamofire-cigghtqwmzhspicxohffrdiuuurg/Build/Intermediates/OAuthSwift-Alamofire.build/Release-iphoneos/OAuthSwift-Alamofire.build/Script-02AF90F7E1483DE793EE256B.sh
(1 failure)


It looks like the cocoapods dependencies need to be removed in the build settings.

OAuthSwift adapter causing error 32 on Twitter client

{"errors":[{"code":32,"message":"Could not authenticate you."}]}

is the exact error.

Given

 let params = ["status":tweet.urlEscaped]
 let url = "https://api.twitter.com/1.1/statuses/update.json

Running

oAuthSwift.client.post(url, parameters: params, headers: nil, success: { result in
    dump(result.1)
    print(String(data: result.0, encoding: .utf8)!)
}, failure: nil)

Works just fine.

let sessionManager = SessionManager.default
sessionManager.adapter = oAuthSwift.requestAdapte 
sessionManager.request(url, method: .post, parameters: params, headers: nil).responseJSON { response
    dump(response.request!)
    print(String(data: response.data!,encoding: .utf8)!) 
}

Fails.

I'm not quite well versed enough with OAuthSwift's workings to figure out exactly what is going on that causes the problem.

Question: Can't retrying be avoided?

Hi,
I just started playing with this on a project and was wondering why the refresh mechanism relies on the retry mechanism for a "failed" request? Is this a limitation of Alamofire?

I am not super-comfortable with relying on a 401. It would be nice to be able to log Oauth-related failures without having to supress a ton of expected credential failures server side.

Tokens are (often, and certainly in my case) JWT tokens. So, i know before making a request wether or not the access token is valid or expired. The problem seems to be that adapt() for RequestAdapter is not terribly compatible with an async http request.

If you have the time to answer, I am curious.

Requests while refreshing are not handled properly

If a request comes in with a 401 while token refresh is in progress, the completion handler of retry is never called and I believe the request just "disappears."

In fact, documentation for retry states:

The one requirement is that the completion closure is called to ensure the request is properly cleaned up after.

How can I get access token wihtout passing authorization URL?

Hello there,

I want to implement Oauth2.0 with following parameters
client secret,
client key,
access token URL.
I am attaching screen shot for the same.
I see your code is asking for authorization url.

I tested api in postman it works fine.

Can you please let me know how I can achieve using your library?

Here is screenshot for request
Screen Shot 2019-12-23 at 10 52 26 AM

Here is screenshot for Response

Screen Shot 2019-12-23 at 10 53 30 AM

No longer compatible with OAuthSwift (2.0.0)

Using OAuthSwiftAlamofire (0.2.0) with OAuthSwift (2.0.0) (and Xcode 10.2.1/Swift 5), I encounter a compiler error in OAuthSwiftRequestAdaptor, line 80: parameters do not match oauth2Swift.renewAccessToken.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.