Search code examples
kubernetesluaistioenvoyproxy

How to redirect to login page in EnvoyFilter using lua code?


I am new to Lua, below is my inline code for "EnvoyFilter". I have spent a couple of hours to search a few articles and posts. But, didn't find any suitable answer, hence posting this question.

The scenario is when I am getting a 503 error code I want to redirect to the login page.

             function envoy_on_response(response_handle)
                if response_handle:headers():get(":status") == "503" then
                  #TODO Redirect to http://login-page.com
                end
              end

Any help or suggestion would be helpful and appreciated.

[Working Answer]

function envoy_on_response(response_handle)
  if response_handle:headers():get(":status") == "503" then                
    response_handle:headers():replace("content-type", "text/html")                
    response_handle:headers():replace(":status", "307")                
    response_handle:headers():add("location", "https://login-page.com")
  end
end 

Solution

  • You could use a 302 Found response to instruct the users browser to make a new request to the login page.

    Something like this should work:

    First add some logging to validate, that it's working. Now replace the status field in the header and set it to 302. Last add a location field to the header, which contains the url you want to redirect to.

    function envoy_on_response(response_handle)
        if response_handle:headers():get(":status") == "503" then
            response_handle:logInfo("Got status 503, redirect to login...")
            response_handle:headers():replace(":status", "302")
            response_handle:headers():add("location", "http://login-page.com")
        end
    end
    

    See docs for further inspiration: https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/lua_filter

    Having said this I want to add that this might not be a good approach for failure handling. The user will not be informed about the error, but will just be redirected and land on the login page, without knowing why.

    What problem are you trying to solve? Maybe there is a better way.