title: Login to site using CSRF token using Go/Python
body: <p>I want to backup automatically web content from a site which requires login. I try to login by simulating a POST request. But I get the error:</p>
  
  <pre><code>csrf token: CSRF attack detected
  </code></pre>
  
  <p>Here are some extracts from the code I use:</p>
  
  <pre><code>func postLoginForm(csrfToken string) {
      values := make(url.Values)
      values.Set("signin[username]", "myusername") 
      values.Set("signin[password]", "mypassword") 
  
      values.Set("signin[_csrf_token]", csrfToken)
      resp, err := http.PostForm("https://spwebservicebm.reaktor.no/admin/nb", values)
  
      dumpHTTPResponse(resp) // show response to STDOUT
  }
  </code></pre>
  
  <p>The csrf token I get by fetching the login page and scanning it for a hidden input field named <code>signin[_csrf_token]</code>. The important part of the code for doing that is the following:</p>
  
  <pre><code>// Finds input field named signin[_csrf_token] and returns value as csrfToken
  func handleNode(n *html.Node) (csrfToken string, found bool) {
      if n.Type == html.ElementNode &amp;&amp; n.Data == "input" {
          m := make(map[string]string)
          for _, attr := range n.Attr {
              m[attr.Key] = attr.Val
          }
          if m["name"] == "signin[_csrf_token]" {
              return  m["value"], true
          }
      }
  
      for c := n.FirstChild; c != nil; c = c.NextSibling {
           if csrfToken, found = handleNode(c); found {
               return 
           }       
      }
  
      return "", false
  }
  </code></pre>
  
  <p>I don't need to be using Go, that is just because I am most familiar with that. Using python could be a solution as well, but I did not have any more luck with that.</p>