Magento-RestApi
Magento-RestApi copied to clipboard
Oauth fails with "invalid form key" after some patches - fix
After some patches (including SUPEE-6788, SUPEE-7405, SUPEE-7405v1.1, SUPEE-8788, SUPEE-9652 and SUPEE-9767v2), MagentoApi.cs wasn't getting back a Location from the API at the end of method private string Login.
Used fidder to see the traffic - and found using (var response = postRequest.GetResponse()) returned the html form again with the error "invalid form key", rather than the expected "click here to grant approval" form.
After some digging / comparing to a Magento test page, found a difference - if (!string.IsNullOrEmpty(webClient.AdminHtml)) cookieContainer.Add(new Uri(postRequest.RequestUri.GetLeftPart(UriPartial.Authority)), new Cookie("adminhtml", webClient.AdminHtml)); ..... mine wasn't getting webClient.AdminHTML set - so this cookie wasn't being set, but it's absense is what was causing the login POST to fail..
Fix was therefore to move this: var cookieContainer = new CookieContainer(); to the top of the method, and use a HttpWebRequest for the GET on the login page, and assign the cookie container to it which populates the cookies; then use same cookie container for the POST, so the cookie is passed across.
Not sure if this needs to be included in the main project or if there is any possible adverse impact, but hope this helps someone somewhere sometime :)