Session management
Sessions can be managed by:
- The user who owns the session through self-service endpoints
- System administrators through administrative endpoints
Self-service
Self-service session management allows users to manage their accounts on their own, without any administrative intervention. Each user can manage only the sessions tied to their accounts.
When performing these operations, remember to include the Ory Session Cookie in the requests. When calling the endpoints from a proxy or middleware, make sure to forward the cookies sent to the proxy/middleware. When calling these endpoints as AJAX calls, make sure to include credentials and configure CORS properly.
Listing all active sessions
You can show users a list of all of their active sessions using the session listing API from the SDK. The API returns a paginated response. Optional parameters allow to get a specific page and define the number of items shown on a single page.
You can use this call to build a user interface (UI) that shows users their active sessions.
- Go
- TypeScript
- React
package main
import (
"context"
"fmt"
"github.com/ory/client-go"
"os"
)
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
}
import { Configuration, FrontendApi } from "@ory/client"
const frontend = new FrontendApi(
new Configuration({
basePath: `https://${process.env.ORY_PROJECT_SLUG}.projects.oryapis.com`,
}),
)
export async function getSessions(sessionId: string, token: string) {
return await frontend.listMySessions({
xSessionToken: token,
page: 1, // optional parameter
perPage: 10, // optional parameter
})
}
import { Configuration, FrontendApi, Session } from "@ory/client"
import { useEffect, useState } from "react"
const ory = new FrontendApi(
new Configuration({
basePath: "http://localhost:4000", // Use your local Ory Tunnel URL
baseOptions: {
withCredentials: true,
},
}),
)
export function MySessions() {
const [sessions, setSessions] = useState<Session[]>([])
useEffect(() => {
ory
.listMySessions({
page: 1,
perPage: 10,
})
.then((res) => {
setSessions(res.data)
})
.catch((err) => {
// Couldn't fetch active sessions
// This might occur if the current session has expired
})
}, [])
if (!sessions) {
return "Loading"
}
return (
<table>
<tr>
<th>Session ID</th>
<th>Expires at</th>
<th>Authenticated at</th>
</tr>
{sessions.length > 0 ? (
sessions.map((session) => (
<tr id={session.id}>
<td>{session.id}</td>
<td>{session.expires_at || ""}</td>
<td>{session.authenticated_at || ""}</td>
</tr>
))
) : (
<tr>
<td>No active sessions.</td>
</tr>
)}
</table>
)
}
Revoking a specific session
You can revoke specific sessions using the revoke session API. This allows users to log out from their account on different devices or terminate sessions they don't recognize and suspect of malicious activity.
Sessions revoked by users are not deleted from the system. Instead, they become inactive. Only administrators can delete sessions using the administrative endpoints.
This API can only revoke sessions other than the current session. To revoke the current session, use the self-service logout.
- Go
- TypeScript
- React
package main
import (
"context"
"fmt"
"github.com/ory/client-go"
"os"
)
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
}
import { Configuration, FrontendApi } from "@ory/client"
const frontend = new FrontendApi(
new Configuration({
basePath: `https://${process.env.ORY_PROJECT_SLUG}.projects.oryapis.com`,
}),
)
export async function revokeSession(sessionId: string, token: string) {
return await frontend.disableMySession({
id: sessionId,
xSessionToken: token,
})
}
import { Configuration, FrontendApi } from "@ory/client"
const ory = new FrontendApi(
new Configuration({
basePath: "http://localhost:4000", // Use your local Ory Tunnel URL
baseOptions: {
withCredentials: true,
},
}),
)
// Example of a modal component
export function RevokeSession(sessionId: string) {
const handleRevokeSession = async () => {
try {
await ory.disableMySession({
id: sessionId,
})
} catch (error) {
// The session could not be revoked
// This might occur if the current session has expired or if the sessionId provided was invalid
}
// Session was revoked successfully
}
return (
<button onClick={handleRevokeSession}>Revoke Session {sessionId}</button>
)
}
Revoking all other sessions
To allow users to revoke all sessions other than the currently active one, use the revoke sessions API. Sessions revoked by users are not deleted from the system. Instead, they become inactive.
Only administrators can delete sessions using the administrative endpoints.
This API can only revoke sessions other than the current session. To revoke the current session, use the self-service logout.
- Go
- TypeScript
- React
package main
import (
"context"
"fmt"
"github.com/ory/client-go"
"os"
)
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, sessionToRevokeId 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
}
import { Configuration, FrontendApi } from "@ory/client"
const frontend = new FrontendApi(
new Configuration({
basePath: `https://${process.env.ORY_PROJECT_SLUG}.projects.oryapis.com`,
}),
)
export async function revokeSession(sessionId: string, token: string) {
return await frontend.disableMyOtherSessions({
xSessionToken: token,
})
}
import { Configuration, FrontendApi } from "@ory/client"
const ory = new FrontendApi(
new Configuration({
basePath: "http://localhost:4000", // Use your local Ory Tunnel URL
baseOptions: {
withCredentials: true,
},
}),
)
export function RevokeOtherSessions() {
const handleRevokeOtherSessions = async () => {
try {
await ory.disableMyOtherSessions()
} catch (error) {
// The sessions could not be revoked
// This might occur if the current session has expired
}
// Sessions were revoked successfully
}
return (
<button onClick={handleRevokeOtherSessions}>Revoke other sessions</button>
)
}
Administrative
Administrative session management allows privileged users to manage all sessions in the system.
You must use a personal access token (PAT) for all administrative session management operations.
- Go
- TypeScript
package session
import (
"context"
"fmt"
"github.com/ory/client-go"
"os"
)
var ory *client.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 ContextWithToken(ctx context.Context) context.Context {
return context.WithValue(ctx, client.ContextAccessToken, os.Getenv("ORY_API_KEY"))
}
import { Configuration, IdentityApi } from "@ory/client"
const identityApi = new IdentityApi(
new Configuration({
basePath: `https://${process.env.ORY_PROJECT_SLUG}.projects.oryapis.com`,
accessToken: `${process.env.ORY_ACCESS_TOKEN}`,
}),
)
Listing all sessions
You can get a list of all sessions available in the system using the list sessions API from the SDK. The API returns a paginated response. Optional parameters allow to get a specific page and define the number of items shown on a single page.
- Go
- TypeScript
- Ory Console
package session
import (
"context"
"github.com/ory/client-go"
)
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
}
import { Configuration, IdentityApi } from "@ory/client"
const identityApi = new IdentityApi(
new Configuration({
basePath: `https://${process.env.ORY_PROJECT_SLUG}.projects.oryapis.com`,
accessToken: `${process.env.ORY_ACCESS_TOKEN}`,
}),
)
export async function ListSessions(
expandOptions?: Array<"Devices" | "Identity">,
pageToken?: string,
pageSize?: number,
active?: boolean,
) {
// All parameters here are optional
// Expand options can be used to include data for certain attributes in the response which are not returned by default to improve performance
// Page Token obtained from the response header has to be set to receive subsequent page data
return await identityApi.listSessions({
expand: expandOptions,
active: active, // Optional parameter to filter sessions based on state (active/inactive)
pageToken: pageToken,
pageSize: pageSize, // Optional parameter to control the number of sessions per page (has default fallback value)
})
}
To view all sessions available in a project, go to Ory Console → Sessions.
Listing all sessions of a user
Administrators can get a list of all sessions of a given available in the system using the list identity sessions API from the SDK. The API returns a paginated response. Optional parameters allow to get a specific page and define the number of items shown on a single page.
- Go
- TypeScript
package session
import (
"context"
"github.com/ory/client-go"
)
func GetIdentitySessions(ctx context.Context, identityId string, pageNumber int64, perPage int64) (sessions []client.Session, err error) {
sessions, _, err = ory.IdentityApi.ListIdentitySessions(ContextWithToken(ctx), identityId).
Page(pageNumber). // Optional - page number
PerPage(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
}
import { Configuration, IdentityApi } from "@ory/client"
const identityApi = new IdentityApi(
new Configuration({
basePath: `https://${process.env.ORY_PROJECT_SLUG}.projects.oryapis.com`,
accessToken: `${process.env.ORY_ACCESS_TOKEN}`,
}),
)
export async function GetIdentitySessions(
identityId: string,
active?: boolean,
pageNumber?: number,
pageSize?: number,
) {
return await identityApi.listIdentitySessions({
id: identityId,
active: active, // Optional parameter to filter sessions based on state (active/inactive)
page: pageNumber, // Optional parameter to receive subsequent pages
perPage: pageSize, // Optional parameter to control the number of sessions per page (has default fallback value)
})
}
Getting session details
Administrators can get the details of any session available in the system using the get session API from the SDK.
- Go
- TypeScript
- Ory Console
package session
import (
"context"
"github.com/ory/client-go"
)
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
}
import { Configuration, IdentityApi } from "@ory/client"
const identityApi = new IdentityApi(
new Configuration({
basePath: `https://${process.env.ORY_PROJECT_SLUG}.projects.oryapis.com`,
accessToken: `${process.env.ORY_ACCESS_TOKEN}`,
}),
)
export async function GetSession(
sessionId: string,
expandOptions?: Array<"Devices" | "Identity">,
) {
return await identityApi.getSession({
id: sessionId,
expand: expandOptions,
})
}
To view sessions metadata, go to Ory Console → Sessions and click the Actions icon corresponding to the session you want to inspect.
Revoking a session
Administrators can revoke any session available in the system using the revoke session API from the SDK.
- Go
- TypeScript
- Ory Console
package session
import (
"context"
)
func DisableSession(ctx context.Context, sessionId string) (err error) {
_, err = ory.IdentityApi.DisableSession(ContextWithToken(ctx), sessionId).
Execute()
return err
}
import { Configuration, IdentityApi } from "@ory/client"
const identityApi = new IdentityApi(
new Configuration({
basePath: `https://${process.env.ORY_PROJECT_SLUG}.projects.oryapis.com`,
accessToken: `${process.env.ORY_ACCESS_TOKEN}`,
}),
)
export async function DisableSession(sessionId: string) {
return await identityApi.disableSession({
id: sessionId,
})
}
To revoke a session, go to Ory Console → Sessions, select the Actions icon corresponding to the session you want to terminate and click the Terminate Session button.
Revoke and delete sessions of a user
Administrators can revoke and delete all sessions of a specific user using the revoke and delete identity sessions API from the SDK.
This operation forcefully logs the user out of all their sessions and deletes all session data.
- Go
- TypeScript
package session
import (
"context"
)
func DisableAndDeleteSessions(ctx context.Context, identityId string) (err error) {
_, err = ory.IdentityApi.DeleteIdentitySessions(ContextWithToken(ctx), identityId).
Execute()
return err
}
import { Configuration, IdentityApi } from "@ory/client"
const identityApi = new IdentityApi(
new Configuration({
basePath: `https://${process.env.ORY_PROJECT_SLUG}.projects.oryapis.com`,
accessToken: `${process.env.ORY_ACCESS_TOKEN}`,
}),
)
export async function DisableAndDeleteSessions(identityId: string) {
return await identityApi.deleteIdentitySessions({
id: identityId,
})
}