title: HttpServletRequest, csrf check for referrer header
body: <p>I need to add a check to see if the domain matches the referrer and completely new to csrf concepts and servlets. I would like to know if there is a way for me to validate if the referrer exists </p>
  
  <p>If the referrer header is not <a href="https://[samedomain]/abc/sso?module=console" rel="nofollow noreferrer">https://[samedomain]/abc/sso?module=console</a>, then fail. Note that the check should be very strict here. Cannot just compare using endswith “/abc/sso?module=console” since it could be bypass with <a href="https://attacker.com/abc/sso?module=console" rel="nofollow noreferrer">https://attacker.com/abc/sso?module=console</a> or <a href="https://[samedomain].attacker.com/abc/sso?module=console" rel="nofollow noreferrer">https://[samedomain].attacker.com/abc/sso?module=console</a>
  If not fail, proceed</p>
  
  <p>I am looking for the right validation with regards to code like may be need to compare the port and the server name too.  I am not looking for something overly complicated 
   i have come this far , </p>
  
  <pre><code>    String refererHeader = request.getHeader("referer");
      final String PATH = '/abc/sso?module=console',
      String host = request.getServerName();
      int port = request.getServerPort();
  
      String portstr="";
      if(port!=80 || port!= 443){
        portstr=":"+port;
      }
  
      if (refererHeader == null) {
          response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
          return;
      }
  
      if (refererHeader != null &amp;&amp;  host!== null) {
       //check if port is not the default ports, in that case construct the url 
  
       //append with PATH and compare if the referrer header and this matches 
  
      }
  </code></pre>
  
  <p>Any help would be appreciated </p>