Sign in
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.
- Expressjs
- Next.js
- Go
app.get("/", (req, res) => {
ory
.toSession({ cookie: req.header("cookie") })
.then((data) => res.json(data))
.catch(() => res.redirect(`${baseUrl}/ui/login`))
})
This checks if the user has an active session and redirects to the Ory login page if needed.
export default function Page() {
const [session, setSession] = useState<Session | null>(null)
useEffect(() => {
// Check if the user is authenticated
const checkSession = async () => {
try {
const session = await ory.toSession()
setSession(session)
} catch (error) {
// No valid session found, redirect to Ory login
window.location.href = `${basePath}/ui/login`
}
}
checkSession()
}, [])
return (
<>
<pre>{JSON.stringify(session, null, 2)}</pre>
</>
)
}
This checks for an active session and redirects to login if needed.
login_handler.go
package main
import (
"io"
"net/http"
)
// LoginHandler handles the /login route
func (app *App) loginHandler(writer http.ResponseWriter, request *http.Request) {
// Get cookies from the request
cookies := request.Header.Get("Cookie")
// Try to verify session with Ory
session, response, err := app.ory.FrontendAPI.ToSession(request.Context()).Cookie(cookies).Execute()
// If there's an error or session is not active, redirect to login UI
if err != nil || (err == nil && !*session.Active) {
http.Redirect(writer, request, app.tunnelUrl+"/ui/login", http.StatusSeeOther)
return
}
// If session is valid, send the session data as JSON response
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(http.StatusOK)
// Use io.Copy to copy the response body to the writer
io.Copy(writer, response.Body)
}
After 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.