SpringUserFramework icon indicating copy to clipboard operation
SpringUserFramework copied to clipboard

Persistent postLogin Redirect URL in HTTPSession

Open devondragon opened this issue 11 months ago • 0 comments

Summary

Enhance login behavior by introducing a persistent postLogin redirect URL stored in the HTTPSession, similar to Spring Security’s targetUrl, but lasting beyond a single redirect. This will allow users to be redirected to their intended destination even after multiple steps (e.g., login, registration, or other intermediate flows).

Use Case & Motivation

  • A Login button on various parts of the site should allow users to log in and return to where they left off.
  • The login page should capture the intended redirect target, either via:
    • A query parameter (e.g., ?redirectUrl=/dashboard)
    • Referrer header (if applicable)
  • This redirect target should be stored in the HTTPSession to persist beyond a single Spring Security redirect.
  • Custom Authentication Success Handler: A custom implementation of SavedRequestAwareAuthenticationSuccessHandler will check for the session-stored redirect URL and use it as the targetUrl.
  • Support for Registration Flow: If registration automatically logs in the user, the same mechanism should apply. Additionally, it may persist a preferred post-login destination in the user's profile for first-time logins after registration.

Proposed Implementation

1. Capture Redirect URL in Login Page Controller

  • If a redirectUrl query parameter is provided, store it in the HTTPSession.
  • If no query parameter is provided, fall back to the Referer header (if available and safe).
  • Ensure only safe URLs (same-origin, no open redirects) are stored.

2. Modify Authentication Success Handling

  • Extend SavedRequestAwareAuthenticationSuccessHandler to check for a session-stored postLoginRedirectUrl.
  • If found, use it as the targetUrl, otherwise fallback to the default behavior.
  • Clear the session-stored redirect after usage to avoid unintended reuse.

3. Registration Support (Optional)

  1. If the registration flow logs in the user, apply the same redirect logic.
  2. Consider persisting a "preferred post-login page" on the user profile to provide a selection on the first login post-registration.

Acceptance Criteria

✅ Users who click "Login" from a specific page and complete authentication are redirected back to the intended page. ✅ Redirect URL persists across multiple redirects if necessary. ✅ Safe handling of URLs (prevents open redirects). ✅ Works for both login and registration (if the latter logs in the user). ✅ Unit tests cover expected behaviors and edge cases.

Additional Notes

  • This should work seamlessly with Spring Security’s existing redirect mechanisms while providing a persistent fallback.
  • Should consider security concerns (e.g., validating that redirects stay within the application's domain).

devondragon avatar Feb 07 '25 13:02 devondragon