So instead of ctx.Redirect(http.StatusSeeOther, "/") I need them to log back in. I currently have this function redirecting them to ‘/login’.
This works in a new browser session with no auth session cookie.
But it breaks if they’ve already logged in and then the auth session cookie expires.
In that case redirecting them to /login doesn’t force the login page. It just sends them back to the app as if they had already successfully logged in.
So it’s essentially a permanent session.
So far nothing I have tried has worked.
Redirecting them to ‘/login’ and redirecting them to ‘/logout’ don’t work.
You’ll need to modify your authentication middleware to properly clear both your application session and the Auth0 session. Here’s how you can handle this:
First, create a logout handler if you haven’t already:
func LogoutHandler(ctx *gin.Context) {
domain := os.Getenv("AUTH0_DOMAIN")
clientID := os.Getenv("AUTH0_CLIENT_ID")
returnTo := os.Getenv("AUTH0_CALLBACK_URL") // or whatever URL you want to return to
// Clear the local session
session := sessions.Default(ctx)
session.Clear()
session.Save()
// Redirect to Auth0 logout endpoint
logoutUrl := fmt.Sprintf(
"https://%s/v2/logout?client_id=%s&returnTo=%s",
domain,
clientID,
returnTo,
)
ctx.Redirect(http.StatusTemporaryRedirect, logoutUrl)
}
Then modify your IsAuthenticated middleware:
func IsAuthenticated(ctx *gin.Context) {
session := sessions.Default(ctx)
if session.Get("profile") == nil {
// Clear any existing session data
session.Clear()
session.Save()
// Redirect to logout handler instead of directly to login
ctx.Redirect(http.StatusSeeOther, "/logout")
ctx.Abort() // Important: stop the middleware chain
return
}
ctx.Next()
}
Make sure your routes are set up correctly:
router.GET("/logout", LogoutHandler)
router.GET("/callback", CallbackHandler)
// ... other routes
The key points here are:
When the session is invalid, we redirect to the logout handler instead of directly to login
The logout handler clears both your application session and the Auth0 session
The ctx.Abort() call is important to stop the middleware chain
Code block may not be perfect but Hope this helps.