SDKS

Go SDK

The WorkOS Go SDK provides your Go applications access to the WorkOS Audit Trail and SSO APIs.

Installation

You can install the SDK in your local environment by running:

Terminal

file_copy
go get -u github.com/workos-inc/workos-go

View the source on GitHub.


Configuration

To use the SDK you must first provide your API key from the Developer Dashboard.

You can do this one of two ways:

First, by declaring the environment variable WORKOS_API_KEY:

Terminal

file_copy
WORKOS_API_KEY="{secretKey}" ./app

Or, you can set it before your application starts:

Using the audittrail package

main.go

file_copy
package main

import "github.com/workos-inc/workos-go/audittrail"

func main() {
	audittrail.SetAPIKey("{secretKey}")
}

Using the sso package

main.go

file_copy
package main

import "github.com/workos-inc/workos-go/sso"

func main() {
  sso.Configure(
    "{secretKey}",
    "{projectId}",
    "{redirectURI}",
  )
}

SDK Structure

After installing and configuring WorkOS, it's helpful to be oriented with the SDK's layout. This SDK is organized into sseparate packages, one for each supported product:

  • audittrail
  • sso

Each of these packages has its own associated functions for interacting with WorkOS. Calling these functions takes the general form:

submodule.functionCall()

The audittrail Package

For further reference, check out the audittrail package.

audittrail.SetAPIKey(workosApiKey)

Configure your default client to publish audit trail events with the Publish function.

sso.setAPIKey() accepts one argument:

For example:

main.go

file_copy
package main

import "github.com/workos-inc/workos-go/audittrail"

func main() {
	audittrail.SetAPIKey("{secretKey}")
}

audittrail.Publish(context, audittrail.Event)

Publish a provided audit trail event.

audittrail.Publish() accepts two arguments:

  • context (Context) - package defining deadlines, cancellation signals, and other request-scoped values sent across boundaries and processes
  • audittrail.Event (struct) - a struct representing an audit trail event

audittrail.Event{} is defined:

audittrail.Event{} struct

file_copy
type Event struct {
    Action     string     `json:"action"`
    ActionType ActionType `json:"action_type"`
    ActorName  string     `json:"actor_name"`
    ActorID    string     `json:"actor_id"`
    Group      string     `json:"group"`
  
    // A key that ensures that single, unique event is not published multiple times.
    // Once the event is sent for the first time, the lock on the key expires
    // after 24 hours.
    //
    // An idempotency key is automatically generated if not set.
    IdempotencyKey string `json:"-"`
  
    // An IP address that locates event's origin.
    Location string `json:"location"`
  
    // The event metadata. It can't contain more than 50 keys, and a key can't
    // exceed 40 characters.
    Metadata Metadata `json:"metadata,omitempty"`
  
    // The time when the event occurred.
    //
    // Defaults to time.Now().
    OccurredAt time.Time `json:"occurred_at"`
  
    TargetName string `json:"target_name"`
    TargetID   string `json:"target_id"`
  }

audittrail.Event{} uses a couple of notable custom types:

  • type ActionType (string) - a type containing the related CRUD action associated with an audit trail event

It is defined as constants that enumerate each different action type:

type ActionType

file_copy
const (
    Create ActionType = "C"
    Read   ActionType = "R"
    Update ActionType = "U"
    Delete ActionType = "D"
  )
  • type Metadata (map[string]interface{}) - a location for storing key-value data that provide additional context surrounding your events. Any relevant information that would be helpful to you or to others viewing this event in the future should be stored here.

Do not store sensitive or personally identifiable information in the metadata field.

Valid values for the metadata field include the following primitive types:

  • string
  • bool
  • int, int8, int16, int32, int64
  • float32, float64
  • time.Time
  • err
  • JSON objects containing elements of the primitive types listed above

Good events contain all relevant, supporting information surrounding the event. Any information that could be used to inform future readers precisely what happened, how it happened, and when it happened should be included.

For more details on using the metadata attribute, check out the API Reference.

Altogether, publishing an audit trail event is implemented as follows:

main.go

