Skip to main content

Go

In this document you can find code examples for a self-hosted Ory Kratos 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 kratos-client.

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 Kratos Go SDK

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

Configuration

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

package main

import (
"context"

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

func main() {
configuration := client.NewConfiguration()
configuration.Servers = []client.ServerConfiguration{
{
URL: "http://127.0.0.1:4434", // Kratos Admin API
},
}
apiClient := client.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 the local hosted UI in your browser
  2. Sign up and create an account and log in
  3. Copy the ory_kratos_session 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"

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

func main() {
configuration := client.NewConfiguration()
configuration.Servers = []client.ServerConfiguration{
{
URL: "http://127.0.0.1:4433", // Kratos Public API
},
}
apiClient := client.NewAPIClient(configuration)
cookie := "ory_kratos_session=MTY0ODgyMTExN3xEdi1CQkFFQ180SUFBUkFCRUFBQVJfLUNBQUVHYzNSeWFXNW5EQThBRFhObGMzTnBiMjVmZEc5clpXNEdjM1J5YVc1bkRDSUFJRkZDVFVKbFNIcEJOalZyY0Vad1JEZ3dNMng1V0RsWlpEQlFXa3RoUjNJenzKCLhzCkox1OmvNJlKcqtWuNkSnPLrUgM6Ew2EMYksfg=="
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

The following code examples show how to use the IdentityAPI requests need to be authorized.

CreateIdentity and DeleteIdentity

package main

import (
"context"
"fmt"
"os"

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

func main() {
configuration := ory.NewConfiguration()
configuration.Servers = []ory.ServerConfiguration{
{
URL: "http://127.0.0.1:4434", // Kratos Admin API
},
}
apiClient := ory.NewAPIClient(configuration)
CreateIdentityBody := *ory.NewCreateIdentityBody(
"default",
map[string]interface{}{
"email": "[email protected]",
"name": map[string]string{
"first": "foo",
"last": "bar",
},
},
) // CreateIdentityBody | (optional)

createdIdentity, r, err := apiClient.IdentityApi.CreateIdentity(context.Background()).CreateIdentityBody(CreateIdentityBody).Execute()
if err != nil {
fmt.Fprintf(os.Stderr, "Error when calling `FrontendApi.CreateIdentity``: %v\n", err)
fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
}
// response from `CreateIdentity`: Identity
fmt.Fprintf(os.Stdout, "Created identity with ID: %v\n", createdIdentity.Id)
getIdentity, r, err := apiClient.IdentityApi.GetIdentity(context.Background(), createdIdentity.Id).Execute()
if err != nil {
fmt.Fprintf(os.Stderr, "Error when calling `FrontendApi.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)

r, err = apiClient.IdentityApi.DeleteIdentity(context.Background(), getIdentity.Id).Execute()
if err != nil {
fmt.Fprintf(os.Stderr, "Error when calling `FrontendApi.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 Kratos 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 the local hosted UI in your browser
  3. Sign up and create an account and log in
  4. Copy the ory cookie from the Application tab in your browser developer tools
  5. Add the cookie to the cUrl request below:
curl 'http://localhost:8080/ping' -b 'ory_kratos_session=<your-session-cookie-here>'
pong
package main

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

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

type kratosMiddleware struct {
ory *ory.APIClient
}

func NewMiddleware() *kratosMiddleware {
configuration := ory.NewConfiguration()
configuration.Servers = []ory.ServerConfiguration{
{
URL: "http://127.0.0.1:4434", // Kratos Admin API
},
}
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, "http://127.0.0.1:4455/login")
return
}
if !*session.Active {
c.Redirect(http.StatusMovedPermanently, "http://your_endpoint")
return
}
c.Next()
}
}
func (k *kratosMiddleware) validateSession(r *http.Request) (*ory.Session, error) {
cookie, err := r.Cookie("ory_kratos_session")
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 Kratos 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 the local hosted UI in your browser
  3. Sign up and create an account and log in
  4. Copy the ory cookie from the Application tab in your browser developer tools
  5. Add the cookie to the cUrl request below:
curl 'http://localhost:8080/ping' -b 'ory_kratos_session=<your-session-cookie-here>'
pong
package main

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

"github.com/labstack/echo/v4"

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

type kratosMiddleware struct {
ory *ory.APIClient
}

func NewMiddleware() *kratosMiddleware {
configuration := ory.NewConfiguration()
configuration.Servers = []ory.ServerConfiguration{
{
URL: "http://127.0.0.1:4433", // Kratos Public API
},
}
return &kratosMiddleware{
ory: ory.NewAPIClient(configuration),
}
}
func (k *kratosMiddleware) 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, "http://127.0.0.1:4455/login")
}
if !*session.Active {
return c.Redirect(http.StatusMovedPermanently, "http://your_endpoint")
}
return next(c)
}
}
func (k *kratosMiddleware) validateSession(r *http.Request) (*ory.Session, error) {
cookie, err := r.Cookie("ory_kratos_session")
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(":1323"))
}