Skip to main content

Ory Hydra Go

In this document you can find code examples for the Ory Hydra Go SDK.

The Ory Hydra Go SDK is generated using go-swagger.

danger

Don't consume the /oauth2/auth and /oauth2/token endpoints using this SDK. Use golang.org/x/oauth2. For more information visit the Using OAuth2 guide.

info

Missing an example? Please create a feature request and it will be added here.

You can find more auto-generated examples of SDK usage in the documentation hydra-client-go.

Installation

To install the Go SDK, run:

go get github.com/ory/hydra-client-go@<version-you-want>

Configuration

The following code example shows how to set up and configure Ory Hydra using the Go SDK:

package main

import (
client "github.com/ory/hydra-client-go"
)

func main() {
configuration := client.NewConfiguration()
configuration.Servers = []client.ServerConfiguration{
{
URL: "http://localhost:4445", // Admin API URL
},
}
// admin := client.NewAPIClient(configuration)
// admin.OAuth2Api.CreateOAuth2Client(...

configuration.Servers = []client.ServerConfiguration{
{
URL: "http://localhost:4445", // Public API URL
},
}

// hydraPublic := client.NewAPIClient(configuration)
// public.PublicApi.RevokeOAuth2Token(...
}

Making requests

The following code example shows how to make requests to the Ory Hydra Public API. In this example the request is used to create an OAuth 2.0 client:

package main

import (
"context"
"fmt"
"net/http"
"os"

client "github.com/ory/hydra-client-go"
)

func main() {
clientName := "example_client"
oAuth2Client := *client.NewOAuth2Client() // OAuth2Client |
oAuth2Client.SetClientId("example_client_id")
oAuth2Client.SetClientName(clientName)

configuration := client.NewConfiguration()
configuration.Servers = []client.ServerConfiguration{
{
URL: "http://localhost:4445", // Public API URL
},
}
apiClient := client.NewAPIClient(configuration)
resp, r, err := apiClient.OAuth2Api.CreateOAuth2Client(context.Background()).OAuth2Client(oAuth2Client).Execute()
if err != nil {
switch r.StatusCode {
case http.StatusConflict:
fmt.Fprintf(os.Stderr, "Conflict when creating oAuth2Client: %v\n", err)
default:
fmt.Fprintf(os.Stderr, "Error when calling `OAuth2Api.CreateOAuth2Client``: %v\n", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
}
}
// response from `CreateOAuth2Client`: OAuth2Client
fmt.Fprintf(os.Stdout, "Created client with name %s\n", resp.GetClientName())

limit := int64(20)
offset := int64(0)
clients, r, err := apiClient.OAuth2Api.ListOAuth2Clients(context.Background()).Limit(limit).Offset(offset).ClientName(clientName).Execute()
if err != nil {
fmt.Fprintf(os.Stderr, "Error when calling `OAuth2Api.ListOAuth2Clients``: %v\n", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
}
fmt.Fprintf(os.Stdout, "We have %d clients\n", len(clients))
fmt.Fprintf(os.Stdout, "First client name: %s\n", clients[0].GetClientName())

}

With Authentication

Some endpoints require basic authentication. The following code example shows how to make an authenticated request to the Ory Hydra Admin API:

package main

import (
"context"
"encoding/base64"
"fmt"
"net/http"

client "github.com/ory/hydra-client-go"
)

type BasicAuthTransport struct {
Username string
Password string
}

func (t BasicAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req.Header.Set("Authorization", fmt.Sprintf("Basic %s",
base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s",
t.Username, t.Password)))))
return http.DefaultTransport.RoundTrip(req)
}

func main() {
config := client.NewConfiguration()
config.Servers = []client.ServerConfiguration{
{
URL: "http://localhost:4445", // Admin API
},
}

c := client.NewAPIClient(config)
config.HTTPClient.Transport = BasicAuthTransport{Username: "foo", Password: "bar"}

req := c.OAuth2Api.GetOAuth2ConsentRequest(context.Background()).ConsentChallenge("consentChallenge_example")
fmt.Println(req.Execute())

}

Status codes and error handling

The following code example shows how to handle errors and status codes:

package main

import (
"context"
"fmt"
"net/http"
"os"

client "github.com/ory/hydra-client-go"
)

func main() {
consentChallenge := "consentChallenge_example" // string |

configuration := client.NewConfiguration()
configuration.Servers = []client.ServerConfiguration{
{
URL: "http://localhost:4445", // Admin API
},
}
apiClient := client.NewAPIClient(configuration)
resp, r, err := apiClient.OAuth2Api.GetOAuth2ConsentRequest(context.Background()).ConsentChallenge(consentChallenge).Execute()
if err != nil {
switch r.StatusCode {
case http.StatusNotFound:
// Accessing to response details
// cast err to *client.GenericOpenAPIError object first and then
// to your desired type
notFound, ok := err.(*client.GenericOpenAPIError).Model().(client.JsonError)
fmt.Println(ok)
fmt.Println(*notFound.ErrorDescription)
case http.StatusGone:

r, ok := err.(*client.GenericOpenAPIError).Model().(client.RequestWasHandledResponse)
fmt.Println(r, ok)
fmt.Println("It's gone")
default:
fmt.Fprintf(os.Stderr, "Error when calling `OAuth2Api.GetOAuth2ConsentRequest``: %v\n", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
}
}
// response from `GetConsentRequest`: ConsentRequest
fmt.Fprintf(os.Stdout, "Response from `OAuth2Api.GetOAuth2ConsentRequest`: %v\n", resp)
}

On every request

You may want to protect Ory Hydra using OAuth2 Access Tokens. In that case, you can enhance the SDK by using the OAuth2 Client:

package main

import (
"context"

client "github.com/ory/hydra-client-go"
"golang.org/x/oauth2/clientcredentials"
)

func main() {
config := client.NewConfiguration()
config.Servers = []client.ServerConfiguration{
{
URL: "http://localhost:4444", // Public API URL
},
}

creds := clientcredentials.Config{
TokenURL: "http://hydra.localhost:4444/oauth2/token",
ClientID: "my-client",
ClientSecret: "my-secret",
Scopes: []string{"scope-a", "scope-b"},
}
config.HTTPClient = creds.Client(context.TODO())
c := client.NewAPIClient(config)
req := c.PublicApi.RevokeOAuth2Token(context.TODO())
req.Execute()

}