Session
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.
Protect routes
You can protect routes by checking for a session cookie.
- Express (JS)
- Next.js
- Go
- Java
export const createRequireAuth = (ory, baseUrl = process.env.ORY_SDK_URL) => {
return async (req, res, next) => {
try {
const { data: session } = await ory.toSession({
cookie: req.header("cookie"),
})
req.session = session
next()
} catch (error) {
res.redirect(`${baseUrl}/self-service/login/browser`)
}
}
}
export const registerSessionRoute = (app, requireAuth) => {
app.get("/session", requireAuth, (req, res) => {
res.json(req.session.identity.traits) // { email: 'newtestuser@gmail.com' }
})
}
./middleware.ts
import { NextResponse, NextRequest } from "next/server"
import ory from "@/lib/ory"
export async function middleware(request: NextRequest) {
try {
await ory.toSession({
cookie: request.headers.get("cookie") || "",
})
// If toSession() doesn't throw, the session is valid
return NextResponse.next()
} catch (error) {
return NextResponse.redirect(
`${process.env.ORY_SDK_URL}/self-service/login/browser`,
)
}
}
// Configure which routes to protect
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico|public).*)"],
}
middleware.go
package main
import (
"context"
"errors"
"log"
"net/http"
ory "github.com/ory/client-go"
)
func (app *App) sessionMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
log.Printf("Checking authentication status\n")
// Pass cookies to Ory's ToSession endpoint
cookies := request.Header.Get("Cookie")
// Verify session with Ory
session, _, err := app.ory.FrontendAPI.ToSession(request.Context()).Cookie(cookies).Execute()
// Redirect to login if session doesn't exist or is inactive
if err != nil || (err == nil && !*session.Active) {
log.Printf("No active session, redirecting to login\n")
// Redirect to the login page
http.Redirect(writer, request, app.tunnelUrl+"/self-service/login/browser", http.StatusSeeOther)
return
}
// Add session to context for the handler
ctx := withSession(request.Context(), session)
next.ServeHTTP(writer, request.WithContext(ctx))
}
}
func withSession(ctx context.Context, v *ory.Session) context.Context {
return context.WithValue(ctx, "req.session", v)
}
func getSession(ctx context.Context) (*ory.Session, error) {
session, ok := ctx.Value("req.session").(*ory.Session)
if !ok || session == nil {
return nil, errors.New("session not found in context")
}
return session, nil
}
// Dashboard page protected by middleware
mux.Handle("/", app.sessionMiddleware(app.dashboardHandler))
RequireAuth.java
package session;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import sh.ory.ApiException;
import sh.ory.api.FrontendApi;
import sh.ory.model.Session;
import java.io.IOException;
public class RequireAuth implements HandlerInterceptor {
private final FrontendApi ory;
private final String baseUrl;
public RequireAuth(FrontendApi ory, String baseUrl) {
this.ory = ory;
this.baseUrl = baseUrl;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
String cookieHeader = request.getHeader("Cookie");
try {
Session session = ory.toSession(null, cookieHeader, null);
if (session != null && session.getActive() != null && session.getActive()) {
// Store session in request attribute
request.setAttribute("session", session);
return true;
}
} catch (ApiException e) {
// Session is invalid or doesn't exist
}
// Redirect to login page
response.sendRedirect(baseUrl + "/self-service/login/browser");
return false;
}
}
SessionHandler.java
package session;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sh.ory.model.Session;
@RestController
public class SessionHandler {
@GetMapping("/session")
public ResponseEntity<Object> getSession(HttpServletRequest request) {
Session session = (Session) request.getAttribute("session");
if (session != null && session.getIdentity() != null && session.getIdentity().getTraits() != null) {
return ResponseEntity.ok(session.getIdentity().getTraits());
}
return ResponseEntity.notFound().build();
}
}
Refresh sessions
You can refresh user sessions to extend their expiration time:
- Express (JS)
- Next.js
- Go
- Java
export const registerRefreshSessionRoute = (app, baseUrl) => {
app.get("/refresh-session", async (req, res) => {
// Redirect to login with refresh=true parameter
res.redirect(`${baseUrl}/ui/login?refresh=true`)
})
}
api/refresh-session/route.ts
import { NextResponse } from "next/server"
export async function GET() {
return NextResponse.redirect(
`${process.env.ORY_SDK_URL}/self-service/login/browser?refresh=true`,
)
}
refresh_handler.go
// refresh_handler.go
package main
import (
"net/http"
)
// RefreshSessionHandler handles the /refresh-session route
func (app *App) refreshSessionHandler(writer http.ResponseWriter, request *http.Request) {
// Redirect to Ory login UI with refresh=true parameter
http.Redirect(writer, request, app.tunnelUrl+"/self-service/login/browser?refresh=true", http.StatusSeeOther)
}
RefreshSessionHandler.java
package session;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
@RestController
public class RefreshSessionHandler {
private final String baseUrl;
public RefreshSessionHandler(String baseUrl) {
this.baseUrl = baseUrl;
}
@GetMapping("/refresh-session")
public void refreshSession(HttpServletResponse response) throws IOException {
// Redirect to login with refresh=true parameter
response.sendRedirect(baseUrl + "/ui/login?refresh=true");
}
}
Configure session settings in Ory Console
You can configure various session-related settings through the Ory Console. Learn how to:
- Configure Session lifespan
- Allow users to access sensitive settings in their profile like changing credentials.