Coder Social home page Coder Social logo

mastercard / oauth1-signer-go Goto Github PK

View Code? Open in Web Editor NEW
18.0 17.0 13.0 57 KB

Library for generating a Mastercard API compliant OAuth signature.

Home Page: https://developer.mastercard.com/platform/documentation/security-and-authentication/using-oauth-1a-to-access-mastercard-apis/

License: MIT License

Go 100.00%
golang mastercard openapi oauth1 oauth1a go

oauth1-signer-go's Introduction

oauth1-signer-go

Table of Contents

Overview

Library for Generating a Mastercard API compliant OAuth signature.

Compatibility

  • Go 1.20+

References

Versioning and Deprecation Policy

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)

Installation

import github.com/mastercard/oauth1-signer-go

Loading the Signing Key

A signingKey can be created by calling the utils.LoadSigningKey function:

import "github.com/mastercard/oauth1-signer-go/utils"

//…
signingKey, err := utils.LoadSigningKey(
                                    "<insert PKCS#12 key file path>", 
                                    "<insert key password>")
//…

Creating the OAuth Authorization Header

The function that does all the heavy lifting is OAuth.GetAuthorizationHeader. 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.

import "github.com/mastercard/oauth1-signer-go"

//…
consumerKey := "<insert consumer key>"
url, _ := url.Parse("https://sandbox.api.mastercard.com/service")
method := "POST"
payload := "<insert payload>"
authHeader, err := oauth.GetAuthorizationHeader(url, method, payload, consumerKey, signingKey)
//…

Signing HTTP Request

Alternatively, you can use helper function for http request.

Usage briefly described below, but you can also refer to the test package for examples.

import "github.com/mastercard/oauth1-signer-go"

//…
payload := "<insert payload>"
request, _ := http.NewRequest("POST", "https://sandbox.api.mastercard.com/service", payload)
signer := &oauth.Signer{
    ConsumerKey: consumerKey,
    SigningKey:  signingKey,
}
err = signer.Sign(request)
//…

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.

The github.com/mastercard/oauth1-signer-go/interceptor package provides you function for http request interception you can use when configuring your API client. This function takes care of adding the correct Authorization header before sending the request.

Generators currently supported:

Go

OpenAPI Generator

Client libraries can be generated using the following command:

openapi-generator-cli generate -i openapi-spec.yaml -g go -o out

See also:

Usage of the github.com/mastercard/oauth1-signer-go/interceptor
import "github.com/mastercard/oauth1-signer-go/interceptor"

//…
configuration := openapi.NewConfiguration()
configuration.BasePath = "https://sandbox.api.mastercard.com"
httpClient, _ := interceptor.GetHttpClient("<insert consumer key>", "<insert PKCS#12 key file path>", "<insert key password>")
configuration.HTTPClient = httpClient
apiClient := openapi.NewAPIClient(configuration)

response, err = apiClient.SomeApi.doSomething()
//…

oauth1-signer-go's People

Contributors

bhargavmodi avatar danny-gallagher avatar dependabot[bot] avatar ech0s7r avatar jaaufauvre avatar joseph-neeraj avatar kaischwanke avatar

Stargazers

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

Watchers

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

oauth1-signer-go's Issues

Masterpass

I use this library to signing requests for Masterpass, but I did some changes in code (sha1 and encoding).
How can I push my branch for review?

Request body empty after reading it

Bug Report Checklist

  • Have you provided a code sample to reproduce the issue?
  • Have you tested with the latest release to confirm the issue still exists?
  • Have you searched for related issues/PRs?
  • What's the actual output vs expected output?

Description
Reading the request body in the sign function leaves it empty

To Reproduce
Test to illustrate the behaviour:

func TestBodyRestore(t *testing.T) {
	originalBody := "{\"foo\": \"bar\"}"
	getRequest, _ := http.NewRequest("GET", "", strings.NewReader(originalBody))
	bodyHash := getSignedBodyHash(getRequest)
	bodyHash2 := getSignedBodyHash(getRequest)
	if bodyHash != bodyHash2 {
		t.Errorf("Body hashes sould be the same")
	}
}

func getSignedBodyHash(r *http.Request) string {
	signer := &oauth.Signer{ConsumerKey: consumerKey, SigningKey: signingKey}
	_ = signer.Sign(r)
	authHeader := r.Header["Authorization"][0]
	return extractBodyHash(authHeader)
}

func extractBodyHash(input string) string {
	regexPattern := `oauth_body_hash="([^"]+)"`
	re := regexp.MustCompile(regexPattern)

	match := re.FindStringSubmatch(input)
	if len(match) == 0 {
		panic("value not found")
	}
	return match[1]
}

Expected behavior
The request body should remain intact after reading it

Additional context
The request body in Go is a ReadCloser interface. Once you read the content, the buffer will be empty.
I had forgotten about that behaviour in my previous PR

Related issues/PRs
PR #10 created

Signer not using latest request body

Bug Report Checklist

  • Have you provided a code sample to reproduce the issue?
  • Have you tested with the latest release to confirm the issue still exists?
  • Have you searched for related issues/PRs?
  • What's the actual output vs expected output?

Unit test to reproduce the issue:

func TestMiddlewareIssue(t *testing.T) {
	originalBody := "{\"foo\": \"bar\"}"
	getRequest, _ := http.NewRequest("GET", "", strings.NewReader(originalBody))
	// second request, same body as the first one
	getRequestModified, _ := http.NewRequest("GET", "", strings.NewReader(originalBody))
	// faking a middleware function, which alters the request body (i.e. encrypting it)
	getRequestModified.Body = io.NopCloser(bytes.NewReader([]byte("{\"foo\": \"baz\"}")))
	bodyHash := getSignedBodyHash(getRequest)
	bodyHashModified := getSignedBodyHash(getRequestModified)
	// we would expect the oauth_body_hash values to be different, since both request have different payloads
	if bodyHash == bodyHashModified {
		t.Errorf("The oauth_body_hash should be different, since the request bodies were different")
	}
}

func getSignedBodyHash(r *http.Request) string {
	signer := &oauth.Signer{ConsumerKey: consumerKey, SigningKey: signingKey}
	_ = signer.Sign(r)
	authHeader := r.Header["Authorization"][0]
	return extractBodyHash(authHeader)
}

func extractBodyHash(input string) string {
	regexPattern := `oauth_body_hash="([^"]+)"`
	re := regexp.MustCompile(regexPattern)

	match := re.FindStringSubmatch(input)
	if len(match) == 0 {
		panic("value not found")
	}
	return match[1]
}

Description
The signing function on occasion might be using an outdated payload

To Reproduce
Create a http request, change the request body. The sign function will not use the updated body

Expected behavior
The latest version of the request body should be used

Additional context
This happens because of the way the http.request getBody function works. It will keep a snapshot of the initially created request.
https://github.com/golang/go/blob/master/src/net/http/request.go#L913

Suggest a fix/enhancement
PR created: #6

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.