I\'m using play framework 2.4.2
with Java and I want to validate that a user is logged in by intercepting all requests and checking if a session value is set. So I
Even if I would re-consider using action composition, you can fix Option 1.
Create a custom annotation to mark the actions that don't need validation.
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface NoAuthRequired {}
Then change your HttpRequestHandler implementation.
public class RequestHandler extends DefaultHttpRequestHandler {
@Override
public Action createAction(Http.Request request, Method actionMethod) {
return new Action.Simple() {
@Override
public F.Promise<Result> call(Http.Context ctx) throws Throwable {
// if the action is annotated with @NoAuthRequired or user is logged in delegate to it
if (actionMethod.isAnnotationPresent(NoAuthRequired.class) || ctx.session().containsKey("loggedIn")) {
return delegate.call(ctx);
}
// otherwise, block access
else {
return F.Promise.pure(forbidden("You're not allowed"));
}
}
};
}
}
In this way, every route requires validation unless explicitly annotated.
As you can see from the code, the session is available through the Context.