Skip to content

Session Reference

Creates a session for a user.

Arguments

userId string required
The ID of the user
tags string[]
The tags associated with the session to be created. Leave empty if using defaults. See the Session Tags documentation for more information
userAgent string
Information about the user agent, such as their OS. See the docs here for more information.
ipAddress string
The user's IP Address. Including this value will include the user's IP address in the session audit logs. It is also required if you have IP Address restrictions configured. See the docs here for more information.
metadata JsonValue
Additional information to store about the user session.
deviceRegistration DeviceRegistration
Link the session to a specific device. See the Device Registration docs for more information.

Successful Response

sessionId string
The ID of the created session
sessionToken string
The token for the created session
expiresAt number
The Unix timestamp when the session expires
newDeviceDetected boolean
Whether a new device was detected (only present when using device registration)

Error Types

SessionLimitExceeded
The user has exceeded the maximum number of allowed active sessions
IpAddressError
The provided IP address is either on your blocklist, not allowed, or not specified when it should be
TagParseError
The tags provided could not be parsed
InvalidDeviceRegistration
The device registration data provided was invalid
UnexpectedError
An unexpected error occurred during the operation
const auth = createClient({ url, integrationKey });
const result = await auth.session.create({
userId: "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
tags: [
"type:high_security"
],
userAgent: "Mozilla/5.0 (Macintosh...",
ipAddress: "136.38.37.199",
metadata: {
"example": "value"
},
deviceRegistration: {
signedDeviceChallenge: "eyJhbGciOiJF..",
rememberDevice: true,
requestMethod: "POST",
requestUrl: "https://api.example.com/api/user",
},
});
if (result.ok) {
console.log("Session created successfully");
// Use result.data.sessionToken for authentication
res.cookie("session", result.data.sessionToken);
} else {
console.log(`Error: ${result.error}`);
// Check result.error.type to handle specific errors
}
client = create_client(url=url, integration_key=integration_key)
result = await client.session.create(
user_id="1189c444-8a2d-4c41-8b4b-ae43ce79a492",
tags=[
"type:high_security"
],
user_agent="Mozilla/5.0 (Macintosh...",
ip_address="136.38.37.199",
metadata={
"example": "value"
},
device_registration={
"signed_device_challenge": "eyJhbGciOiJF..",
"remember_device": True,
"request_method": "POST",
"request_url": "https://api.example.com/api/user",
},
)
if is_ok(result):
print("Session created successfully")
# Use result.data.session_token for authentication
response.set_cookie("session", result.data.session_token)
else:
print(f"Error: {result.error}")
# Check result.error.type to handle specific errors
client, err := byo.NewClient(url, integrationKey)
if err != nil {
log.Fatal(err)
}
result, err := client.Session.Create(ctx, byo.CreateSessionCommand{
UserID: "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
Tags: []string{"type:high_security"},
UserAgent: byo.String("Mozilla/5.0 (Macintosh..."),
IPAddress: byo.String("136.38.37.199"),
Metadata: map[string]any{
"example": "value",
},
DeviceRegistration: &byo.DeviceRegistration{
SignedDeviceChallenge: "eyJhbGciOiJF..",
RememberDevice: byo.Bool(true),
RequestMethod: byo.String("POST"),
RequestURL: byo.String("https://api.example.com/api/user"),
},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.SessionToken)
PropelAuthClient client = PropelAuthClient.create(url, integrationKey);
CreateSessionCommand command = CreateSessionCommand.builder()
.userId("1189c444-8a2d-4c41-8b4b-ae43ce79a492")
.tags(Arrays.asList("type:high_security"))
.userAgent("Mozilla/5.0 (Macintosh...")
.ipAddress("136.38.37.199")
.metadata(JsonValue.of(Map.of("example", "value")))
.deviceRegistration(DeviceRegistration.builder()
.signedDeviceChallenge("eyJhbGciOiJF..")
.rememberDevice(true)
.requestMethod("POST")
.requestUrl("https://api.example.com/api/user")
.build())
.build();
try {
CreateSessionResponse sessionResponse = client.session.create(command);
System.out.println("Session created successfully");
// Use sessionResponse.getSessionToken() for authentication
response.addCookie(new Cookie("session", sessionResponse.getSessionToken()));
} catch (CreateSessionException.SessionLimitExceeded e) {
System.out.println("Session limit exceeded: " + e.getDetails().getMaxAllowed());
} catch (CreateSessionException e) {
System.out.println("Error: " + e.getMessage());
}
var client = new PropelAuthClient(new PropelAuthOptions { Url = url, IntegrationKey = integrationKey });
var command = new CreateSessionCommand
{
UserId = "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
Tags = new List<string> { "type:high_security" },
UserAgent = "Mozilla/5.0 (Macintosh...",
IpAddress = "136.38.37.199",
Metadata = JsonSerializer.SerializeToElement(new Dictionary<string, object>
{
{ "example", "value" }
}),
DeviceRegistration = new DeviceRegistration
{
SignedDeviceChallenge = "eyJhbGciOiJF..",
RememberDevice = true,
RequestMethod = "POST",
RequestUrl = "https://api.example.com/api/user"
}
};
try
{
var sessionResponse = await client.Session.CreateAsync(command);
Console.WriteLine("Session created successfully");
// Use sessionResponse.SessionToken for authentication
response.Cookies.Append("session", sessionResponse.SessionToken);
}
catch (CreateSessionException.SessionLimitExceeded ex)
{
Console.WriteLine($"Session limit exceeded: {ex.Details.MaxAllowed}");
}
catch (CreateSessionException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Response
{
ok: true,
data: {
sessionId: "vNCf0b...",
sessionToken: "sess_vNCf0boJ...",
expiresAt: 1735689600,
newDeviceDetected: true
}
}
Result(
data=CreateSessionResponse(
session_id="vNCf0b...",
session_token="sess_vNCf0boJ...",
expires_at=1735689600,
new_device_detected=True
)
)
byo.CreateSessionResponse{
SessionID: "vNCf0b...",
SessionToken: "sess_vNCf0boJ...",
ExpiresAt: 1735689600,
NewDeviceDetected: byo.Bool(true),
}
CreateSessionResponse(
sessionId="vNCf0b...",
sessionToken="sess_vNCf0boJ...",
expiresAt=1735689600,
newDeviceDetected=true
)
CreateSessionResponse
{
SessionId = "vNCf0b...",
SessionToken = "sess_vNCf0boJ...",
ExpiresAt = 1735689600,
NewDeviceDetected = true
}

Validates a user's session.

Arguments

sessionToken string
The session token returned from the Create Session function.
userAgent string
Information about the user agent, such as their OS. See the docs here for more information.
ipAddress string
The user's IP Address. Including this value will include the user's IP address in the session audit logs. It is also required if you have IP Address restrictions configured. See the docs here for more information.
requiredTags string[]
Checks if the session was created with the included tags. See the Session Tags documentation for more information
deviceVerification DeviceVerification
Link the session to a specific device. See the Device Registration docs for more information.
ignoreDeviceForVerification boolean
Set to true to override device verification when the session was created with a registered device.

Successful Response

sessionId string
The ID of the validated session
userId string
The ID of the user who owns this session
createdAt number
The Unix timestamp when the session was created
expiresAt number
The Unix timestamp when the session expires
tags string[]
The tags associated with this session
metadata JsonValue
Additional metadata stored with the session
hasDeviceRegistered boolean
Whether the session has a device registered

Error Types

InvalidSessionToken
The provided session token is invalid, expired, or does not exist
IpAddressError
The provided IP address is either on your blocklist, not allowed, or not specified when it should be
NewDeviceChallengeRequired
A new device is detected and a challenge is required. Returns deviceChallenge and expiresAt in error details
DeviceVerificationRequired
The user's device must go through verification
DeviceVerificationFailed
The device failed verification
UnexpectedError
An unexpected error occurred during the operation
const auth = createClient({ url, integrationKey });
const result = await auth.session.validate({
sessionToken: "sess_vNCf0boJ...",
userAgent: "Mozilla/5.0 (Macintosh...",
ipAddress: "136.38.37.199",
requiredTags: [
"type:high_security"
],
deviceVerification: {
signedDeviceChallenge: "eyJhbGciOiJFUzI1NiIsInR5cCI6ImRw..",
requestMethod: "POST",
requestUrl: "https://api.example.com/api/user",
},
ignoreDeviceForVerification: false
});
if (result.ok) {
console.log("Session validated successfully");
// Access user information from result.data
const userId = result.data.userId;
} else {
console.log(`Error: ${result.error}`);
// Check result.error.type to handle specific errors
if (result.error.type === "NewDeviceChallengeRequired") {
// Handle new device challenge
const challenge = result.error.details.deviceChallenge;
}
}
client = create_client(url=url, integration_key=integration_key)
result = await client.session.validate(
session_token="sess_vNCf0boJ...",
user_agent="Mozilla/5.0 (Macintosh...",
ip_address="136.38.37.199",
required_tags=[
"type:high_security"
],
device_verification=DeviceVerification(
signed_device_challenge="eyJhbGciOiJFUzI1NiIsInR5cCI6ImRw..",
request_method="POST",
request_url="https://api.example.com/api/user",
),
ignore_device_for_verification=False
)
if is_ok(result):
print("Session validated successfully")
# Access user information from result.data
user_id = result.data.user_id
else:
print(f"Error: {result.error}")
# Check result.error.type to handle specific errors
if result.error.type == "NewDeviceChallengeRequired":
# Handle new device challenge
challenge = result.error.details["deviceChallenge"]
client, err := byo.NewClient(url, integrationKey)
if err != nil {
log.Fatal(err)
}
result, err := client.Session.Validate(ctx, byo.ValidateSessionCommand{
SessionToken: byo.String("sess_vNCf0boJ..."),
UserAgent: byo.String("Mozilla/5.0 (Macintosh..."),
IPAddress: byo.String("136.38.37.199"),
RequiredTags: []string{"type:high_security"},
DeviceVerification: &byo.DeviceVerification{
SignedDeviceChallenge: "eyJhbGciOiJFUzI1NiIsInR5cCI6ImRw..",
RequestMethod: byo.String("POST"),
RequestURL: byo.String("https://api.example.com/api/user"),
},
IgnoreDeviceForVerification: byo.Bool(false),
})
if err != nil {
// Check the error type with errors.As to handle specific errors
var challengeErr *byo.ValidateSessionErrorNewDeviceChallengeRequired
if errors.As(err, &challengeErr) {
// Handle new device challenge
fmt.Println(challengeErr.Details.DeviceChallenge)
}
log.Fatal(err)
}
fmt.Println(result.UserID)
PropelAuthClient client = PropelAuthClient.create(url, integrationKey);
ValidateSessionCommand command = ValidateSessionCommand.builder()
.sessionToken("sess_vNCf0boJ...")
.userAgent("Mozilla/5.0 (Macintosh...")
.ipAddress("136.38.37.199")
.requiredTags(Arrays.asList("type:high_security"))
.deviceVerification(DeviceVerification.builder()
.signedDeviceChallenge("eyJhbGciOiJFUzI1NiIsInR5cCI6ImRw..")
.requestMethod("POST")
.requestUrl("https://api.example.com/api/user")
.build())
.ignoreDeviceForVerification(false)
.build();
try {
ValidateSessionResponse response = client.session.validate(command);
System.out.println("Session validated successfully");
// Access user information from response
String userId = response.getUserId();
} catch (ValidateSessionException.InvalidSessionToken e) {
System.out.println("Invalid token: " + e.getMessage());
} catch (ValidateSessionException.NewDeviceChallengeRequired e) {
// Handle new device challenge
String challenge = e.getDetails().getDeviceChallenge();
} catch (ValidateSessionException e) {
System.out.println("Error: " + e.getMessage());
}
var client = new PropelAuthClient(new PropelAuthOptions { Url = url, IntegrationKey = integrationKey });
var command = new ValidateSessionCommand
{
SessionToken = "sess_vNCf0boJ...",
UserAgent = "Mozilla/5.0 (Macintosh...",
IpAddress = "136.38.37.199",
RequiredTags = new List<string> { "type:high_security" },
DeviceVerification = new DeviceVerification
{
SignedDeviceChallenge = "eyJhbGciOiJFUzI1NiIsInR5cCI6ImRw..",
RequestMethod = "POST",
RequestUrl = "https://api.example.com/api/user"
},
IgnoreDeviceForVerification = false
};
try
{
var response = await client.Session.ValidateAsync(command);
Console.WriteLine("Session validated successfully");
// Access user information from response
var userId = response.UserId;
}
catch (ValidateSessionException.InvalidSessionToken ex)
{
Console.WriteLine($"Invalid token: {ex.Message}");
}
catch (ValidateSessionException.NewDeviceChallengeRequired ex)
{
// Handle new device challenge
var challenge = ex.Details.DeviceChallenge;
}
catch (ValidateSessionException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Response
{
ok: true,
data: {
sessionId: "LkYZi7nlyoEtzdL9e0aS1N",
userId: "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
createdAt: 1752277593,
expiresAt: 1753487193,
tags: [
"type:high_security"
],
metadata: {
example: "value"
},
hasDeviceRegistered: true
}
}
Result(
data=ValidateSessionResponse(
session_id="LkYZi7nlyoEtzdL9e0aS1N",
user_id="1189c444-8a2d-4c41-8b4b-ae43ce79a492",
created_at=1752277593,
expires_at=1753487193,
tags=[
"type:high_security"
],
metadata={
"example": "value"
},
has_device_registered=True
)
)
byo.ValidateSessionResponse{
SessionID: "LkYZi7nlyoEtzdL9e0aS1N",
UserID: "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
CreatedAt: 1752277593,
ExpiresAt: 1753487193,
Tags: []string{"type:high_security"},
HasDeviceRegistered: true,
}
ValidateSessionResponse(
sessionId="LkYZi7nlyoEtzdL9e0aS1N",
userId="1189c444-8a2d-4c41-8b4b-ae43ce79a492",
createdAt=1752277593,
expiresAt=1753487193,
tags=["type:high_security"],
metadata={"example": "value"},
hasDeviceRegistered=true
)
ValidateSessionResponse
{
SessionId = "LkYZi7nlyoEtzdL9e0aS1N",
UserId = "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
CreatedAt = 1752277593,
ExpiresAt = 1753487193,
Tags = ["type:high_security"],
Metadata = {"example": "value"},
HasDeviceRegistered = true
}

Validates a session and optionally returns a new session token for rotation. Does the same validation as the standard Validate function but may return a refreshed token.

Arguments

sessionToken string
The session token returned from the Create Session function.
userAgent string
Information about the user agent, such as their OS. See the docs here for more information.
ipAddress string
The user's IP Address. Including this value will include the user's IP address in the session audit logs. It is also required if you have IP Address restrictions configured. See the docs here for more information.
requiredTags string[]
Checks if the session was created with the included tags. See the Session Tags documentation for more information
deviceVerification DeviceVerification
Link the session to a specific device. See the Device Registration docs for more information.
ignoreDeviceForVerification boolean
Set to true to override device verification when the session was created with a registered device.

Successful Response

sessionId string
The ID of the validated session
userId string
The ID of the user who owns this session
createdAt number
The Unix timestamp when the session was created
expiresAt number
The Unix timestamp when the session expires
tags string[]
The tags associated with this session
metadata JsonValue
Additional metadata stored with the session
hasDeviceRegistered boolean
Whether the session has a device registered
newSessionToken string
A new session token if rotation occurred (based on session_refresh_interval_secs)

Error Types

InvalidSessionToken
The provided session token is invalid, expired, or does not exist
IpAddressError
The provided IP address is either on your blocklist, not allowed, or not specified when it should be
NewDeviceChallengeRequired
A new device is detected and a challenge is required. Returns deviceChallenge and expiresAt in error details
DeviceVerificationRequired
The user's device must go through verification
DeviceVerificationFailed
The device failed verification
UnexpectedError
An unexpected error occurred during the operation
const auth = createClient({ url, integrationKey });
const result = await auth.session.validateAndRefresh({
sessionToken: "sess_vNCf0boJ...",
userAgent: "Mozilla/5.0 (Macintosh...",
ipAddress: "136.38.37.199",
requiredTags: [
"type:high_security"
],
deviceVerification: {
signedDeviceChallenge: "eyJhbGciOiJFUzI1NiIsInR5cCI6ImRw..",
requestMethod: "POST",
requestUrl: "https://api.example.com/api/user",
},
ignoreDeviceForVerification: false
});
if (result.ok) {
console.log("Session validated successfully");
// Update cookie if a new token was issued
if (result.data.newSessionToken) {
res.cookie("sessionToken", result.data.newSessionToken, COOKIE_OPTIONS);
}
// Access user information from result.data
const userId = result.data.userId;
} else {
console.log(`Error: ${result.error}`);
// Check result.error.type to handle specific errors
if (result.error.type === "NewDeviceChallengeRequired") {
// Handle new device challenge
const challenge = result.error.details.deviceChallenge;
}
}
client = create_client(url=url, integration_key=integration_key)
result = await client.session.validate_and_refresh(
session_token="sess_vNCf0boJ...",
user_agent="Mozilla/5.0 (Macintosh...",
ip_address="136.38.37.199",
required_tags=[
"type:high_security"
],
device_verification=DeviceVerification(
signed_device_challenge="eyJhbGciOiJFUzI1NiIsInR5cCI6ImRw..",
request_method="POST",
request_url="https://api.example.com/api/user",
),
ignore_device_for_verification=False
)
if is_ok(result):
print("Session validated successfully")
# Update cookie if a new token was issued
if result.data.new_session_token:
response.set_cookie("sessionToken", result.data.new_session_token, **COOKIE_OPTIONS)
# Access user information from result.data
user_id = result.data.user_id
else:
print(f"Error: {result.error}")
# Check result.error.type to handle specific errors
if result.error.type == "NewDeviceChallengeRequired":
# Handle new device challenge
challenge = result.error.details["deviceChallenge"]
client, err := byo.NewClient(url, integrationKey)
if err != nil {
log.Fatal(err)
}
result, err := client.Session.ValidateAndRefresh(ctx, byo.ValidateAndRefreshSessionCommand{
SessionToken: byo.String("sess_vNCf0boJ..."),
UserAgent: byo.String("Mozilla/5.0 (Macintosh..."),
IPAddress: byo.String("136.38.37.199"),
RequiredTags: []string{"type:high_security"},
DeviceVerification: &byo.DeviceVerification{
SignedDeviceChallenge: "eyJhbGciOiJFUzI1NiIsInR5cCI6ImRw..",
RequestMethod: byo.String("POST"),
RequestURL: byo.String("https://api.example.com/api/user"),
},
IgnoreDeviceForVerification: byo.Bool(false),
})
if err != nil {
// Check the error type with errors.As to handle specific errors
var challengeErr *byo.ValidateAndRefreshSessionErrorNewDeviceChallengeRequired
if errors.As(err, &challengeErr) {
// Handle new device challenge
fmt.Println(challengeErr.Details.DeviceChallenge)
}
log.Fatal(err)
}
if result.NewSessionToken != nil {
// Update cookie if a new token was issued
http.SetCookie(w, &http.Cookie{Name: "sessionToken", Value: *result.NewSessionToken})
}
PropelAuthClient client = PropelAuthClient.create(url, integrationKey);
ValidateAndRefreshSessionCommand command = ValidateAndRefreshSessionCommand.builder()
.sessionToken("sess_vNCf0boJ...")
.userAgent("Mozilla/5.0 (Macintosh...")
.ipAddress("136.38.37.199")
.requiredTags(Arrays.asList("type:high_security"))
.deviceVerification(DeviceVerification.builder()
.signedDeviceChallenge("eyJhbGciOiJFUzI1NiIsInR5cCI6ImRw..")
.requestMethod("POST")
.requestUrl("https://api.example.com/api/user")
.build())
.ignoreDeviceForVerification(false)
.build();
try {
ValidateAndRefreshSessionResponse response = client.session.validateAndRefresh(command);
System.out.println("Session validated successfully");
// Update cookie if a new token was issued
if (response.getNewSessionToken() != null) {
// Set cookie with new token - implementation depends on your framework
// e.g., HttpServletResponse.addCookie(new Cookie("sessionToken", response.getNewSessionToken()));
}
// Access user information from response
String userId = response.getUserId();
} catch (ValidateAndRefreshSessionException.InvalidSessionToken e) {
System.out.println("Invalid token: " + e.getMessage());
} catch (ValidateAndRefreshSessionException.NewDeviceChallengeRequired e) {
// Handle new device challenge
String challenge = e.getDetails().getDeviceChallenge();
} catch (ValidateAndRefreshSessionException e) {
System.out.println("Error: " + e.getMessage());
}
var client = new PropelAuthClient(new PropelAuthOptions { Url = url, IntegrationKey = integrationKey });
var command = new ValidateAndRefreshSessionCommand
{
SessionToken = "sess_vNCf0boJ...",
UserAgent = "Mozilla/5.0 (Macintosh...",
IpAddress = "136.38.37.199",
RequiredTags = new List<string> { "type:high_security" },
DeviceVerification = new DeviceVerification
{
SignedDeviceChallenge = "eyJhbGciOiJFUzI1NiIsInR5cCI6ImRw..",
RequestMethod = "POST",
RequestUrl = "https://api.example.com/api/user"
},
IgnoreDeviceForVerification = false
};
try
{
var response = await client.Session.ValidateAndRefreshAsync(command);
Console.WriteLine("Session validated successfully");
// Update cookie if a new token was issued
if (response.NewSessionToken != null)
{
// Set cookie with new token - implementation depends on your framework
// e.g., Response.Cookies.Append("sessionToken", response.NewSessionToken, cookieOptions);
}
// Access user information from response
var userId = response.UserId;
}
catch (ValidateAndRefreshSessionException.InvalidSessionToken ex)
{
Console.WriteLine($"Invalid token: {ex.Message}");
}
catch (ValidateAndRefreshSessionException.NewDeviceChallengeRequired ex)
{
// Handle new device challenge
var challenge = ex.Details.DeviceChallenge;
}
catch (ValidateAndRefreshSessionException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Response
{
ok: true,
data: {
sessionId: "LkYZi7nlyoEtzdL9e0aS1N",
userId: "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
createdAt: 1752277593,
expiresAt: 1753487193,
tags: [
"type:high_security"
],
metadata: {
example: "value"
},
hasDeviceRegistered: true,
newSessionToken: "sess_xYz9aBc2..."
}
}
Result(
data=ValidateAndRefreshSessionResponse(
session_id="LkYZi7nlyoEtzdL9e0aS1N",
user_id="1189c444-8a2d-4c41-8b4b-ae43ce79a492",
created_at=1752277593,
expires_at=1753487193,
tags=[
"type:high_security"
],
metadata={
"example": "value"
},
has_device_registered=True,
new_session_token="sess_xYz9aBc2..."
)
)
byo.ValidateAndRefreshSessionResponse{
SessionID: "LkYZi7nlyoEtzdL9e0aS1N",
UserID: "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
CreatedAt: 1752277593,
ExpiresAt: 1753487193,
Tags: []string{"type:high_security"},
HasDeviceRegistered: true,
NewSessionToken: byo.String("sess_xYz9aBc2..."),
}
ValidateAndRefreshSessionResponse(
sessionId="LkYZi7nlyoEtzdL9e0aS1N",
userId="1189c444-8a2d-4c41-8b4b-ae43ce79a492",
createdAt=1752277593,
expiresAt=1753487193,
tags=["type:high_security"],
metadata={"example": "value"},
hasDeviceRegistered=true,
newSessionToken="sess_xYz9aBc2..."
)
ValidateAndRefreshSessionResponse
{
SessionId = "LkYZi7nlyoEtzdL9e0aS1N",
UserId = "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
CreatedAt = 1752277593,
ExpiresAt = 1753487193,
Tags = ["type:high_security"],
Metadata = { "example": "value" },
HasDeviceRegistered = true,
NewSessionToken = "sess_xYz9aBc2..."
}

Creates a stateless token (JWT) for a user. These can be verified without making a call to the BYO service.

Arguments

userId string required
The ID of the user to create the token for
sessionId string
The ID of the session to link the stateless token to
customClaims JsonValue
Additional custom claims to include in the token
issuer string
The issuer claim for the token
audience string
The audience claim for the token
notBeforeUnixtime number
Unix timestamp before which the token should not be accepted
lifetimeSecs number
The lifetime of the token in seconds

Successful Response

statelessToken string
The generated JWT
expiresAt number
Unix timestamp when the token expires

Error Types

TokenCreationFailed
The token could not be created
UnexpectedError
An unexpected error occurred during the operation
const auth = createClient({ url, integrationKey });
const result = await auth.session.createStatelessToken({
userId: "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
sessionId: "LkYZi7nlyoEtzdL9e0aS1N",
customClaims: {
"example": "value"
},
lifetimeSecs: 1800
});
if (result.ok) {
console.log("Token created successfully");
// Use result.data.statelessToken as your JWT
} else {
console.log(`Error: ${result.error}`);
// Check result.error.type to handle specific errors
}
client = create_client(url=url, integration_key=integration_key)
result = await client.session.create_stateless_token(
user_id="1189c444-8a2d-4c41-8b4b-ae43ce79a492",
session_id="LkYZi7nlyoEtzdL9e0aS1N",
custom_claims={
"example": "value"
},
lifetime_secs=1800
)
if is_ok(result):
print("Token created successfully")
# Use result.data.stateless_token as your JWT
else:
print(f"Error: {result.error}")
# Check result.error.type to handle specific errors
client, err := byo.NewClient(url, integrationKey)
if err != nil {
log.Fatal(err)
}
result, err := client.Session.CreateStatelessToken(ctx, byo.CreateStatelessTokenCommand{
UserID: "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
SessionID: byo.String("LkYZi7nlyoEtzdL9e0aS1N"),
CustomClaims: map[string]any{
"example": "value",
},
LifetimeSecs: byo.Int(1800),
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.StatelessToken)
PropelAuthClient client = PropelAuthClient.create(url, integrationKey);
CreateStatelessTokenCommand command = CreateStatelessTokenCommand.builder()
.userId("1189c444-8a2d-4c41-8b4b-ae43ce79a492")
.sessionId("LkYZi7nlyoEtzdL9e0aS1N")
.customClaims(JsonValue.of(Map.of("example", "value")))
.lifetimeSecs(1800)
.build();
try {
CreateStatelessTokenResponse tokenResponse = client.session.createStatelessToken(command);
System.out.println("Token created successfully");
// Use tokenResponse.getStatelessToken() as your JWT
} catch (CreateStatelessTokenException e) {
System.out.println("Error: " + e.getMessage());
}
var client = new PropelAuthClient(new PropelAuthOptions { Url = url, IntegrationKey = integrationKey });
var command = new CreateStatelessTokenCommand
{
UserId = "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
SessionId = "LkYZi7nlyoEtzdL9e0aS1N",
CustomClaims = JsonSerializer.SerializeToElement(new Dictionary<string, object>
{
{ "example", "value" }
}),
LifetimeSecs = 1800
};
try
{
var tokenResponse = await client.Session.CreateStatelessTokenAsync(command);
Console.WriteLine("Token created successfully");
// Use tokenResponse.StatelessToken as your JWT
}
catch (CreateStatelessTokenException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Response
{
ok: true,
data: {
statelessToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp...",
expiresAt: 1753487193
}
}
Result(
data=CreateStatelessTokenResponse(
stateless_token="eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp...",
expires_at=1753487193
)
)
byo.CreateStatelessTokenResponse{
StatelessToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp...",
ExpiresAt: 1753487193,
}
CreateStatelessTokenResponse(
statelessToken="eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp...",
expiresAt=1753487193
)
CreateStatelessTokenResponse
{
StatelessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6Ikp...",
ExpiresAt = 1753487193
}

Fetches all active sessions. Optionally filter by user ID or session tags.

Arguments

userId string
Filter sessions by user ID
sessionTags string[]
Filter sessions by tags
page number
Page number for pagination (default: 0)

Successful Response

items SessionInfo[]
Array of session information objects
page number
Current page number
pageSize number
Number of items per page
totalCount number
Total number of sessions
hasMoreResults boolean
Whether more pages are available

Error Types

UnexpectedError
An unexpected error occurred during the operation
const auth = createClient({ url, integrationKey });
const result = await auth.session.fetchAll({
userId: "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
sessionTags: [
"type:high_security"
],
page: 0
});
if (result.ok) {
console.log("Sessions retrieved successfully");
console.log(`Found ${result.data.totalCount} total sessions`);
console.log(`Showing page ${result.data.page} with ${result.data.items.length} items`);
} else {
console.log(`Error: ${result.error}`);
// Check result.error.type to handle specific errors
}
client = create_client(url=url, integration_key=integration_key)
result = await client.session.fetch_all(
user_id="1189c444-8a2d-4c41-8b4b-ae43ce79a492",
session_tags=[
"type:high_security"
],
page=0
)
if is_ok(result):
print("Sessions retrieved successfully")
print(f"Found {result.data.total_count} total sessions")
print(f"Showing page {result.data.page} with {len(result.data.items)} items")
else:
print(f"Error: {result.error}")
# Check result.error.type to handle specific errors
client, err := byo.NewClient(url, integrationKey)
if err != nil {
log.Fatal(err)
}
result, err := client.Session.FetchAll(ctx, byo.FetchAllSessionsCommand{
UserID: byo.String("1189c444-8a2d-4c41-8b4b-ae43ce79a492"),
SessionTags: []string{"type:high_security"},
Page: byo.Int(0),
})
if err != nil {
log.Fatal(err)
}
fmt.Println(len(result.Items))
PropelAuthClient client = PropelAuthClient.create(url, integrationKey);
FetchAllSessionsCommand command = FetchAllSessionsCommand.builder()
.userId("1189c444-8a2d-4c41-8b4b-ae43ce79a492")
.sessionTags(Arrays.asList("type:high_security"))
.page(0)
.build();
try {
FetchAllSessionsResponse response = client.session.fetchAll(command);
System.out.println("Sessions retrieved successfully");
System.out.println("Found " + response.getTotalCount() + " total sessions");
System.out.println("Showing page " + response.getPage() + " with " + response.getItems().size() + " items");
} catch (FetchAllSessionsException e) {
System.out.println("Error: " + e.getMessage());
}
var client = new PropelAuthClient(new PropelAuthOptions { Url = url, IntegrationKey = integrationKey });
var command = new FetchAllSessionsCommand
{
UserId = "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
SessionTags = new List<string> { "type:high_security" },
Page = 0
};
try
{
var response = await client.Session.FetchAllAsync(command);
Console.WriteLine("Sessions retrieved successfully");
Console.WriteLine($"Found {response.TotalCount} total sessions");
Console.WriteLine($"Showing page {response.Page} with {response.Items.Count} items");
}
catch (FetchAllSessionsException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Response
{
ok: true,
data: {
items: [
{
sessionId: "rgLYjcNpFQYV9LQf4AwM37",
createdAt: 1752277593,
expiresAt: 1753487193,
lastActivityAt: 1752278000,
device: {
displayName: "Chrome on Mac OS X",
deviceType: "desktop",
browser: "Chrome",
browserVersion: "139.0",
os: "Mac OS X",
osVersion: "10.15"
},
ipAddress: "127.0.0.1",
sessionTags: [
"type:high_security"
],
metadata: {
example: "value"
}
},
{
sessionId: "rgLYjcNpFQYV9LQf4AwM37",
createdAt: 1752277593,
...
}
],
page: 0,
pageSize: 10,
totalCount: 100,
hasMoreResults: true
}
}
Result(
data=FetchAllSessionsResponse(
items=[
SessionInfo(
session_id="rgLYjcNpFQYV9LQf4AwM37",
created_at=1752277593,
expires_at=1753487193,
last_activity_at=1752278000,
device=DeviceInfo(
display_name="Chrome on Mac OS X",
device_type="desktop",
browser="Chrome",
browser_version="139.0",
os="Mac OS X",
os_version="10.15"
),
ip_address="127.0.0.1",
session_tags=[
"type:high_security"
],
metadata={
"example": "value"
}
),
SessionInfo(
session_id="rgLYjcNpFQYV9LQf4AwM37",
created_at=1752277593,
...
)
],
page=0,
page_size=10,
total_count=100,
has_more_results=True
)
)
byo.FetchAllSessionsResponse{
Items: []byo.SessionInfo{
{
SessionID: "rgLYjcNpFQYV9LQf4AwM37",
CreatedAt: 1752277593,
ExpiresAt: 1753487193,
LastActivityAt: 1752278000,
Device: byo.DeviceInfo{
DisplayName: "Chrome on Mac OS X",
DeviceType: byo.DeviceTypeDesktop,
Browser: byo.String("Chrome"),
BrowserVersion: byo.String("139.0"),
Os: byo.String("Mac OS X"),
OsVersion: byo.String("10.15"),
},
IPAddress: byo.String("127.0.0.1"),
SessionTags: []string{"type:high_security"},
},
},
Page: 0,
PageSize: 10,
TotalCount: 100,
HasMoreResults: true,
}
FetchAllSessionsResponse(
items=[
SessionInfo(
sessionId="rgLYjcNpFQYV9LQf4AwM37",
createdAt=1752277593,
expiresAt=1753487193,
lastActivityAt=1752278000,
device=DeviceInfo(
displayName="Chrome on Mac OS X",
deviceType=DESKTOP,
browser="Chrome",
browserVersion="139.0",
os="Mac OS X",
osVersion="10.15"
),
ipAddress="127.0.0.1",
sessionTags=["type:high_security"],
metadata={"example": "value"}
),
SessionInfo(
sessionId="rgLYjcNpFQYV9LQf4AwM37",
createdAt=1752277593,
...
)
],
page=0,
pageSize=10,
totalCount=100,
hasMoreResults=true
)
FetchAllSessionsResponse
{
Items = [
SessionInfo
{
SessionId = "rgLYjcNpFQYV9LQf4AwM37",
CreatedAt = 1752277593,
ExpiresAt = 1753487193,
LastActivityAt = 1752278000,
Device = DeviceInfo
{
DisplayName = "Chrome on Mac OS X",
DeviceType = "desktop",
Browser = "Chrome",
BrowserVersion = "139.0",
Os = "Mac OS X",
OsVersion = "10.15"
},
IpAddress = "127.0.0.1",
SessionTags = ["type:high_security"],
Metadata = { "example": "value" }
},
SessionInfo
{
SessionId = "rgLYjcNpFQYV9LQf4AwM37",
CreatedAt = 1752277593,
...
}
],
Page = 0,
PageSize = 10,
TotalCount = 100,
HasMoreResults = true
}

Fetches all active sessions for a specific user. Returns detailed information about each session including device info, IP address, and metadata.

Arguments

userId string required
The user's ID
sessionTags string[]
Filter sessions by tags. Only returns sessions that have all specified tags

Successful Response

sessions SessionInfo[]
Array of session information objects

Error Types

UnexpectedError
An unexpected error occurred during the operation
const auth = createClient({ url, integrationKey });
const result = await auth.session.fetchAllForUser({
userId: "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
sessionTags: [
"type:high_security"
]
});
if (result.ok) {
console.log("Sessions retrieved successfully");
// Access the sessions array
result.data.sessions.forEach(session => {
console.log(`Session ${session.sessionId} expires at ${session.expiresAt}`);
});
} else {
console.log(`Error: ${result.error}`);
}
client = create_client(url=url, integration_key=integration_key)
result = await client.session.fetch_all_for_user(
user_id="1189c444-8a2d-4c41-8b4b-ae43ce79a492",
session_tags=[
"type:high_security"
]
)
if is_ok(result):
print("Sessions retrieved successfully")
# Access the sessions array
for session in result.data.sessions:
print(f"Session {session.session_id} expires at {session.expires_at}")
else:
print(f"Error: {result.error}")
client, err := byo.NewClient(url, integrationKey)
if err != nil {
log.Fatal(err)
}
result, err := client.Session.FetchAllForUser(ctx, byo.FetchAllSessionsForUserCommand{
UserID: "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
SessionTags: []string{"type:high_security"},
})
if err != nil {
log.Fatal(err)
}
for _, session := range result.Sessions {
fmt.Printf("Session %s expires at %d\n", session.SessionID, session.ExpiresAt)
}
PropelAuthClient client = PropelAuthClient.create(url, integrationKey);
FetchAllSessionsForUserCommand command = FetchAllSessionsForUserCommand.builder()
.userId("1189c444-8a2d-4c41-8b4b-ae43ce79a492")
.sessionTags(Arrays.asList("type:high_security"))
.build();
try {
FetchAllSessionsForUserResponse response = client.session.fetchAllForUser(command);
System.out.println("Sessions retrieved successfully");
// Access the sessions array
for (SessionInfo session : response.getSessions()) {
System.out.println("Session " + session.getSessionId() + " expires at " + session.getExpiresAt());
}
} catch (FetchAllSessionsForUserException e) {
System.out.println("Error: " + e.getMessage());
}
var client = new PropelAuthClient(new PropelAuthOptions { Url = url, IntegrationKey = integrationKey });
var command = new FetchAllSessionsForUserCommand
{
UserId = "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
SessionTags = new List<string> { "type:high_security" }
};
try
{
var response = await client.Session.FetchAllForUserAsync(command);
Console.WriteLine("Sessions retrieved successfully");
// Access the sessions array
foreach (var session in response.Sessions)
{
Console.WriteLine($"Session {session.SessionId} expires at {session.ExpiresAt}");
}
}
catch (FetchAllSessionsForUserException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Response
{
ok: true,
data: {
sessions: [
{
sessionId: "LkYZi7nlyoEtzdL9e0aS1N",
createdAt: 1755195289,
expiresAt: 1756404889,
lastActivityAt: 1755196326,
device: {
displayName: "Chrome on Mac OS X",
deviceType: "desktop",
browser: "Chrome",
browserVersion: "139.0",
os: "Mac OS X",
osVersion: "10.15"
},
ipAddress: "127.0.0.1",
sessionTags: [
"type:high_security"
],
metadata: {
example: "value"
}
}
]
}
}
Result(
data=FetchAllSessionsForUserResponse(
sessions=[
SessionInfo(
session_id="LkYZi7nlyoEtzdL9e0aS1N",
created_at=1755195289,
expires_at=1756404889,
last_activity_at=1755196326,
device=DeviceInfo(
display_name="Chrome on Mac OS X",
device_type="desktop",
browser="Chrome",
browser_version="139.0",
os="Mac OS X",
os_version="10.15"
),
ip_address="127.0.0.1",
session_tags=[
"type:high_security"
],
metadata={
"example": "value"
}
)
]
)
)
byo.FetchAllSessionsForUserResponse{
Sessions: []byo.SessionInfo{
{
SessionID: "LkYZi7nlyoEtzdL9e0aS1N",
CreatedAt: 1755195289,
ExpiresAt: 1756404889,
LastActivityAt: 1755196326,
Device: byo.DeviceInfo{
DisplayName: "Chrome on Mac OS X",
DeviceType: byo.DeviceTypeDesktop,
Browser: byo.String("Chrome"),
BrowserVersion: byo.String("139.0"),
Os: byo.String("Mac OS X"),
OsVersion: byo.String("10.15"),
},
IPAddress: byo.String("127.0.0.1"),
SessionTags: []string{"type:high_security"},
},
},
}
FetchAllSessionsForUserResponse(
sessions=[
SessionInfo(
sessionId="LkYZi7nlyoEtzdL9e0aS1N",
createdAt=1755195289,
expiresAt=1756404889,
lastActivityAt=1755196326,
device=DeviceInfo(
displayName="Chrome on Mac OS X",
deviceType=DESKTOP,
browser="Chrome",
browserVersion="139.0",
os="Mac OS X",
osVersion="10.15"
),
ipAddress="127.0.0.1",
sessionTags=["type:high_security"],
metadata={"example": "value"}
)
]
)
FetchAllSessionsForUserResponse
{
Sessions = [
SessionInfo
{
SessionId = "LkYZi7nlyoEtzdL9e0aS1N",
CreatedAt = 1755195289,
ExpiresAt = 1756404889,
LastActivityAt = 1755196326,
Device = DeviceInfo
{
DisplayName = "Chrome on Mac OS X",
DeviceType = "desktop",
Browser = "Chrome",
BrowserVersion = "139.0",
Os = "Mac OS X",
OsVersion = "10.15"
},
IpAddress = "127.0.0.1",
SessionTags = ["type:high_security"],
Metadata = {"example": "value"}
}
]
}

Fetches a session by its ID.

Arguments

sessionId string required
The ID of the session

Successful Response

sessionId string
The unique session ID
createdAt number
Unix timestamp when session was created
expiresAt number
Unix timestamp when session expires
lastActivityAt number
Unix timestamp of last session activity
device DeviceInfo
Information about the device
ipAddress string
IP address of the session
sessionTags string[]
Array of session tags
metadata object
Custom metadata associated with the session

Error Types

SessionNotFound
The specified session ID was not found
UnexpectedError
An unexpected error occurred during the operation
const auth = createClient({ url, integrationKey });
const result = await auth.session.fetchById({
sessionId: "JVAdUSsMc2UtjehFvzpNGm"
});
if (result.ok) {
console.log("Session retrieved successfully");
console.log(`Session expires at: ${result.data.expiresAt}`);
} else {
console.log(`Error: ${result.error}`);
// Check result.error.type to handle specific errors
}
client = create_client(url=url, integration_key=integration_key)
result = await client.session.fetch_by_id(
session_id="JVAdUSsMc2UtjehFvzpNGm"
)
if is_ok(result):
print("Session retrieved successfully")
print(f"Session expires at: {result.data.expires_at}")
else:
print(f"Error: {result.error}")
# Check result.error.type to handle specific errors
client, err := byo.NewClient(url, integrationKey)
if err != nil {
log.Fatal(err)
}
result, err := client.Session.FetchByID(ctx, byo.FetchSessionByIdCommand{
SessionID: "JVAdUSsMc2UtjehFvzpNGm",
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.ExpiresAt)
PropelAuthClient client = PropelAuthClient.create(url, integrationKey);
FetchSessionByIdCommand command = FetchSessionByIdCommand.builder()
.sessionId("JVAdUSsMc2UtjehFvzpNGm")
.build();
try {
SessionInfo sessionInfo = client.session.fetchById(command);
System.out.println("Session retrieved successfully");
System.out.println("Session expires at: " + sessionInfo.getExpiresAt());
} catch (FetchSessionByIdException.SessionNotFound e) {
System.out.println("Session not found");
} catch (FetchSessionByIdException e) {
System.out.println("Error: " + e.getMessage());
}
var client = new PropelAuthClient(new PropelAuthOptions { Url = url, IntegrationKey = integrationKey });
var command = new FetchSessionByIdCommand
{
SessionId = "JVAdUSsMc2UtjehFvzpNGm"
};
try
{
var sessionInfo = await client.Session.FetchByIdAsync(command);
Console.WriteLine("Session retrieved successfully");
Console.WriteLine($"Session expires at: {sessionInfo.ExpiresAt}");
}
catch (FetchSessionByIdException.SessionNotFound ex)
{
Console.WriteLine("Session not found");
}
catch (FetchSessionByIdException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Response
{
ok: true,
data: {
sessionId: "JVAdUSsMc2UtjehFvzpNGm",
createdAt: 1752277593,
expiresAt: 1753487193,
lastActivityAt: 1752278000,
device: {
displayName: "Chrome on Mac OS X",
deviceType: "desktop",
browser: "Chrome",
browserVersion: "139.0",
os: "Mac OS X",
osVersion: "10.15"
},
ipAddress: "127.0.0.1",
sessionTags: [
"type:high_security"
],
metadata: {
example: "value"
}
}
}
Result(
data=SessionInfo(
session_id="JVAdUSsMc2UtjehFvzpNGm",
created_at=1752277593,
expires_at=1753487193,
last_activity_at=1752278000,
device=DeviceInfo(
display_name="Chrome on Mac OS X",
device_type="desktop",
browser="Chrome",
browser_version="139.0",
os="Mac OS X",
os_version="10.15"
),
ip_address="127.0.0.1",
session_tags=[
"type:high_security"
],
metadata={
"example": "value"
}
)
)
byo.SessionInfo{
SessionID: "JVAdUSsMc2UtjehFvzpNGm",
CreatedAt: 1752277593,
ExpiresAt: 1753487193,
LastActivityAt: 1752278000,
Device: byo.DeviceInfo{
DisplayName: "Chrome on Mac OS X",
DeviceType: byo.DeviceTypeDesktop,
Browser: byo.String("Chrome"),
BrowserVersion: byo.String("139.0"),
Os: byo.String("Mac OS X"),
OsVersion: byo.String("10.15"),
},
IPAddress: byo.String("127.0.0.1"),
SessionTags: []string{"type:high_security"},
}
SessionInfo(
sessionId="JVAdUSsMc2UtjehFvzpNGm",
createdAt=1752277593,
expiresAt=1753487193,
lastActivityAt=1752278000,
device=DeviceInfo(
displayName="Chrome on Mac OS X",
deviceType=DESKTOP,
browser="Chrome",
browserVersion="139.0",
os="Mac OS X",
osVersion="10.15"
),
ipAddress="127.0.0.1",
sessionTags=["type:high_security"],
metadata={"example": "value"}
)
SessionInfo
{
SessionId = "JVAdUSsMc2UtjehFvzpNGm",
CreatedAt = 1752277593,
ExpiresAt = 1753487193,
LastActivityAt = 1752278000,
Device = DeviceInfo
{
DisplayName = "Chrome on Mac OS X",
DeviceType = "desktop",
Browser = "Chrome",
BrowserVersion = "139.0",
Os = "Mac OS X",
OsVersion = "10.15"
},
IpAddress = "127.0.0.1",
SessionTags = ["type:high_security"],
Metadata = {"example": "value"}
}

Invalidates a user's session.

Arguments

sessionId string required
The ID of the session.
userId string
The ID of the user. The session will not be invalidated if the session does not belong to the provided user ID.

Successful Response

Returns an empty response on success


Error Types

SessionNotFound
The provided session was not found
UnexpectedError
An unexpected error occurred
const auth = createClient({ url, integrationKey });
const result = await auth.session.invalidateById({
sessionId: "LkYZi7nlyoEtzdL9e0aS1N",
userId: "1189c444-8a2d-4c41-8b4b-ae43ce79a492"
});
if (result.ok) {
console.log("Session invalidated successfully");
} else {
console.log(`Error: ${result.error}`);
}
client = create_client(url=url, integration_key=integration_key)
result = await client.session.invalidate_by_id(
session_id="LkYZi7nlyoEtzdL9e0aS1N",
user_id="1189c444-8a2d-4c41-8b4b-ae43ce79a492"
)
if is_ok(result):
print("Session invalidated successfully")
else:
print(f"Error: {result.error}")
client, err := byo.NewClient(url, integrationKey)
if err != nil {
log.Fatal(err)
}
_, err = client.Session.InvalidateByID(ctx, byo.InvalidateSessionByIdCommand{
SessionID: "LkYZi7nlyoEtzdL9e0aS1N",
UserID: byo.String("1189c444-8a2d-4c41-8b4b-ae43ce79a492"),
})
if err != nil {
log.Fatal(err)
}
PropelAuthClient client = PropelAuthClient.create(url, integrationKey);
InvalidateSessionByIdCommand command = InvalidateSessionByIdCommand.builder()
.sessionId("LkYZi7nlyoEtzdL9e0aS1N")
.userId("1189c444-8a2d-4c41-8b4b-ae43ce79a492")
.build();
try {
InvalidateSessionByIdResponse response = client.session.invalidateById(command);
System.out.println("Session invalidated successfully");
} catch (InvalidateSessionByIdException.SessionNotFound e) {
System.out.println("Session not found");
} catch (InvalidateSessionByIdException e) {
System.out.println("Error: " + e.getMessage());
}
var client = new PropelAuthClient(new PropelAuthOptions { Url = url, IntegrationKey = integrationKey });
var command = new InvalidateSessionByIdCommand
{
SessionId = "LkYZi7nlyoEtzdL9e0aS1N",
UserId = "1189c444-8a2d-4c41-8b4b-ae43ce79a492"
};
try
{
var response = await client.Session.InvalidateByIdAsync(command);
Console.WriteLine("Session invalidated successfully");
}
catch (InvalidateSessionByIdException.SessionNotFound ex)
{
Console.WriteLine("Session not found");
}
catch (InvalidateSessionByIdException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Response
{
ok: true,
data: {}
}
Result(
data=InvalidateSessionByIdResponse()
)
byo.InvalidateSessionByIdResponse{}
InvalidateSessionByIdResponse()
InvalidateSessionByIdResponse()

Invalidates a user's session by its token. This is commonly used for logout functions.

Arguments

sessionToken string
The session token to invalidate

Successful Response

Returns an empty response on success


Error Types

UnexpectedError
An unexpected error occurred during the operation
const auth = createClient({ url, integrationKey });
const result = await auth.session.invalidateByToken({
sessionToken: "sess_vNCf0boJ..",
});
if (result.ok) {
console.log("Session invalidated successfully");
} else {
console.log(`Error: ${result.error}`);
// Check result.error.type to handle specific errors
}
client = create_client(url=url, integration_key=integration_key)
result = await client.session.invalidate_by_token(
session_token="sess_vNCf0boJ.."
)
if is_ok(result):
print("Session invalidated successfully")
else:
print(f"Error: {result.error}")
# Check result.error.type to handle specific errors
client, err := byo.NewClient(url, integrationKey)
if err != nil {
log.Fatal(err)
}
_, err = client.Session.InvalidateByToken(ctx, byo.InvalidateSessionByTokenCommand{
SessionToken: byo.String("sess_vNCf0boJ..."),
})
if err != nil {
log.Fatal(err)
}
PropelAuthClient client = PropelAuthClient.create(url, integrationKey);
InvalidateSessionByTokenCommand command = InvalidateSessionByTokenCommand.builder()
.sessionToken("sess_vNCf0boJ..")
.build();
try {
InvalidateSessionByTokenResponse response = client.session.invalidateByToken(command);
System.out.println("Session invalidated successfully");
} catch (InvalidateSessionByTokenException e) {
System.out.println("Error: " + e.getMessage());
}
var client = new PropelAuthClient(new PropelAuthOptions { Url = url, IntegrationKey = integrationKey });
var command = new InvalidateSessionByTokenCommand
{
SessionToken = "sess_vNCf0boJ.."
};
try
{
var response = await client.Session.InvalidateByTokenAsync(command);
Console.WriteLine("Session invalidated successfully");
}
catch (InvalidateSessionByTokenException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Response
{
ok: true,
data: {}
}
Result(
data=InvalidateSessionByTokenResponse()
)
byo.InvalidateSessionByTokenResponse{}
InvalidateSessionByTokenResponse()
InvalidateSessionByTokenResponse()

Invalidates all sessions for a specific user. This is useful for forcing a user to re-authenticate across all devices.

Arguments

userId string required
The ID of the user whose sessions should be invalidated
sessionTags string[]
Filter to only invalidate sessions with specific tags

Successful Response

sessionsInvalidated number
The number of sessions that were invalidated

Error Types

UnexpectedError
An unexpected error occurred during the operation
const auth = createClient({ url, integrationKey });
const result = await auth.session.invalidateAllForUser({
userId: "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
sessionTags: [
"type:high_security"
]
});
if (result.ok) {
console.log(`Invalidated ${result.data.sessionsInvalidated} sessions`);
} else {
console.log(`Error: ${result.error}`);
// Check result.error.type to handle specific errors
}
client = create_client(url=url, integration_key=integration_key)
result = await client.session.invalidate_all_for_user(
user_id="1189c444-8a2d-4c41-8b4b-ae43ce79a492",
session_tags=[
"type:high_security"
]
)
if is_ok(result):
print(f"Invalidated {result.data.sessions_invalidated} sessions")
else:
print(f"Error: {result.error}")
# Check result.error.type to handle specific errors
client, err := byo.NewClient(url, integrationKey)
if err != nil {
log.Fatal(err)
}
result, err := client.Session.InvalidateAllForUser(ctx, byo.InvalidateAllSessionsForUserCommand{
UserID: "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
SessionTags: []string{"type:high_security"},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.SessionsInvalidated)
PropelAuthClient client = PropelAuthClient.create(url, integrationKey);
InvalidateAllSessionsForUserCommand command = InvalidateAllSessionsForUserCommand.builder()
.userId("1189c444-8a2d-4c41-8b4b-ae43ce79a492")
.sessionTags(Arrays.asList("type:high_security"))
.build();
try {
InvalidateAllSessionsForUserResponse response = client.session.invalidateAllForUser(command);
System.out.println("Invalidated " + response.getSessionsInvalidated() + " sessions");
} catch (InvalidateAllSessionsForUserException e) {
System.out.println("Error: " + e.getMessage());
}
var client = new PropelAuthClient(new PropelAuthOptions { Url = url, IntegrationKey = integrationKey });
var command = new InvalidateAllSessionsForUserCommand
{
UserId = "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
SessionTags = new List<string> { "type:high_security" }
};
try
{
var response = await client.Session.InvalidateAllForUserAsync(command);
Console.WriteLine($"Invalidated {response.SessionsInvalidated} sessions");
}
catch (InvalidateAllSessionsForUserException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Response
{
ok: true,
data: {
sessionsInvalidated: 3
}
}
Result(
data=InvalidateAllSessionsForUserResponse(
sessions_invalidated=3
)
)
byo.InvalidateAllSessionsForUserResponse{
SessionsInvalidated: 3,
}
InvalidateAllSessionsForUserResponse(
sessionsInvalidated=3
)
InvalidateAllSessionsForUserResponse
{
SessionsInvalidated = 3
}

Invalidate All Sessions For User Except One

Section titled “Invalidate All Sessions For User Except One”
Invalidates all sessions for a user except one. This is useful when implementing "log out all other devices" functionality.

Arguments

userId string required
The ID of the user whose sessions should be invalidated
sessionTokenToKeep string required
The session token that should remain active
sessionTags string[]
Filter to only invalidate sessions with specific tags

Successful Response

sessionsInvalidated number
The number of sessions that were invalidated

Error Types

UnexpectedError
An unexpected error occurred during the operation
const auth = createClient({ url, integrationKey });
const result = await auth.session.invalidateAllForUserExceptOne({
userId: "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
sessionTokenToKeep: "sess_vNCf0boJ..",
sessionTags: [
"type:high_security"
]
});
if (result.ok) {
console.log(`Invalidated ${result.data.sessionsInvalidated} sessions`);
} else {
console.log(`Error: ${result.error}`);
// Check result.error.type to handle specific errors
}
client = create_client(url=url, integration_key=integration_key)
result = await client.session.invalidate_all_for_user_except_one(
user_id="1189c444-8a2d-4c41-8b4b-ae43ce79a492",
session_token_to_keep="sess_vNCf0boJ..",
session_tags=[
"type:high_security"
]
)
if is_ok(result):
print(f"Invalidated {result.data.sessions_invalidated} sessions")
else:
print(f"Error: {result.error}")
# Check result.error.type to handle specific errors
client, err := byo.NewClient(url, integrationKey)
if err != nil {
log.Fatal(err)
}
result, err := client.Session.InvalidateAllForUserExceptOne(ctx, byo.InvalidateAllSessionsForUserExceptOneCommand{
UserID: "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
SessionTokenToKeep: "sess_vNCf0boJ...",
SessionTags: []string{"type:high_security"},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.SessionsInvalidated)
PropelAuthClient client = PropelAuthClient.create(url, integrationKey);
InvalidateAllSessionsForUserExceptOneCommand command = InvalidateAllSessionsForUserExceptOneCommand.builder()
.userId("1189c444-8a2d-4c41-8b4b-ae43ce79a492")
.sessionTokenToKeep("sess_vNCf0boJ..")
.sessionTags(Arrays.asList("type:high_security"))
.build();
try {
InvalidateAllSessionsForUserExceptOneResponse response = client.session.invalidateAllForUserExceptOne(command);
System.out.println("Invalidated " + response.getSessionsInvalidated() + " sessions");
} catch (InvalidateAllSessionsForUserExceptOneException e) {
System.out.println("Error: " + e.getMessage());
}
var client = new PropelAuthClient(new PropelAuthOptions { Url = url, IntegrationKey = integrationKey });
var command = new InvalidateAllSessionsForUserExceptOneCommand
{
UserId = "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
SessionTokenToKeep = "sess_vNCf0boJ..",
SessionTags = new List<string> { "type:high_security" }
};
try
{
var response = await client.Session.InvalidateAllForUserExceptOneAsync(command);
Console.WriteLine($"Invalidated {response.SessionsInvalidated} sessions");
}
catch (InvalidateAllSessionsForUserExceptOneException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Response
{
ok: true,
data: {
sessionsInvalidated: 5
}
}
Result(
data=InvalidateAllSessionsForUserExceptOneResponse(
sessions_invalidated=5
)
)
byo.InvalidateAllSessionsForUserExceptOneResponse{
SessionsInvalidated: 5,
}
InvalidateAllSessionsForUserExceptOneResponse(
sessionsInvalidated=5
)
InvalidateAllSessionsForUserExceptOneResponse
{
SessionsInvalidated = 5
}

Update tags or metadata for an existing session.

Arguments

sessionId string required
The session ID.
tagsToRemove string[]
A list of tags to remove from the session
tagsToAdd string[]
A list of tags to add to the session
newMetadata JsonValue
Additional information to store about the user session. Using this property will overwrite all existing metadata for the session.
patchMetadata JsonValue
Additional information to store about the user session. Using this property will add to the existing metadata for the session.

Successful Response

Returns an empty response on success


Error Types

SessionNotFound
The provided session ID was not found
ConflictingMetadataOptions
Both metadata arguments were included in the command. Only use one or the other
InvalidTagFormat
The tag properties are formatted incorrectly
CannotModifyOnCreateOnlyTags
Some of the tags you are adding or removing are in the on_create_only_tags field in the session config
UnexpectedError
An unexpected error occurred
const auth = createClient({ url, integrationKey });
const result = await auth.session.update({
sessionId: "JVAdUSsMc2UtjehFvzpNGm",
tagsToRemove: ["type:high_security"],
tagsToAdd: ["type:low_security"],
newMetadata: {
"example": "value"
},
// patchMetadata: {
// "example": "value"
// }
});
if (result.ok) {
console.log("Session updated successfully");
} else {
console.log(`Error: ${result.error}`);
}
client = create_client(url=url, integration_key=integration_key)
result = await client.session.update(
session_id="JVAdUSsMc2UtjehFvzpNGm",
tags_to_remove=["type:high_security"],
tags_to_add=["type:low_security"],
new_metadata={
"example": "value"
},
# patch_metadata={
# "example": "value"
# }
)
if is_ok(result):
print("Session updated successfully")
else:
print(f"Error: {result.error}")
client, err := byo.NewClient(url, integrationKey)
if err != nil {
log.Fatal(err)
}
_, err = client.Session.Update(ctx, byo.UpdateSessionCommand{
SessionID: "JVAdUSsMc2UtjehFvzpNGm",
TagsToRemove: []string{"type:high_security"},
TagsToAdd: []string{"type:low_security"},
NewMetadata: map[string]any{
"example": "value",
},
// PatchMetadata: map[string]any{
// "example": "value",
// },
})
if err != nil {
log.Fatal(err)
}
PropelAuthClient client = PropelAuthClient.create(url, integrationKey);
UpdateSessionCommand command = UpdateSessionCommand.builder()
.sessionId("JVAdUSsMc2UtjehFvzpNGm")
.tagsToRemove(Arrays.asList("type:high_security"))
.tagsToAdd(Arrays.asList("type:low_security"))
.newMetadata(JsonValue.of(Map.of("example", "value")))
// .patchMetadata(JsonValue.of(Map.of("example", "value")))
.build();
try {
UpdateSessionResponse response = client.session.update(command);
System.out.println("Session updated successfully");
} catch (UpdateSessionException.SessionNotFound e) {
System.out.println("Session not found");
} catch (UpdateSessionException e) {
System.out.println("Error: " + e.getMessage());
}
var client = new PropelAuthClient(new PropelAuthOptions { Url = url, IntegrationKey = integrationKey });
var command = new UpdateSessionCommand
{
SessionId = "JVAdUSsMc2UtjehFvzpNGm",
TagsToRemove = new List<string> { "type:high_security" },
TagsToAdd = new List<string> { "type:low_security" },
NewMetadata = JsonSerializer.SerializeToElement(new Dictionary<string, object>
{
{ "example", "value" }
})
// PatchMetadata = JsonSerializer.SerializeToElement(new Dictionary<string, object>
// {
// { "example", "value" }
// })
};
try
{
var response = await client.Session.UpdateAsync(command);
Console.WriteLine("Session updated successfully");
}
catch (UpdateSessionException.SessionNotFound ex)
{
Console.WriteLine("Session not found");
}
catch (UpdateSessionException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Response
{
ok: true,
data: {}
}
Result(
data=UpdateSessionResponse()
)
byo.UpdateSessionResponse{}
UpdateSessionResponse()
UpdateSessionResponse()

Update tags or metadata for multiple sessions.

Arguments

filter SessionsFilter required
Filter by a userId or session tags. Any matching sessions will be updated.
tagsToRemove string[]
A list of tags to remove from each session
tagsToAdd string[]
A list of tags to add to each session
newMetadata JsonValue
Additional information to store about the user session. Using this property will overwrite all existing metadata for each session.
patchMetadata JsonValue
Additional information to store about the user session. Using this property will add to the existing metadata for each session.

Successful Response

updatedCount number
Number of sessions that were updated

Error Types

ConflictingMetadataOptions
Both metadata arguments were included in the command. Only use one or the other
InvalidTagFormat
The tag properties are formatted incorrectly
CannotModifyOnCreateOnlyTags
Some of the tags you are adding or removing are in the on_create_only_tags field in the session config
UpdatingTooManySessionsAtOnce
Too many sessions match the filter criteria
UnexpectedError
An unexpected error occurred
const auth = createClient({ url, integrationKey });
const result = await auth.session.updateMany({
filter: {
userId: "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
sessionTags: ["type:high_security"]
},
tagsToRemove: ["type:high_security"],
tagsToAdd: ["type:low_security"],
newMetadata: {
"example": "value"
},
// patchMetadata: {
// "example": "value"
// }
});
if (result.ok) {
console.log(`Updated ${result.data.updatedCount} sessions`);
} else {
console.log(`Error: ${result.error}`);
}
client = create_client(url=url, integration_key=integration_key)
result = await client.session.update_many(
filter=SessionsFilter(
user_id="1189c444-8a2d-4c41-8b4b-ae43ce79a492",
session_tags=["type:high_security"]
),
tags_to_remove=["type:high_security"],
tags_to_add=["type:low_security"],
new_metadata={
"example": "value"
},
# patch_metadata={
# "example": "value"
# }
)
if is_ok(result):
print(f"Updated {result.data.updated_count} sessions")
else:
print(f"Error: {result.error}")
client, err := byo.NewClient(url, integrationKey)
if err != nil {
log.Fatal(err)
}
result, err := client.Session.UpdateMany(ctx, byo.UpdateSessionsCommand{
Filter: byo.SessionsFilter{
UserID: byo.String("1189c444-8a2d-4c41-8b4b-ae43ce79a492"),
SessionTags: []string{"type:high_security"},
},
TagsToRemove: []string{"type:high_security"},
TagsToAdd: []string{"type:low_security"},
NewMetadata: map[string]any{
"example": "value",
},
// PatchMetadata: map[string]any{
// "example": "value",
// },
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.UpdatedCount)
PropelAuthClient client = PropelAuthClient.create(url, integrationKey);
UpdateSessionsCommand command = UpdateSessionsCommand.builder()
.filter(SessionsFilter.builder()
.userId("1189c444-8a2d-4c41-8b4b-ae43ce79a492")
.sessionTags(Arrays.asList("type:high_security"))
.build())
.tagsToRemove(Arrays.asList("type:high_security"))
.tagsToAdd(Arrays.asList("type:low_security"))
.newMetadata(JsonValue.of(Map.of("example", "value")))
// .patchMetadata(JsonValue.of(Map.of("example", "value")))
.build();
try {
UpdateSessionsResponse response = client.session.updateMany(command);
System.out.println("Updated " + response.getUpdatedCount() + " sessions");
} catch (UpdateSessionsException.UpdatingTooManySessionsAtOnce e) {
System.out.println("Updating too many sessions at once");
} catch (UpdateSessionsException e) {
System.out.println("Error: " + e.getMessage());
}
var client = new PropelAuthClient(new PropelAuthOptions { Url = url, IntegrationKey = integrationKey });
var command = new UpdateSessionsCommand
{
Filter = new SessionsFilter
{
UserId = "1189c444-8a2d-4c41-8b4b-ae43ce79a492",
SessionTags = new List<string> { "type:high_security" }
},
TagsToRemove = new List<string> { "type:high_security" },
TagsToAdd = new List<string> { "type:low_security" },
NewMetadata = JsonSerializer.SerializeToElement(new Dictionary<string, object>
{
{ "example", "value" }
})
// PatchMetadata = JsonSerializer.SerializeToElement(new Dictionary<string, object>
// {
// { "example", "value" }
// })
};
try
{
var response = await client.Session.UpdateManyAsync(command);
Console.WriteLine($"Updated {response.UpdatedCount} sessions");
}
catch (UpdateSessionsException.UpdatingTooManySessionsAtOnce ex)
{
Console.WriteLine("Updating too many sessions at once");
}
catch (UpdateSessionsException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Response
{
ok: true,
data: {
updatedCount: 10
}
}
Result(
data=UpdateSessionsResponse(
updated_count=10
)
)
byo.UpdateSessionsResponse{
UpdatedCount: 10,
}
UpdateSessionsResponse(updatedCount=10)
UpdateSessionsResponse
{
UpdatedCount = 10
}

Retrieves the JSON Web Key Set (JWKS) containing your public keys. These are used to verify stateless tokens without making API calls to BYO.

Arguments


Successful Response

keys JwkKey[]
Array of public keys used to verify stateless tokens

Error Types

UnexpectedError
An unexpected error occurred during the operation
const auth = createClient({ url, integrationKey });
const result = await auth.session.getJwks({});
if (result.ok) {
console.log("JWKS fetched successfully");
// Cache and use result.data.keys to verify JWTs
} else {
console.log(`Error: ${result.error}`);
// Check result.error.type to handle specific errors
}
client = create_client(url=url, integration_key=integration_key)
result = await client.session.get_jwks()
if is_ok(result):
print("JWKS fetched successfully")
# Cache and use result.data.keys to verify JWTs
else:
print(f"Error: {result.error}")
# Check result.error.type to handle specific errors
client, err := byo.NewClient(url, integrationKey)
if err != nil {
log.Fatal(err)
}
result, err := client.Session.GetJwks(ctx, byo.GetJwksCommand{})
if err != nil {
log.Fatal(err)
}
fmt.Println(len(result.Keys))
PropelAuthClient client = PropelAuthClient.create(url, integrationKey);
GetJwksCommand command = GetJwksCommand.builder().build();
try {
GetJwksResponse response = client.session.getJwks(command);
System.out.println("JWKS fetched successfully");
// Cache and use response.getKeys() to verify JWTs
} catch (GetJwksException e) {
System.out.println("Error: " + e.getMessage());
}
var client = new PropelAuthClient(new PropelAuthOptions { Url = url, IntegrationKey = integrationKey });
var command = new GetJwksCommand();
try
{
var response = await client.Session.GetJwksAsync(command);
Console.WriteLine("JWKS fetched successfully");
// Cache and use response.Keys to verify JWTs
}
catch (GetJwksException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Response
{
ok: true,
data: {
keys: [
{
kty: "RSA",
kid: "stk_kug0nXf5IjMuQQlpvaEpdhRbD6JpxuZx",
use: "sig",
alg: "RS256",
n: "9pSayY4...",
e: "AQAB"
},
{
kty: "RSA",
kid: "stk_EVWEcamSadaJgNwRy4qunljgc0kDDdGP",
use: "sig",
alg: "RS256",
n: "sG2c9kr7b7H...",
e: "AQAB"
}
]
}
}
Result(
data=GetJwksResponse(
keys=[
JwkKey(
kty="RSA",
kid="stk_kug0nXf5IjMuQQlpvaEpdhRbD6JpxuZx",
use="sig",
alg="RS256",
n="9pSayY4...",
e="AQAB"
),
JwkKey(
kty="RSA",
kid="stk_EVWEcamSadaJgNwRy4qunljgc0kDDdGP",
use="sig",
alg="RS256",
n="sG2c9kr7b7H...",
e="AQAB"
)
]
)
)
byo.GetJwksResponse{
Keys: []byo.JwkKey{
{
Kty: "RSA",
Kid: "stk_kug0nXf5IjMuQQlpvaEpdhRbD6JpxuZx",
Use: "sig",
Alg: "RS256",
N: "9pSayY4...",
E: "AQAB",
},
},
}
GetJwksResponse(
keys=[
JwkKey(
kty="RSA",
kid="stk_kug0nXf5IjMuQQlpvaEpdhRbD6JpxuZx",
use="sig",
alg="RS256",
n="9pSayY4...",
e="AQAB"
),
JwkKey(
kty="RSA",
kid="stk_EVWEcamSadaJgNwRy4qunljgc0kDDdGP",
use="sig",
alg="RS256",
n="sG2c9kr7b7H...",
e="AQAB"
)
]
)
GetJwksResponse(
Keys=[
JwkKey(
Kty="RSA",
Kid="stk_kug0nXf5IjMuQQlpvaEpdhRbD6JpxuZx",
Use="sig",
Alg="RS256",
N="9pSayY4...",
E="AQAB"
),
JwkKey(
Kty="RSA",
Kid="stk_EVWEcamSadaJgNwRy4qunljgc0kDDdGP",
Use="sig",
Alg="RS256",
N="sG2c9kr7b7H...",
E="AQAB"
)
]
)

Creates a new JWKS with the option to deactivate existing JWKS.

Arguments

secsBeforeNewKeyBecomesDefault number required
Number of seconds before new stateless tokens are issued using the newly issued key.
secsBeforeExistingKeysAreDeactivated number required
Number of seconds before other JWKs are deactivated. Once deactivated, the JWKs will no longer be returned when using the Get JWKS command

Successful Response

newKeyId string
The ID of the newly created key
newKeyBecomesDefaultAt number
Unix timestamp when the new key becomes the default
existingKeysExpireAt number
Unix timestamp when existing keys will be deactivated

Error Types

RotationFailed
The JWKS could not be rotated
InvalidParameters
The command arguments are not valid
UnexpectedError
An unexpected error occurred during the operation
const auth = createClient({ url, integrationKey });
const result = await auth.session.rotateStatelessTokenKey({
secsBeforeNewKeyBecomesDefault: 1800,
secsBeforeExistingKeysAreDeactivated: 86400
});
if (result.ok) {
console.log(`New key created: ${result.data.newKeyId}`);
console.log(`Becomes default at: ${new Date(result.data.newKeyBecomesDefaultAt * 1000)}`);
} else {
console.log(`Error: ${result.error}`);
// Check result.error.type to handle specific errors
}
client = create_client(url=url, integration_key=integration_key)
result = await client.session.rotate_stateless_token_key(
secs_before_new_key_becomes_default=1800,
secs_before_existing_keys_are_deactivated=86400
)
if is_ok(result):
print(f"New key created: {result.data.new_key_id}")
print(f"Becomes default at: {result.data.new_key_becomes_default_at}")
else:
print(f"Error: {result.error}")
# Check result.error.type to handle specific errors
client, err := byo.NewClient(url, integrationKey)
if err != nil {
log.Fatal(err)
}
result, err := client.Session.RotateStatelessTokenKey(ctx, byo.RotateStatelessTokenKeyCommand{
SecsBeforeNewKeyBecomesDefault: 1800,
SecsBeforeExistingKeysAreDeactivated: 86400,
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.NewKeyID)
PropelAuthClient client = PropelAuthClient.create(url, integrationKey);
RotateStatelessTokenKeyCommand command = RotateStatelessTokenKeyCommand.builder()
.secsBeforeNewKeyBecomesDefault(1800)
.secsBeforeExistingKeysAreDeactivated(86400)
.build();
try {
RotateStatelessTokenKeyResponse response = client.session.rotateStatelessTokenKey(command);
System.out.println("New key created: " + response.getNewKeyId());
System.out.println("Becomes default at: " + response.getNewKeyBecomesDefaultAt());
} catch (RotateStatelessTokenKeyException.RotationFailed e) {
System.out.println("Rotation failed: " + e.getDetails());
} catch (RotateStatelessTokenKeyException.InvalidParameters e) {
System.out.println("Invalid parameters: " + e.getDetails());
} catch (RotateStatelessTokenKeyException e) {
System.out.println("Error: " + e.getMessage());
}
var client = new PropelAuthClient(new PropelAuthOptions { Url = url, IntegrationKey = integrationKey });
var command = new RotateStatelessTokenKeyCommand
{
SecsBeforeNewKeyBecomesDefault = 1800,
SecsBeforeExistingKeysAreDeactivated = 86400
};
try
{
var response = await client.Session.RotateStatelessTokenKeyAsync(command);
Console.WriteLine($"New key created: {response.NewKeyId}");
Console.WriteLine($"Becomes default at: {response.NewKeyBecomesDefaultAt}");
}
catch (RotateStatelessTokenKeyException.RotationFailed ex)
{
Console.WriteLine($"Rotation failed: {ex.Details}");
}
catch (RotateStatelessTokenKeyException.InvalidParameters ex)
{
Console.WriteLine($"Invalid parameters: {ex.Details}");
}
Response
{
ok: true,
data: {
newKeyId: "stk_n3GlUdKNxD8_tGL6uBuhm9wa294xp4O1",
newKeyBecomesDefaultAt: 1755273937,
existingKeysExpireAt: 1755274022
}
}
Result(
data=RotateStatelessTokenKeyResponse(
new_key_id="stk_n3GlUdKNxD8_tGL6uBuhm9wa294xp4O1",
new_key_becomes_default_at=1755273937,
existing_keys_expire_at=1755274022
)
)
byo.RotateStatelessTokenKeyResponse{
NewKeyID: "stk_n3GlUdKNxD8_tGL6uBuhm9wa294xp4O1",
NewKeyBecomesDefaultAt: 1755273937,
ExistingKeysExpireAt: 1755274022,
}
RotateStatelessTokenKeyResponse(
newKeyId="stk_n3GlUdKNxD8_tGL6uBuhm9wa294xp4O1",
newKeyBecomesDefaultAt=1755273937,
existingKeysExpireAt=1755274022
)
RotateStatelessTokenKeyResponse
{
NewKeyId = "stk_n3GlUdKNxD8_tGL6uBuhm9wa294xp4O1",
NewKeyBecomesDefaultAt = 1755273937,
ExistingKeysExpireAt = 1755274022
}

Creates a device challenge for device trust. The challenge is sent to the user's device to verify it.

Arguments

userAgent string
The user agent of the request
ipAddress string
The IP address of the request

Successful Response

deviceChallenge string
The challenge token to send to the device
expiresAt number
Unix timestamp when the challenge expires

Error Types

UnexpectedError
An unexpected error occurred during the operation
const auth = createClient({ url, integrationKey });
const result = await auth.session.device.createChallenge({
userAgent: req.headers["user-agent"],
ipAddress: req.socket.remoteAddress
});
if (result.ok) {
console.log("Device challenge created");
// Send result.data.deviceChallenge to the client
} else {
console.log(`Error: ${result.error}`);
// Check result.error.type to handle specific errors
}
client = create_client(url=url, integration_key=integration_key)
result = await client.session.device.create_challenge(
user_agent=request.headers.get("user-agent"),
ip_address=request.client.host
)
if is_ok(result):
print("Device challenge created")
# Send result.data.device_challenge to the client
else:
print(f"Error: {result.error}")
# Check result.error.type to handle specific errors
client, err := byo.NewClient(url, integrationKey)
if err != nil {
log.Fatal(err)
}
result, err := client.Session.Device.CreateChallenge(ctx, byo.CreateDeviceChallengeCommand{
UserAgent: byo.String(r.UserAgent()),
IPAddress: byo.String(r.RemoteAddr),
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result.DeviceChallenge)
PropelAuthClient client = PropelAuthClient.create(url, integrationKey);
CreateDeviceChallengeCommand command = CreateDeviceChallengeCommand.builder()
.userAgent(request.getHeader("User-Agent"))
.ipAddress(request.getRemoteAddr())
.build();
try {
CreateDeviceChallengeResponse response = client.session.device.createChallenge(command);
System.out.println("Device challenge created");
// Send response.getDeviceChallenge() to the client
} catch (CreateDeviceChallengeException e) {
System.out.println("Error: " + e.getMessage());
}
var client = new PropelAuthClient(new PropelAuthOptions { Url = url, IntegrationKey = integrationKey });
var command = new CreateDeviceChallengeCommand
{
UserAgent = request.Headers["User-Agent"],
IpAddress = request.HttpContext.Connection.RemoteIpAddress?.ToString()
};
try
{
var response = await client.Session.Device.CreateChallengeAsync(command);
Console.WriteLine("Device challenge created");
// Send response.DeviceChallenge to the client
}
catch (CreateDeviceChallengeException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Response
{
ok: true,
data: {
deviceChallenge: "cha_4mGVEbsLhoqt8QBHLBtj9E7yskxzvTgP",
expiresAt: 1755718568
}
}
Result(
data=CreateDeviceChallengeResponse(
device_challenge="cha_4mGVEbsLhoqt8QBHLBtj9E7yskxzvTgP",
expires_at=1755718568
)
)
byo.CreateDeviceChallengeResponse{
DeviceChallenge: "cha_4mGVEbsLhoqt8QBHLBtj9E7yskxzvTgP",
ExpiresAt: 1755718568,
}
CreateDeviceChallengeResponse(
deviceChallenge="cha_4mGVEbsLhoqt8QBHLBtj9E7yskxzvTgP",
expiresAt=1755718568
)
CreateDeviceChallengeResponse
{
DeviceChallenge = "cha_4mGVEbsLhoqt8QBHLBtj9E7yskxzvTgP",
ExpiresAt = 1755718568
}

Registers a new device and pairs it with an existing user session.

Arguments

signedDeviceChallenge string required
The signed device challenge. See the Device Registration docs for more information.
rememberDevice boolean required
Whether to remember this device for future logins
sessionToken string
The session token to associate with this device
sessionId string
The session ID to associate with this device
requestUrl string
The URL of the request
requestMethod string
The HTTP method of the request
userAgent string
The user agent of the request
ipAddress string
The IP address of the request

Successful Response

newDeviceDetected boolean
Whether this is a newly detected device

Error Types

SessionNotFound
The specified session was not found
NewDeviceChallengeRequired
A new device challenge is required
InvalidDeviceRegistration
The device registration data is invalid
DeviceAlreadyRegistered
This device is already registered
UnexpectedError
An unexpected error occurred during the operation
const auth = createClient({ url, integrationKey });
const result = await auth.session.device.register({
signedDeviceChallenge: "eyJhbGciOiJFUzI1NiIsInR5cCI6ImRw..",
rememberDevice: true,
sessionToken: "sess_vNCf0boJ...",
requestUrl: "https://api.example.com/api/user",
requestMethod: "POST",
userAgent: req.headers["user-agent"],
ipAddress: req.socket.remoteAddress
});
if (result.ok) {
if (result.data.newDeviceDetected) {
console.log("New device registered");
}
} else {
console.log(`Error: ${result.error}`);
// Check result.error.type to handle specific errors
}
client = create_client(url=url, integration_key=integration_key)
result = await client.session.device.register(
signed_device_challenge="eyJhbGciOiJFUzI1NiIsInR5cCI6ImRw..",
remember_device=True,
session_token="sess_vNCf0boJ...",
request_url="https://api.example.com/api/user",
request_method="POST",
user_agent=request.headers.get("user-agent"),
ip_address=request.client.host
)
if is_ok(result):
if result.data.new_device_detected:
print("New device registered")
else:
print(f"Error: {result.error}")
# Check result.error.type to handle specific errors
client, err := byo.NewClient(url, integrationKey)
if err != nil {
log.Fatal(err)
}
result, err := client.Session.Device.Register(ctx, byo.RegisterDeviceCommand{
SignedDeviceChallenge: "eyJhbGciOiJFUzI1NiIsInR5cCI6ImRw..",
RememberDevice: true,
SessionToken: byo.String("sess_vNCf0boJ..."),
RequestURL: byo.String("https://api.example.com/api/user"),
RequestMethod: byo.String("POST"),
UserAgent: byo.String(r.UserAgent()),
IPAddress: byo.String(r.RemoteAddr),
})
if err != nil {
log.Fatal(err)
}
if result.NewDeviceDetected {
fmt.Println("New device registered")
}
PropelAuthClient client = PropelAuthClient.create(url, integrationKey);
RegisterDeviceCommand command = RegisterDeviceCommand.builder()
.signedDeviceChallenge("eyJhbGciOiJFUzI1NiIsInR5cCI6ImRw..")
.rememberDevice(true)
.sessionToken("sess_vNCf0boJ...")
.requestUrl("https://api.example.com/api/user")
.requestMethod("POST")
.userAgent(request.getHeader("User-Agent"))
.ipAddress(request.getRemoteAddr())
.build();
try {
RegisterDeviceResponse response = client.session.device.register(command);
if (response.getNewDeviceDetected()) {
System.out.println("New device registered");
}
} catch (RegisterDeviceException.NewDeviceChallengeRequired e) {
// Handle new device challenge
String challenge = e.getDetails().getDeviceChallenge();
} catch (RegisterDeviceException e) {
System.out.println("Error: " + e.getMessage());
}
var client = new PropelAuthClient(new PropelAuthOptions { Url = url, IntegrationKey = integrationKey });
var command = new RegisterDeviceCommand
{
SignedDeviceChallenge = "eyJhbGciOiJFUzI1NiIsInR5cCI6ImRw..",
RememberDevice = true,
SessionToken = "sess_vNCf0boJ...",
RequestUrl = "https://api.example.com/api/user",
RequestMethod = "POST",
UserAgent = Request.Headers["User-Agent"],
IpAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString()
};
try
{
var response = await client.Session.Device.RegisterAsync(command);
if (response.NewDeviceDetected)
{
Console.WriteLine("New device registered");
}
}
catch (RegisterDeviceException.NewDeviceChallengeRequired ex)
{
// Handle new device challenge
var challenge = ex.Details.DeviceChallenge;
}
catch (RegisterDeviceException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Response
{
ok: true,
data: {
newDeviceDetected: true
}
}
Result(
data=RegisterDeviceResponse(
new_device_detected=True
)
)
byo.RegisterDeviceResponse{
NewDeviceDetected: true,
}
RegisterDeviceResponse(newDeviceDetected=true)
RegisterDeviceResponse { NewDeviceDetected = true }

You can configure the default session settings, such as session length and the number of allowed concurrent sessions, in the 'session_config.jsonc' file.

Arguments

absolute_lifetime_secs number
Controls amount of seconds before a session expires. Defaults to 1209600 (14 days)
inactivity_timeout_secs number
Amount of seconds of inactivity before session becomes invalid. A session is active when it is validated. Defaults to no inactivity timeout.
max_concurrent_sessions_per_user number
The maximum number of valid sessions per user. Defaults to 8, max is 20.
on_session_limit_exceeded string
Action to take when the session limit set by max_concurrent_sessions_per_user is exceeded. Must equal one of the following:
  • drop_oldest: Remove the oldest session(s) to make room (default)
  • reject_new: Reject the new session creation request
  • drop_newest: Remove the most recently created session(s) to make room
  • drop_least_recently_active: Remove the least recently active session(s)
disallow_ip_address_changes boolean
Whether to invalidate sessions when an IP address change is detected. Defaults to false.
ip_allowlist string[]
Only IP addresses included in the allowlist will be allowed to create and validate sessions. Defaults to not being set.
{
// Required
"defaults": {
"absolute_lifetime_secs": 1209600,
"inactivity_timeout_secs": 3600,
"max_concurrent_sessions_per_user": 8,
"on_session_limit_exceeded": "drop_oldest",
"disallow_ip_address_changes": true
},
// Optional
"tags": [
{
"tag": "type:low_security",
"absolute_lifetime_secs": 1209600,
"max_concurrent_sessions_per_user": 20,
"on_session_limit_exceeded": "drop_least_recently_active"
},
{
"tag": "type:high_security",
"absolute_lifetime_secs": 3600,
"max_concurrent_sessions_per_user": 1,
"on_session_limit_exceeded": "drop_least_recently_active",
"ip_allowlist": ["10.0.0.1/32"]
}
]
}