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

Frontend API

The following code examples show how to use the Frontend API frontend. These endpoints are used by frontend applications (e.g. Single-Page-App, Native Apps, Server Apps, ...) to manage a user's own profile. There are two types of flows: native flows and browser flows. Native flows are used by API clients. Browser flows are used by browser clients. Read the Browser vs. native apps document and the Self-service flows overview to learn more.

Browser clients

API clients

Create login flow

Create a login flow for API clients such as mobile devices or native applications. For browser clients use CreateBrowserLoginFlow.

login.go
package frontend

import (
"context"
"fmt"
"os"

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func CreateLogin(ctx context.Context) (*client.LoginFlow, error) {
flow, _, err := ory.FrontendApi.CreateNativeLoginFlow(ctx).Execute()
if err != nil {
return nil, err
}

return flow, nil
}

Create registration flow

Create a registration flow for API clients such as mobile devices or native applications. For browser clients use createBrowserLoginFlow.

login.go
package frontend

import (
"context"
"fmt"
"os"

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func CreateRegisteration(ctx context.Context) (*client.RegistrationFlow, error) {
flow, _, err := ory.FrontendApi.CreateNativeRegistrationFlow(ctx).Execute()
if err != nil {
return nil, err
}

return flow, nil
}

Create recovery flow

Create a recovery flow for API clients such as mobile devices or native applications. For browser clients use createBrowserRecoveryFlow.

login.go
package frontend

import (
"context"
"fmt"
"os"

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func CreateRecovery(ctx context.Context) (*client.RecoveryFlow, error) {
flow, _, err := ory.FrontendApi.CreateNativeRecoveryFlow(ctx).Execute()
if err != nil {
return nil, err
}

return flow, nil
}

Create verification flow

Create a verification flow for API clients such as mobile devices or native applications. For browser clients use createBrowserRecoveryFlow.

login.go
package frontend

import (
"context"
"fmt"
"os"

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func CreateVerification(ctx context.Context) (*client.VerificationFlow, error) {
flow, _, err := ory.FrontendApi.CreateNativeVerificationFlow(ctx).Execute()
if err != nil {
return nil, err
}

return flow, nil
}

Get registration flow

Get a registration flow.

login.go
package frontend

import (
"context"
"fmt"
"os"

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func GetRegistration(ctx context.Context, flowId string) (*client.RegistrationFlow, error) {
flow, _, err := ory.FrontendApi.GetRegistrationFlow(ctx).Id(flowId).Execute()
if err != nil {
return nil, err
}

return flow, nil
}

Get recovery flow

Get a recovery flow.

login.go
package frontend

import (
"context"
"fmt"
"os"

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func GetRecovery(ctx context.Context, flowId string) (*client.RecoveryFlow, error) {
flow, _, err := ory.FrontendApi.GetRecoveryFlow(ctx).Id(flowId).Execute()
if err != nil {
return nil, err
}

return flow, nil
}

Get verification flow

Get a verification flow.

login.go
package frontend

import (
"context"
"fmt"
"os"

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func GetVerification(ctx context.Context, flowId string) (*client.VerificationFlow, error) {
flow, _, err := ory.FrontendApi.GetVerificationFlow(ctx).Id(flowId).Execute()
if err != nil {
return nil, err
}

return flow, nil
}

Submit login flow

To submit or complete a login flow you need to call the updateLoginFlow endpoint.

login.go
package frontend

import (
"context"
"fmt"
"os"

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func SubmitLogin(ctx context.Context, flowId string, body client.UpdateLoginFlowBody) (*client.SuccessfulNativeLogin, error) {
flow, _, err := ory.FrontendApi.UpdateLoginFlow(ctx).Flow(flowId).UpdateLoginFlowBody(body).Execute()
if err != nil {
return nil, err
}

return flow, nil
}

Submit registration flow

To submit or complete a registration flow you need to call the updateRegistrationFlow endpoint.

login.go
package frontend

import (
"context"
"fmt"
"os"

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func SubmitRegistration(ctx context.Context, flowId string, body client.UpdateRegistrationFlowBody) (*client.SuccessfulNativeRegistration, error) {
flow, _, err := ory.FrontendApi.UpdateRegistrationFlow(ctx).Flow(flowId).UpdateRegistrationFlowBody(body).Execute()
if err != nil {
return nil, err
}

return flow, nil
}

Submit recovery flow

To submit or complete a recovery flow you need to call the updateRecoveryFlow endpoint.

login.go
package frontend

import (
"context"
"fmt"
"os"

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func SubmitRecovery(ctx context.Context, flowId string, body client.UpdateRecoveryFlowBody) (*client.RecoveryFlow, error) {
flow, _, err := ory.FrontendApi.UpdateRecoveryFlow(ctx).Flow(flowId).UpdateRecoveryFlowBody(body).Execute()
if err != nil {
return nil, err
}

return flow, nil
}

Submit verification flow

To submit or complete a recovery flow you need to call the updateVerificationFlow endpoint.

login.go
package frontend

import (
"context"
"fmt"
"os"

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func SubmitVerification(ctx context.Context, flowId string, body client.UpdateVerificationFlowBody) (*client.VerificationFlow, error) {
flow, _, err := ory.FrontendApi.UpdateVerificationFlow(ctx).Flow(flowId).UpdateVerificationFlowBody(body).Execute()
if err != nil {
return nil, err
}

return flow, nil
}

Browser - check who the current HTTP session belongs to

This example uses 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]
login.go
package frontend

import (
"context"
"fmt"
"os"

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

func whoami() {
proxyPort := os.Getenv("PROXY_PORT")
if proxyPort == "" {
proxyPort = "4000"
}
cfg := ory.NewConfiguration()
cfg.Servers = ory.ServerConfigurations{{URL: fmt.Sprintf("http://localhost:%s/.ory", proxyPort)}}
apiClient := ory.NewAPIClient(cfg)
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)
}

Native - check who the current HTTP session belongs to

This example uses toSession call to check if the session is active.

login.go
package frontend

import (
"context"
"fmt"
"os"

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func CheckSession(ctx context.Context, sessionToken string) (session *client.Session, err error) {
session, _, err = ory.FrontendApi.ToSession(ctx).
XSessionToken(sessionToken).
Execute()
if err != nil {
// error revoking the session, for example due to expired token provided
return nil, err
}

return session, nil
}

Get active sessions

Get all active sessions for the current user.

login.go
package frontend

import (
"context"
"fmt"
"os"

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func GetActiveSessions(ctx context.Context, sessionToken string) ([]client.Session, error) {
// Page and Per Page parameters are optional
activeSessions, _, err := ory.FrontendApi.ListMySessions(ctx).
XSessionToken(sessionToken).
Page(1).
PerPage(10).
Execute()
if err != nil {
// error fetching active sessions, for example due to expired session token
return nil, err
}

return activeSessions, nil
}

Perform logout flow

Use performNativeLogout to log out the current user for API clients such as mobile devices or native applications. For browser clients create a logout URL using createBrowserLogoutFlow. .

login.go

package frontend

import (
"context"
"fmt"
"os"

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func Logout(ctx context.Context, sessionToken string) error {
_, err := ory.FrontendApi.PerformNativeLogout(ctx).
PerformNativeLogoutBody(*client.NewPerformNativeLogoutBody(sessionToken)).
Execute()
if err != nil {
return err
}
// Logout was successful

return nil
}

Disable session

Revoke a specific session for the current user.

login.go
package frontend

import (
"context"
"fmt"
"os"

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func RevokeSession(ctx context.Context, sessionToken string, sessionToRevokeId string) error {
_, err := ory.FrontendApi.DisableMySession(ctx, sessionToRevokeId).
XSessionToken(sessionToken).
Execute()
if err != nil {
// error revoking the session, for example due to expired token provided
return err
}

return nil
}

Disable all other sessions

Revoke all other sessions for the current user.

login.go
package frontend

import (
"context"
"fmt"
"os"

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func RevokeOtherSessions(ctx context.Context, sessionToken string) (*client.DeleteMySessionsCount, error) {
revokedSessionsCount, _, err := ory.FrontendApi.DisableMyOtherSessions(ctx).
XSessionToken(sessionToken).
Execute()
if err != nil {
// error revoking the sessions, for example due to expired token provided
return nil, err
}

return revokedSessionsCount, nil
}

Identity API

To use the Identity Management API identity 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

Create and delete identity

With this example you create an identity and delete it.

create-delete-identity.go
package identity

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")

}

Get identity

Get an identity by its ID. You can optionally include credentials, in this example social sign in connections.

state.go

package main

import (
"context"
"fmt"
"github.com/ory/client-go"
"os"
)

var ory *client.APIClient
var authed = context.WithValue(context.Background(), client.ContextAccessToken, os.Getenv("ORY_API_KEY"))

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func getTokens(identityId string) (cl client.IdentityCredentials, err error) {
identity, _, err := ory.IdentityApi.
GetIdentity(authed, identityId).
IncludeCredential([]string{"oidc"}).Execute()
if err != nil {
return cl, err
}
return (*identity.Credentials)["oidc"], nil
}

Patch identity

Patch an identity. In this example this is used to set the identity state.

state.go

package identity

import (
"context"
"fmt"
"os"

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

var authed = context.WithValue(context.Background(), client.ContextAccessToken, os.Getenv("ORY_API_KEY"))

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func setState(identityId string, state string) (err error) {
_, _, err = ory.IdentityApi.
PatchIdentity(authed, identityId).
JsonPatch([]client.JsonPatch{{Op: "replace", Path: "/state", Value: state}}).Execute()
return err
}

Delete session

Delete a specific session.

login.go
package session

import (
"context"
)

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func DisableSession(ctx context.Context, sessionId string) (err error) {
_, err = ory.IdentityApi.DisableSession(ContextWithToken(ctx), sessionId).
Execute()
return err
}

Delete sessions

Delete all sessions for a user.

login.go
package session

import (
"context"
"fmt"
"os"

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func DisableAndDeleteSessions(ctx context.Context, identityId string) (err error) {
_, err = ory.IdentityApi.DeleteIdentitySessions(ContextWithToken(ctx), identityId).
Execute()
return err
}

Get session

Get a specifc session.

login.go
package session

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func GetSession(ctx context.Context, sessionId string, expandOptions []string) (session *client.Session, err error) {
session, _, err = ory.IdentityApi.GetSession(ContextWithToken(ctx), sessionId).
Expand(expandOptions).
Execute()

if err != nil {
return nil, err
}

return session, err
}

Get sessions

Get all sessions for all users.

login.go
package session

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func GetSessions(ctx context.Context, pageToken string, perPage int64) (sessions []client.Session, err error) {
sessions, _, err = ory.IdentityApi.ListSessions(ContextWithToken(ctx)).
PageToken(pageToken). // Optional - token id
PageSize(perPage). // Optional - number of sessions per page
Active(true). // Optional - used to filter result for active or inactive sessions; not setting this returns all sessions
Execute()

if err != nil {
return nil, err
}

return sessions, err
}

Refresh session

Extend a session.

login.go
package session

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

type oryMiddleware struct {
ory *ory.APIClient
}

func init() {
cfg := client.NewConfiguration()
cfg.Servers = client.ServerConfigurations{
{URL: fmt.Sprintf("https://%s.projects.oryapis.com", os.Getenv("ORY_PROJECT_SLUG"))},
}

ory = client.NewAPIClient(cfg)
}

func RefreshSession(ctx context.Context, sessionId string) (session *client.Session, err error) {
session, _, err = ory.IdentityApi.ExtendSession(ContextWithToken(ctx), sessionId).
Execute()

if err != nil {
return nil, err
}

return session, err
}

Go frameworks

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
state.go
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 {
cfg := ory.NewConfiguration()
cfg.Servers = []ory.ServerConfiguration{
{
URL: "https://playground.projects.oryapis.com", // Ory Network Project URL
},
}
return &kratosMiddleware{
ory: ory.NewAPIClient(cfg),
}
}
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
state.go
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 {
cfg := ory.NewConfiguration()
cfg.Servers = []ory.ServerConfiguration{
{
URL: "https://playground.projects.oryapis.com", // Ory Network Project URL
},
}
return &oryMiddleware{
ory: ory.NewAPIClient(cfg),
}
}
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"))
}