file_copy
package main
  
  import "github.com/workos-inc/workos-go/pkg/audittrail"
  
  func main() {
    audittrail.SetAPIKey("{secretKey}")
  
    err := audittrail.Publish(context.Background(), audittrail.Event{
        Action:     "user.login_succeeded",
        ActionType: audittrail.Read,
        ActorName:  "[email protected]",
        ActorID:    "user_01DGZ0F97X0SXJB6D8KB8R0F7B",
        Group:      "dedicated.ai",
        Location:   "27.10.230.99",
        OccurredAt: time.Now(),
        TargetName: "[email protected]",
        TargetID:   "user_01DGZ0F97X0SXJB6D8KB8R0F7B",
    })
    if err != nil {
        // Handle error.
    }
  }

You can use the audittrail.NewEventWithHTTP function to automatically populate an event triggered by the result of an HTTP request.

And the event object published to the WorkOS audit trail will be:

JSON

file_copy
{
    "id": "evt_01DGZ0F9DXZJ312H8K0CKRJ64G",
    "group": "dedicated.ai",
    "location": "27.10.230.99",
    "action": "user.login_succeeded",
    "action_type": "R",
    "actor_name": "[email protected]",
    "actor_id": "user_01DGZ0F97X0SXJB6D8KB8R0F7B",
    "target_name": "[email protected]",
    "target_id": "user_01DGZ0F97X0SXJB6D8KB8R0F7B",
    "metadata": {},
    "occurred_at": "2020-08-14T05:04:19.960Z"
  }

The sso Package

For further reference, check out the SSO package.

sso.Configure(workosApiKey, projectID, redirectURI)

Configure your default client to initiate an authorization workflow using the GetAuthorizationURL, GetProfile and Login functions.

sso.Configure() accepts three arguments:

  • workosApiKey (string) - your API key, found in your Developer Dashboard.
  • projectID (string) — your application's WorkOS Project ID (ex. project_01JG3BCPTRTSTTWQR4VSHXGWCQ)
  • redirectURI (deprecated, string) — a callback URL where your application redirects the user-agent after an authorization code is granted (ex. workos.dev/callback)

For example:

main.go

file_copy
sso.Configure(
    "{secretKey}",
    "{projectId}",
    "https://workos.dev/callback",
  )

sso.Login(sso.GetAuthorizationURLOptions)

Generate an http.Handler to redirect the client to the appropriate login provider.

sso.Login() is configured with the authorization URL options contained in the sso.GetAuthorizationURLOptions{} struct. This struct's options are used by the sso.Login() handler to generate an authorization URL and redirect the client to the correct Identity Provider login screen. It accepts three fields:

  • domain (string) — the Enterprise's domain (e.g. example.com), optional with a provider parameter.
  • redirectURI (string) — a callback URL where your application redirects the user-agent after an authorization code is granted (ex. workos.dev/callback)
  • provider (optional, string) — optional parameter that specifies the type of Connection to authenticate with. If used, a user of any domain can be authenticated. Only GoogleOAuth is currently supported. Most commonly used for "Signup with Google" buttons.
  • state (optional, string) — optional unique identifier used to manage state across authorization requests (e.g. 1234zyx)

Example:

main.go

file_copy
sso.Login(sso.GetAuthorizationURLOptions{
    Domain: "workos.dev",
    RedirectURI: "{redirectURI}",
  })

And when implemented on your server's handler:

main.go

file_copy
http.Handle("/login", sso.Login(sso.GetAuthorizationURLOptions{
    Domain: "workos.dev",
    RedirectURI: "{redirectURI}",
  }))

sso.GetProfile(context, sso.GetProfileOptions)

Return the profile of an authorized user.

sso.GetProfile() accepts two arguments:

  • context (Context) - package defining deadlines, cancellation signals, and other request-scoped values sent across boundaries and processes
  • sso.GetProfileOptions (options) - struct used to configure the sso.GetProfile() function

The sso.GetProfileOptions{} struct accepts a single argument:

  • code (string) — an opaque string provided by the authorization server; will be exchanged for an Access Token when the user's profile is sent

For example:

main.go

file_copy
sso.GetProfile(context.Background(), sso.GetProfileOptions{
    Code:   r.URL.Query().Get("code"),
  })

And when implemented on your server's handler:

main.go

file_copy
http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
    profile, err := sso.GetProfile(context.Background(), sso.GetProfileOptions{
        Code:   r.URL.Query().Get("code"),
    })
    if err != nil {
        // Handle the error ...
        return
    }
  
    // Handle the profile ...
    fmt.Println(profile)
  })