ASP.NET中的MailChimp oauth2不断返回invalid_grant [英] MailChimp oauth2 in ASP.NET keeps returning invalid_grant
问题描述
我正在开发一个新应用程序,该程序可与MailChimp集成.基本上,它使用户可以轻松地将其客户联系信息直接导出到MailChimp帐户(即,导出到MailChimp中的特定邮件列表). 所有这些都有效,并且与我的问题无关.
I am developing a new app that offers integration with MailChimp. Basically, it enables users to easily export their customer contact info directly to a MailChimp account (that is, to a specific mailing-list inside MailChimp). All that works, and are somewhat irrelevant to my question.
为了不每次都要求用户输入MailChimp凭证,我将实现如下所述的oauth2授权工作流程: http://apidocs.mailchimp.com/oauth2/
For not asking the user to enter MailChimp-credentials every time, I'm about to implement the oauth2 authorization workflow as described here: http://apidocs.mailchimp.com/oauth2/
在步骤1-3中工作正常,但是步骤4杀死了我. 这是我第一次使用oauth,但我似乎了解一些基本知识.
It works just fine in step 1-3, but step 4 is killing me. It's my first time working with oauth, but I seem to understand the basics.
这是我的问题:
执行POST呼叫 https://login.mailchimp.com/oauth2/token -URI,要获取最终的访问令牌,我会不断在JSON结果中获取错误:"invalid_grant"
When I do the POST call to the https://login.mailchimp.com/oauth2/token -URI, to get the final access-token, I keep getting the error in JSON result: "invalid_grant"
我检查了请求和响应流,发现我的URL正确编译了.
I have checked the request and response streams, that my url is compiled correctly.
这是我在控制器中的代码:
Here is my code in the controller:
(GrantEcoAccess只是授予对另一个应用程序的访问权限-其余的应该是不言自明的)
(GrantEcoAccess is just to grant access to another app - the rest should be self-explaining)
public class HomeController : ApplicationController
{
private readonly string authorize_uri = "https://login.mailchimp.com/oauth2/authorize";
private readonly string access_token_uri = "https://login.mailchimp.com/oauth2/token";
private readonly string mailchimp_clientid2 = "xxx";
private readonly string mailchimp_secret2 = "yyy";
...
public ActionResult GrantEcoAccess()
{
//if exist: use saved token
var user = (Mailchimp_users)Session["user"];
if (!string.IsNullOrWhiteSpace(user.EcoToken))
return RedirectToAction("GrantMailChimpAccess");
// if !
var url = "https://secure.e-conomic.com/secure/api1/requestaccess.aspx?role=superuser&appId=MailChimp&redirectUrl=http://localhost:18017/Home/IncomingToken";
Redirect(url).ExecuteResult(ControllerContext);
return null;
}
public ActionResult IncomingToken(string token)
{
var user = (Mailchimp_users)Session["user"];
user.EcoToken = token;
EcoSession.DataSession.Refresh(System.Data.Objects.RefreshMode.ClientWins, user);
EcoSession.DataSession.SaveChanges();
return RedirectToAction("GrantMailChimpAccess");
}
public ActionResult GrantMailChimpAccess()
{
//if exist: use saved token
var user = (Mailchimp_users)Session["user"];
if (!string.IsNullOrWhiteSpace(user.MailChimpToken))
return RedirectToAction("Index", "Subscribe");
//if !
var url = string.Format("{0}?response_type=code&client_id={1}&redirect_uri=", authorize_uri, mailchimp_clientid2, "http://127.0.0.1:18017/Home/IncomingMailChimpToken");
Redirect(url).ExecuteResult(ControllerContext);
return null;
}
public ActionResult IncomingMailChimpToken(string code)
{
var url = "https://login.mailchimp.com/oauth2/token?grant_type=authorization_code&client_id=XX&client_secret=XX&code=" + code + "&redirect_uri=http://127.0.0.1:18017/Home/AuthComplete";
//var url = string.Format("?grant_type=authorization_code&client_id={0}&client_secret={1}&code={2}&redirect_uri={3}", mailchimp_clientid, mailchimp_secret, code, Url.Action("AuthComplete"));
Response.Clear();
StringBuilder sb = new StringBuilder();
sb.Append("<html>");
sb.AppendFormat(@"<body onload='document.forms[""form""].submit()'>");
sb.AppendFormat("<form name='form' action='{0}' method='post'>", access_token_uri);
sb.Append("<input type='hidden' name='grant_type' value='authorization_code'>");
sb.AppendFormat("<input type='hidden' name='client_id' value='{0}'>", mailchimp_clientid2);
sb.AppendFormat("<input type='hidden' name='client_secret' value='{0}'>", mailchimp_secret2);
sb.AppendFormat("<input type='hidden' name='code' value='{0}'>", code);
sb.AppendFormat("<input type='hidden' name='redirect_uri' value='{0}'>", "http://127.0.0.1:18017/Home/AuthComplete");
// Other params go here
sb.Append("</form>");
sb.Append("</body>");
sb.Append("</html>");
Response.Write(sb.ToString());
Response.End();
return null;
}
public ActionResult AuthComplete(string access_token, string expires_in, string scope)
{
if (string.IsNullOrWhiteSpace(access_token))
throw new Exception("Could not authorize user with MailChimp");
var user = (Mailchimp_users)Session["user"];
user.MailChimpToken = access_token;
EcoSession.DataSession.Refresh(System.Data.Objects.RefreshMode.ClientWins, user);
EcoSession.DataSession.SaveChanges();
return RedirectToAction("Index", "Subscribe");
}
}
第4步杀死了我,而不是第5步.
It is step 4 that is killing me, not step 5.
推荐答案
步骤4是您的应用程序必须使用代码向access_token_uri发出带外请求"
Step 4 is "Your application must make an out-of-band request to the access_token_uri using the code"
这里的重点是带外". 您必须构建并发送发帖请求服务器端. 客户端不应该有您的mailchimp_secret
The main point here is "out of band". You have to build and send a post request server-side. The client should not have your mailchimp_secret
您的IncomingMailChimpToken可能看起来像这样:
Your IncomingMailChimpToken could look like this :
public ActionResult IncomingMailChimpToken(string code)
{
string mcPostData = String.Format(
"grant_type={0}&client_id={1}&client_secret={2}&code={3}&redirect_url={4}",
System.Web.HttpUtility.UrlEncode("authorization_code"),
System.Web.HttpUtility.UrlEncode(mailchimp_clientid2),
System.Web.HttpUtility.UrlEncode(mailchimp_secret2),
System.Web.HttpUtility.UrlEncode(code),
System.Web.HttpUtility.UrlEncode("http://127.0.0.1:18017/Home/AuthComplete")
);
WebRequest request = WebRequest.Create(access_token_uri);
// Set the Method property of the request to POST.
request.Method = "POST";
request.ContentType = "application/json";
byte[] byteArray = Encoding.UTF8.GetBytes(mcPostData);
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Cleanup the streams and the response.
reader.Close ();
dataStream.Close ();
response.Close ();
// parse the json responseFromServer to extract token, expires_in and scope
// and call AuthComplete with these params
}
这篇关于ASP.NET中的MailChimp oauth2不断返回invalid_grant的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!