Implementing user login
The login flow authenticates existing users in your application. This guide shows how to implement a secure login process that authenticates users and creates sessions.
Login flow
Initialize a login flow
Set up the SDK to communicate with your Ory instance
Redirect to login UI
Check for session and redirect to Ory login when needed
Initialize the login flow
First, set up the SDK and create a new login flow. This step contacts the Ory API to create a flow that guides users through login.
- JavaScript/Node.js
- React
- Next.js
- Go
- cURL
Initialize SDK
const { Configuration, FrontendApi } = require("@ory/client")
// Initialize the SDK
const basePath = process.env.ORY_SDK_URL || "http://localhost:4000"
const ory = new FrontendApi(
new Configuration({
basePath,
credentials: "include",
}),
)
Login / Register
const requireAuth = async (req, res, next) => {
try {
const { data: session } = await ory.toSession({ cookie: req.header("cookie") })
req.session = session
next()
} catch (error) {
// No valid session, redirect to login
res.redirect(`${basePath}/ui/login`)
}
}
Initialize SDK
const { Configuration, FrontendApi } = require("@ory/client")
// Initialize the SDK
const basePath = process.env.ORY_SDK_URL || "http://localhost:4000"
const ory = new FrontendApi(
new Configuration({
basePath,
credentials: "include",
}),
)
Login / Register
This checks if the user has an active session and redirects to the login UI if needed.
export default function Login() {
const [session, setSession] = useState<Session | null>(null)
const [loading, setLoading] = useState(true)
const basePath = process.env.REACT_APP_ORY_SDK_URL || "http://localhost:4000"
useEffect(() => {
// Check if the user is authenticated
const checkSession = async () => {
try {
const session = await ory.toSession()
setSession(session)
setLoading(false)
} catch (error) {
// No valid session, redirect to Ory login
window.location.href = `${basePath}/ui/login`
}
}
checkSession()
}, [])
}
Initialize SDK
const { Configuration, FrontendApi } = require("@ory/client")
// Initialize the SDK
const basePath = process.env.ORY_SDK_URL || "http://localhost:4000"
const ory = new FrontendApi(
new Configuration({
basePath,
credentials: "include",
}),
)
Login / Register
This checks if the user has an active session and redirects to the Ory login page if needed.
const [session, setSession] = useState<Session | null>(null)
const basePath = process.env.NEXT_PUBLIC_ORY_SDK_URL || "http://localhost:4000"
useEffect(() => {
// Check if the user is authenticated
const checkSession = async () => {
try {
const session = await ory.toSession()
setSession(session)
} catch (error) {
// No valid session, redirect to Ory login
window.location.href = `${basePath}/ui/login`
}
}
checkSession()
}, [])
Initialize SDK
This initializes the Ory SDK and sets up the API client.
package main
import (
"fmt"
"os"
ory "github.com/ory/client-go"
)
type App struct {
ory *ory.APIClient
tunnelUrl string
}
func init() {
tunnelPort := os.Getenv("TUNNEL_PORT")
if tunnelPort == "" {
tunnelPort = "4000"
}
// Configure Ory client to use tunnel
c := ory.NewConfiguration()
c.Servers = ory.ServerConfigurations{{URL: fmt.Sprintf("http://localhost:%s", tunnelPort)}}
// Store the tunnel URL for redirects
tunnelUrl := fmt.Sprintf("http://localhost:%s", tunnelPort)
app := &App{
ory: ory.NewAPIClient(c),
tunnelUrl: tunnelUrl,
}
}
Session Middleware
This checks for an active session and redirects to login if needed.
func (app *App) sessionMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request) {
// 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 no active session
if err != nil || (err == nil && !*session.Active) {
http.Redirect(writer, request, app.tunnelUrl+"/ui/login",
http.StatusSeeOther)
return
}
// Add session to context for the handler
ctx := withSession(request.Context(), session)
next.ServeHTTP(writer, request.WithContext(ctx))
}
}
Create login flow
curl -X GET \
'https://$PROJECT_SLUG.projects.oryapis.com/self-service/login/browser' \
-H 'Accept: application/json' \
--verbose
After successful login
After a successful login, Ory:
- Creates a session for the user
- Sets a secure session cookie in the browser
- Redirects the user to the specified return URL or default location
Your application should then check for the presence of this session cookie to determine if a user is authenticated.
Next steps
Now that you have implemented login functionality, you should: