Skip to content

Instantly share code, notes, and snippets.

@tmclnk
Last active December 8, 2022 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmclnk/97136177da200bff2eaa44edd84fb98b to your computer and use it in GitHub Desktop.
Save tmclnk/97136177da200bff2eaa44edd84fb98b to your computer and use it in GitHub Desktop.
Golang Machine to Machine OAuth
package main
import (
"context"
"fmt"
"golang.org/x/oauth2"
"golang.org/x/oauth2/clientcredentials"
"io/ioutil"
"os"
)
/*
* This app demonstrates a machine-to-machine ("two-legged") auth flow.
*
* We have a "Resource Server", https://spring.users.runpaste.com/. This Resource Server
* is responsible for User Profiles, and has some scopes that it checks for like
* "userprofile.edit". The resource server is registered in CloudEntity with the scopes
* it exposes.
*
* In order for our application to consume services from the Resource Server, it gets registered
* as a "Service" Client in CloudEntity. The client must be given access to the Scopes
* exposed by the Resource server, e.g. userprofile.edit and userprofile.view.
*
* This client just needs a token url, client-id, and client-secret in order to make calls against the resource
* server.
*
* See https://auth0.com/blog/using-m2m-authorization/
*/
func main() {
fmt.Println("Demonstrating machine-to-machine authorization flow.")
ctx := context.Background()
// We register this application as a "Client" in CloudEntity (or Keycloak, or Okta, or...).
// The client-id and client-secret are provided.
conf := clientcredentials.Config{
ClientID: "",
ClientSecret: "",
TokenURL: "https://dmsi-poc.us.authz.cloudentity.io/dmsi-poc/spring/oauth2/token",
Scopes: []string{"userprofile.edit", "userprofile.view"},
EndpointParams: nil,
AuthStyle: oauth2.AuthStyleInParams, // send client_id and client_secret as a form post
}
fmt.Printf("Using client_id %s\n", conf.ClientID)
// The library gives us a *http.Client, which encapsulates the work of performing
// the client-credentials flow to get an access token.
client := conf.Client(ctx)
// The Resource Server is configured to receive access tokens.
resp, err := client.Get("https://spring.users.runpaste.com/users/123")
if err != nil {
fmt.Fprintf(os.Stderr, "%s ", err.Error())
os.Exit(1)
} else if resp.StatusCode != 200 {
fmt.Fprintf(os.Stderr, "Status Code %s ", resp.StatusCode)
os.Exit(1)
}
// Dump the results to stdout
bytes, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(bytes))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment