How do redirect in a before filter?

1,044 views
Skip to first unread message

jac...@gmail.com

unread,
Oct 12, 2014, 5:01:23 PM10/12/14
to spar...@googlegroups.com
I am trying to write a before filter that will automatically redirect to the logic page
if the user is not authenticated:

        before("/protected/*", (request, response) -> {
           
if (request.session().attribute(AppConstants.USER) == null) {
                response
.redirect("/login",401);
           
}
       
});

but it does not work.

If I access a protected URL, it just throws a raw ugly Jetty error page with a 401 code...but does not redirect to the /login page.

I tried different codes (200) just in case it was important, but makes no difference.

All the examples for before() filter only show halt(), but I want to just cleanly redirect the user to the login page.

Is there anything wrong with my code here?

thanks
Jacek

P.S. Spark rocks. Shows how good Java can be if you remove all the EE cruft.


Brian Nesbitt

unread,
Oct 12, 2014, 11:35:31 PM10/12/14
to spar...@googlegroups.com
The HTTP 302 response code is the redirect code that you want. Its the default so just remove your 2nd param on the redirect() call and you should get the redirect. 
Also you might want to call halt() after your response.redirect().  It will immediately throw a HaltException that will prevent the rest of the before handler (no other code in your case but in case you add more) from running and (more importantly) any of the actual matching routes from running.  They will still run otherwise.

Also just a note, your current before() path of "/protected/*" won't protect a request with a path of the index protected section, "/protected".

Jacek Furmankiewicz

unread,
Oct 13, 2014, 11:07:05 AM10/13/14
to Brian Nesbitt, spar...@googlegroups.com
Works perfectly. Thanks so much!

--
You received this message because you are subscribed to a topic in the Google Groups "sparkjava" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/sparkjava/Q-BtB4T-myQ/unsubscribe.
To unsubscribe from this group and all its topics, send an email to sparkjava+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Salai Sivamal

unread,
May 22, 2015, 11:28:13 AM5/22/15
to spar...@googlegroups.com, br...@nesbot.com
Jacek,
How you are Authenticating the requests, what framework you use?
Please share Github if possible.
Thanks,
-Salai

Jacek Furmankiewicz

unread,
May 22, 2015, 11:35:22 AM5/22/15
to Salai Sivamal, spar...@googlegroups.com, Brian Nesbitt
This was for a test project. I think we used Apache Shiro,if I remember.
Reply all
Reply to author
Forward
0 new messages