Skip to main content

Session management

After a user has logged in, Ory creates a session cookie that your application can use to verify the user's authentication status. This guide shows how to work with sessions in your application.

Checking session status

You'll need to verify if a user is authenticated before allowing access to protected resources. Here's how to implement session verification:

  1. Verify the session

    Check if the user has a valid session cookie

  2. Access identity information

    Retrieve user details from the session

  3. Handle unauthenticated users

    Redirect to login if no valid session exists

Session verification with express.js

// Using the Ory SDK instance from the sign-in guide

// Middleware to verify sessions
const requireAuth = async (req, res, next) => {
try {
const { data: session } = await ory.toSession({
cookie: req.header("cookie"),
})

// Store session in request for use in route handlers
req.session = session
next()
} catch (error) {
// No valid session, redirect to Ory login UI
res.redirect(`${basePath}/ui/login`)
}
}

Protecting routes

Common patterns for protecting routes in your application:

// Using the requireAuth middleware defined above

// Apply the middleware to routes that need protection
app.get("/dashboard", requireAuth, (req, res) => {
// Access user data from the session
const user = req.session.identity
res.render("dashboard", { user })
})

app.get("/settings", requireAuth, (req, res) => {
res.render("settings", { user: req.session.identity })
})

Refresh sessions

You can refresh user sessions to extend their expiration time:

// Force session refresh by prompting re-authentication
app.get("/refresh-session", async (req, res) => {
const basePath = process.env.ORY_SDK_URL || "http://localhost:4000"
// Redirect to login with refresh=true parameter
res.redirect(`${basePath}/ui/login?refresh=true&return_to=/dashboard`)
})

// Refresh a session programmatically
async function refreshSession(req, res, next) {
try {
const { data: session } = await ory.refreshSession({
cookie: req.header("cookie"),
})

// Session is now refreshed
req.session = session
next()
} catch (error) {
// Error handling
res.redirect(`${basePath}/ui/login`)
}
}

Revoke sessions

There are times when you need to terminate user sessions, such as after a password change or for security reasons:

// Revoke all sessions except the current one
app.post("/revoke-other-sessions", requireAuth, async (req, res) => {
try {
await ory.revokeOtherSessions({
cookie: req.header("cookie"),
})
res.redirect("/settings")
} catch (error) {
res.status(500).send("Failed to revoke sessions")
}
})

// Revoke a specific session
app.post("/revoke-session/:id", requireAuth, async (req, res) => {
try {
await ory.revokeSession({
id: req.params.id,
})
res.redirect("/settings")
} catch (error) {
res.status(500).send("Failed to revoke session")
}
})

// Revoke current session (logout)
app.post("/logout", async (req, res) => {
try {
const { data } = await ory.createBrowserLogoutFlow({
cookie: req.header("cookie"),
})
res.redirect(data.logout_url)
} catch (error) {
res.redirect("/")
}
})

Configure automatic session revocation

You can configure Ory to automatically revoke all active sessions when a user changes their password:

  1. Go to AuthenticationSessions
  2. Configure Revoke sessions after password change
  3. Click Save

Configuring session settings in Ory Console

You can configure various session-related settings through the Ory Console. Learn how to:

Next steps

Now that you've learned how to manage user sessions, you can:

  1. Implement Multi-factor Authentication
  2. Add Password Reset Flows
  3. Set Up Email Verification
  4. Explore OpenID Connect Integration