I'm new to the spark-java framework and I was wondering if anyone has a good solution for checking if a user is authenticated. If the user isn't authenticated, I want to redirect to "/login". The best solution for this is in a before filter in my opinion. But then we have a redirect loop.
public static void main(String[] args) {
before((req, res) -> {
User usr = new User("DUMMY");
if (!Authentication.isUserAuthenticated(usr)) {
res.redirect("/login");
}
});
get("/login", (req, res) -> {
return "Sir, your credentials please!";
});
get("/", (req, res) -> {
return "Welcome!";
});
}
Is there any way to exclude a specific path? Or do you have any adivice for a better solution?
best regards, Philipp
I think a better approach wold be halting with the http not authorized status instead of redirecting. You cold do so by replacing the redirection in your before filter with halt(401)
. Then you should handle this status code in your client code. Are you using any framework for your client code, like AngularJs ?