Skip to content
Zero dependency library for generating a Mastercard API compliant OAuth signature.
Branch: master
Clone or download
Pull request Compare This branch is 37 commits ahead, 4 commits behind lukereichold:development.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
Example
MastercardOAuth1Signer.xcworkspace Restructured project Feb 20, 2019
MastercardOAuth1Signer Removed encoding from consumer key Feb 22, 2019
Resources
.gitignore
.travis.yml Defined env variable for Sonar scanner version May 13, 2019
LICENSE Updated LICENSE Feb 14, 2019
MastercardOAuth1Signer.podspec Bumped version number to 1.0.1 Apr 30, 2019
Podfile Restructured project Feb 20, 2019
README.md Clean-up Apr 24, 2019
xccov-to-sonarqube-generic.sh Enabled code coverage in app code Feb 13, 2019

README.md

oauth1-signer-swift

Table of Contents

Overview

Zero dependency library for generating a Mastercard API compliant OAuth signature.

Compatibility

Swift 4.2

References

Usage

Prerequisites

Before using this library, you will need to set up a project in the Mastercard Developers Portal.

As part of this set up, you'll receive credentials for your app:

  • A consumer key (displayed on the Mastercard Developer Portal)
  • A private request signing key (matching the public certificate displayed on the Mastercard Developer Portal)

Adding the Library to Your Project

MastercardOAuth1Signer is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'MastercardOAuth1Signer'

You can then import the framework from Swift:

import MastercardOAuth1Signer

Note: Use of this library as a pod requires Xcode 10 or later.

Loading the Signing Key

You can use the utility KeyProvider.swift to create a SecKey object representing your developer private key. For that, simply pass in a bundle path for your PKCS#12 key store along with its password:

let signingKey = KeyProvider.loadPrivateKey(fromPath: certificatePath, keyPassword: "<<PASSWORD>>")!

Creating the OAuth Authorization Header

OAuth.authorizationHeader

The method that does all the heavy lifting is OAuth.authorizationHeader(). You can call into it directly and as long as you provide the correct parameters, it will return a string that you can add into your request's Authorization header.

let header = try? OAuth.authorizationHeader(forUri: uri, method: method, payload: payloadString, consumerKey: consumerKey, signingPrivateKey: signingKey)

Example

To run the example project, first clone this repo and then pod install from the project directory.

Example usage:

let uri = URL(string: "https://sandbox.api.mastercard.com/service")!
let method = "GET"
let examplePayload: [String: String] = ["languageId": 1,
                                        "geographicId": 0]
let payloadJSON = (try? JSONSerialization.data(withJSONObject: examplePayload, options: [])) ?? Data()
let payloadString = String(data: payloadJSON, encoding: .utf8)

let consumerKey = "<insert consumer key from developer portal>"
let signingKey = "<initialize private key matching the consumer key>"

let header = try? OAuth.authorizationHeader(forUri: uri, method: method, payload: payloadString, consumerKey: consumerKey, signingPrivateKey: myPrivateKey)

let headers: HTTPHeaders = ["Authorization": header!,
                            "Accept": "application/json",
                            "Referer": "api.mastercard.com"]

Integrating with OpenAPI Generator API Client Libraries

OpenAPI Generator generates API client libraries from OpenAPI Specs. It provides generators and library templates for supporting multiple languages and frameworks.

OpenAPI generator for Swift 4 generates client libraries using Alamofire. To use MastercardOAuth1Signer in a generated client library, follow the below steps:

  1. Create a class extending RequestAdapter
  2. Implement the adapt: method with logic to compute and add the Authorization header to requests:
final class RequestAuthAdapter: RequestAdapter {
    func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
        var urlRequest = urlRequest
        let certificatePath = Bundle(for: type(of: self)).path(forResource: "<<FILENAME>>", ofType: "p12")
        let signingKey = KeyProvider.loadPrivateKey(fromPath: certificatePath!, keyPassword: "<<PASSWORD>>")!
        let consumerKey = "<<CONSUMER_KEY>>"
        var payloadString :String? = nil
        if urlRequest.httpBody != nil
        {
            payloadString = String.init(data: urlRequest.httpBody!, encoding: .utf8)
        }
        let header = try? OAuth.authorizationHeader(forUri: urlRequest.url!, method: urlRequest.httpMethod!, payload: payloadString, consumerKey: consumerKey, signingPrivateKey: signingKey)
        urlRequest.setValue(header!, forHTTPHeaderField: "Authorization")
        return urlRequest
    }
}
  1. Open the generated AlamofireImplementations.swift. Find the initialization of SessionManager and assign the RequestAuthAdapter to it:
let manager = createSessionManager()
manager.adapter = RequestAuthAdapter()

See also:

Authors

You can’t perform that action at this time.