0

Basically, I have created a webapp - which should restrict access to users who are not logged in to the system.

The system is utilising a "user" object to persist session state between the client and the server, this effectively serves as the cookie.

The urls /index, /login, /register can be accessed by all users visiting the webapp, regardless if they are registered, or logged in.

However, anything outside of this url boundary should redirect the user to the registration page.

In order to achieve this, I've been using springs HandlerInterceptorAdapter - and implementing some basic checking in the preHandle(). However - everything I've come up with is getting caught up in a redirect loop.

Any and all suggestions on how to resolve this are most welcome and appreciated. Any advice, articles or examples on where I can expand my knowledge of this use case are most appreciated. Comments on if and why my approach is flawed, and what best practices are I am keen to hear.

Keep in mind id rather not go down the spring security route just yet - trying to keep this as simple as possible.

@Override
public boolean preHandle(HttpServletRequest request,
                         HttpServletResponse response,
                         Object handler) throws Exception {

    HttpSession session = request.getSession();
    User user;

    try {
        user = (User) request.getAttribute("user");
    } catch (Exception e) {
        e.toString();
        return true;
    }


    if (user == null && request.getPathInfo() != "/login" 
     || user == null && request.getPathInfo() != "/register"
     || user == null && request.getPathInfo() == "/index") {

        response.sendRedirect("register");
        return true;
    } else {
        return true;
    }
}
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
Catresl
  • 195
  • 2
  • 15
  • Are you sure you've created a webapp? The code you're showing is so full of mistakes that it's unlikely that you have anything working. – Kayaman Sep 15 '16 at 16:19
  • in what sense ? – Catresl Sep 15 '16 at 19:23
  • Start with what I marked as duplicate, then explain the `e.toString();` line. Usually this kind of code is accompanied with "I just started learning Java 2 weeks ago", but they're not webapps. What gives? – Kayaman Sep 15 '16 at 19:27
  • ok i get the == operator vs the .equals oversight, anything else ? – Catresl Sep 15 '16 at 19:30
  • Well I'm hoping you meant `e.printStackTrace();` instead of `e.toString();`? – Kayaman Sep 15 '16 at 19:31
  • Also that's a hell of an oversight if you're building a webapp and don't remember how to compare Strings. – Kayaman Sep 15 '16 at 19:37
  • yes - been a while since using java.. bet your suggestion doesn't solve the logical issue im having with the infinite redirect. but thanks for the starting point.. ;-) – Catresl Sep 15 '16 at 19:45

0 Answers0