[Play 2.6 Java] Browser back button Issue after logout

When user logout from application he is redirect to the login page, but if user clicks the back button of browser, it again goes to the previous visited page although the page is already logged out.

I tried two methods. The first is to set some HTTP headers like that:

return ok(page.render()).withHeader("Cache-Control", "no-cache,no-store,must-revalidate").
                withHeader("Pragma","no-cache").withHeader("Expires", "0");

It’s works fine, but only for this page. Is there a way to set these headers globally?

The other way is to use an ajax call in the main page to check session:

 $(document).ready(function () {
            CheckingSeassion();
        });
        function CheckingSeassion() {
            $.post("checkSession", {}, function (data) {
                if(data=="0") {
                     window.location = "login";
                }
            });
        }

public Result checkSession() {
        String result = "0";
        if(session().containsKey("id")) {
            result = "1";
        }
        return ok(result);
    }

This method works fine but has a limitation that when user clicks the back button of the browser, the back page shows for 1 or half second because of executing the checkSession.

Is there a better method?

Setting the response headers is the best solution. To apply this across all of your responses, you could use a filter:

https://www.playframework.com/documentation/2.6.x/JavaHttpFilters#Filters

1 Like

Can you give me a real example? I’m trying to understand how to do that following the documentation but really I don’t understand where I’ve to start.

I’ve already a Filter.java for security filters.

@Singleton
public class Filters extends DefaultHttpFilters {

    @Inject
    public Filters(CSRFFilter csrfFilter,
                   AllowedHostsFilter allowedHostsFilter,
                   SecurityHeadersFilter securityHeadersFilter) {
        super(csrfFilter, allowedHostsFilter, securityHeadersFilter);
    }
}

Can I add code to this file?

Your class Filters is used to list and order the Filter instances that are required by your application. To make it clear, that are two concepts here:

  1. play.mvc.Filter: Defines an operation to be applied to requests/results.
  2. play.http.HttpFilters: lists the filters used by your application (in the example you posted they are CSRFFilter, AllowedHostsFilter and SecurityHeadersFilter) and in which order they are applied.

So, in your case, you need to:

  1. Create a new filter to add the headers will want (see an example here).
  2. Inject this new filter into your Filters class and add it to the call to the super constructor.

Best.

Thanks, it’s works perfect.