Skip to main content

Go

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

info

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

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

Installation

If you are starting from scratch, first set up a new Go project

mkdir myproject
cd myproject
go mod init myproject

Install the Ory Go SDK

go get github.com/ory/client-go

Configuration

The following code example shows how to connect to Ory Identities using the Go SDK:

package main

import (
"context"

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

func main() {
configuration := ory.NewConfiguration()
configuration.Servers = []ory.ServerConfiguration{
{
URL: "https://playground.projects.oryapis.com/", // Ory Identities API
},
}
apiClient := ory.NewAPIClient(configuration)
// resp, r, err := apiClient.FrontendApi.ToSession(context.Background()).Cookie("ory_Kratos_session").Execute()
}

Use Frontend API

The following code examples show how to use the FrontendApi.

toSession

In this example you make a toSession call to check if the session is active.

  1. Open the Ory Identities Playground in your browser
  2. Open Sign Up to create an account and log in
  3. Copy the ory_session_playground cookie from the Application tab in your browser developer tools
  4. Add the cookie value in cookie
  5. Run the example and send the request with go run main.go

The response should look like this.

Traits  map[email:youremail@example.com]
package main

import (
"context"
"fmt"
"os"

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

func main() {
proxyPort := os.Getenv("PROXY_PORT")
if proxyPort == "" {
proxyPort = "4000"
}
configuration := ory.NewConfiguration()
configuration.Servers = ory.ServerConfigurations{{URL: fmt.Sprintf("http://localhost:%s/.ory", proxyPort)}}
apiClient := ory.NewAPIClient(configuration)
cookie := "ory_session_playground=<your-session-cookie-here>"
resp, r, err := apiClient.FrontendApi.ToSession(context.Background()).Cookie(cookie).Execute()
if err != nil {
fmt.Fprintf(os.Stderr, "Error when calling `FrontendApi.ToSession``: %v\n", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
}
// response from `ToSession`: Session
fmt.Fprintf(os.Stdout, "Traits %v\n", resp.Identity.Traits)
}

Use Identity Management API

To use the Identity Management API IdentityAPI requests need to be authorized.

  • Create a free Developer project with the Ory CLI or Ory Console ory create project --name "Ory IdentityAPI Example"
  • Create a new API key and export it export ORY_API_KEY=<your-api-key>
  • Run the example with go run main.go

CreateIdentity and DeleteIdentity

With this example you create an identity and delete it.

package main

import (
"context"
"fmt"
"os"

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

// Use this context to access Ory APIs which require an Ory API Key.
var oryAuthedContext = context.WithValue(context.Background(), ory.ContextAccessToken, os.Getenv("ORY_API_KEY"))

func main() {
configuration := ory.NewConfiguration()
configuration.Servers = []ory.ServerConfiguration{
{
URL: "https://<your-ory-project-slug>.projects.oryapis.com", // Ory Network Project URL
},
}
apiClient := ory.NewAPIClient(configuration)
CreateIdentityBody := *ory.NewCreateIdentityBody(
"preset://basic",
map[string]interface{}{
"email": "foo@example.com",
"name": map[string]string{
"first": "foo",
"last": "bar",
},
},
) // CreateIdentityBody | (optional)

createdIdentity, r, err := apiClient.IdentityApi.CreateIdentity(oryAuthedContext).CreateIdentityBody(CreateIdentityBody).Execute()
if err != nil {
fmt.Fprintf(os.Stderr, "Error when calling `IdentityApi.CreateIdentity``: %v\n", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
}
// response from `IdentityApi.CreateIdentity`: Identity
fmt.Fprintf(os.Stdout, "Created identity with ID: %v\n", createdIdentity.Id)
getIdentity, r, err := apiClient.IdentityApi.GetIdentity(oryAuthedContext, createdIdentity.Id).Execute()
if err != nil {
fmt.Fprintf(os.Stderr, "Error when calling `IdentityApi.GetIdentity``: %v\n", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
}
fmt.Fprintf(os.Stdout, "Email for identity with id %v. Traits %v\n", createdIdentity.Id, getIdentity.Traits)

// Delete the identity that was just created (optional)
r, err = apiClient.IdentityApi.DeleteIdentity(oryAuthedContext, getIdentity.Id).Execute()
if err != nil {
fmt.Fprintf(os.Stderr, "Error when calling `IdentityApi.DeleteIdentity``: %v\n", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
}
fmt.Println("Successfully Removed identity")

}

Gin middleware

The following code example shows how to use the Ory Identities Go SDK with the Gin Web Framework. Follow the instructions in the README to install Gin.

  1. Run the Gin middleware with go run main.go
  2. Open the Ory Identities Playground in your browser
  3. Open Sign Up to create an account and log in
  4. Copy the ory_session_playground cookie from the Application tab in your browser developer tools
  5. Add the cooie to the cUrl request below:
curl 'http://localhost:8080/ping' -b 'ory_session_playground=<your-session-cookie-here>'
pong
package main

import (
"context"
"errors"
"net/http"

"github.com/gin-gonic/gin"
ory "github.com/ory/client-go"
)

type kratosMiddleware struct {
ory *ory.APIClient
}

func NewMiddleware() *kratosMiddleware {
configuration := ory.NewConfiguration()
configuration.Servers = []ory.ServerConfiguration{
{
URL: "https://playground.projects.oryapis.com", // Ory Network Project URL
},
}
return &kratosMiddleware{
ory: ory.NewAPIClient(configuration),
}
}
func (k *kratosMiddleware) Session() gin.HandlerFunc {
return func(c *gin.Context) {
session, err := k.validateSession(c.Request)
if err != nil {
c.Redirect(http.StatusMovedPermanently, "https://playground.projects.oryapis.com/ui/login") // Ory Identities Login URL
return
}
if !*session.Active {
c.Redirect(http.StatusMovedPermanently, "http://example.com") // Your Application URL
return
}
c.Next()
}
}
func (k *kratosMiddleware) validateSession(r *http.Request) (*ory.Session, error) {
cookie, err := r.Cookie("ory_session_playground")
if err != nil {
return nil, err
}
if cookie == nil {
return nil, errors.New("no session found in cookie")
}
resp, _, err := k.ory.FrontendApi.ToSession(context.Background()).Cookie(cookie.String()).Execute()
if err != nil {
return nil, err
}
return resp, nil
}
func main() {

r := gin.Default()
k := NewMiddleware()

r.Use(k.Session())
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

Echo middleware

The following code example shows how to use Ory Identities Go SDK with the Echo framework. Follow the instructions to install Echo.

  1. Run the Echo middleware with go run main.go
  2. Open the Ory Identities Playground in your browser
  3. Open Sign Up to create an account and log in
  4. Copy the ory_session_playground cookie from the Application tab in your browser developer tools
  5. Add the cooie to the cUrl request below:
curl 'http://localhost:3000/hello' -b 'ory_session_playground=<your-session-cookie-here>'
Hello World
package main

import (
"context"
"errors"
"net/http"

"github.com/labstack/echo/v4"

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

type oryMiddleware struct {
ory *ory.APIClient
}

func NewMiddleware() *oryMiddleware {
configuration := ory.NewConfiguration()
configuration.Servers = []ory.ServerConfiguration{
{
URL: "https://playground.projects.oryapis.com", // Ory Network Project URL
},
}
return &oryMiddleware{
ory: ory.NewAPIClient(configuration),
}
}
func (k *oryMiddleware) Session(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
session, err := k.validateSession(c.Request())
if err != nil {
return c.Redirect(http.StatusMovedPermanently, "https://playground.projects.oryapis.com/ui/login")
}
if !*session.Active {
return c.Redirect(http.StatusMovedPermanently, "https://example.com")
}
return next(c)
}
}
func (k *oryMiddleware) validateSession(r *http.Request) (*ory.Session, error) {
cookie, err := r.Cookie("ory_session_playground")
if err != nil {
return nil, err
}
if cookie == nil {
return nil, errors.New("no session found in cookie")
}
resp, _, err := k.ory.FrontendApi.ToSession(context.Background()).Cookie(cookie.String()).Execute()
if err != nil {
return nil, err
}
return resp, nil
}
func main() {

k := NewMiddleware()
e := echo.New()
e.Use(k.Session)
e.GET("/hello", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})
e.Logger.Fatal(e.Start(":3000"))
}