Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to protected resource or original/saved request after Servlet 3.0 HttpServletRequest#login() authentication?

As expected, the login page loads when a protected/secure resource is requested:

<login-config>
    <auth-method>FORM</auth-method>
    <realm-name>jdbc</realm-name>
    <form-login-config>
        <form-login-page>/login.xhtml</form-login-page>
        <form-error-page>/login.xhtml</form-error-page>
    </form-login-config>
</login-config>

I understand j_security_check will automatically forward to the protected/secure resource if authentication is successful:

<form method="post" action="j_security_check">
    <input type="text" name="j_username">
    <input type="password" name= "j_password">
</form>

However, I would like to allow users to register (or login) to continue so I've used JSF 2.0: <h:form..., EL: #{loginBean.register()}..., etc... and I'm authenticating programmatically with Servlet 3.0:

public void register() {
    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();

    try {
        // Register...

        request.login(this.username, this.password);

        // Redirect to the protected/secure resource...

    } catch (ServletException e) {
        ...
    }
}

How do I find out what that originally requested resource was? Possibly:

  • Get "saved request" from session (container specific)?
  • Try access the "original request" somehow (where)?
  • Anything related to the request dispatcher (wild guess)?
  • Use the "referer" header (bad idea)?
  • Create a server authentication module (SAM) (not simple)?

Any advice would be very much appreciated!

like image 434
Grant Shield Avatar asked Feb 28 '11 15:02

Grant Shield


1 Answers

The login page is under the covers opened by a forward and the original request URI is available as request attribute with the name javax.servlet.forward.request_uri.

So:

String uri = request.getAttribute("javax.servlet.forward.request_uri");

or, more JSF-ish:

String uri = externalContext.getRequestMap().get("javax.servlet.forward.request_uri");
like image 99
BalusC Avatar answered Oct 19 '22 21:10

BalusC