我使用OAuth 2.0認證我的網站的銷售隊伍銷售人員認證。我下載並運行了Java示例代碼,它工作正常。現在我需要從ASP.Net網頁上做同樣的事情,但它似乎並不奏效。當我做了最後一篇文章,以獲得訪問令牌,它給了我一個錯誤System.Net.WebException:遠程服務器返回錯誤:(400)錯誤的請求。從ASP.Net Web頁C#
我使用的是在這個環節here提到的相同httppost方法。有關詳細信息,該帖子的代碼如下。
public partial class Authenticate2 : System.Web.UI.Page
{
private string tokenUrl;
protected void Page_Load(object sender, EventArgs e)
{
Logger.LogInfoMessage("I am Authenticate 2");
string code = Request["code"];
Logger.LogInfoMessage("Code is: " + code);
string parameters = "code=" + code
+ "&grant_type=authorization_code"
+ "&client_id=" + Authenticate.CONSUMER_KEY
+ "&client_secret=" + Authenticate.CONSUMER_SECRET
+ "&redirect_uri" + Authenticate.REDIRECT_URL;
string result = HttpPost(tokenUrl, parameters);
Logger.LogInfoMessage(result);
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
tokenUrl = Authenticate.ENVIRONMENT + "/services/oauth2/token";
}
public string HttpPost(string URI, string Parameters)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
// Add parameters to post
byte[] data = System.Text.Encoding.ASCII.GetBytes(Parameters);
req.ContentLength = data.Length;
System.IO.Stream os = req.GetRequestStream();
os.Write(data, 0, data.Length);
os.Close();
// Do the post and get the response.
System.Net.WebResponse resp = req.GetResponse();
if (resp == null) return null;
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}
}
身份驗證類來說確實重定向按本:
public partial class Authenticate : System.Web.UI.Page
{
public const string CONSUMER_KEY = "XXX";
public const string CONSUMER_SECRET = "XXX";
public const string REDIRECT_URL = "https://localhost/authenticate2.aspx";
public const string ENVIRONMENT = "https://test.salesforce.com";
public const string ACCESS_TOKEN = "ACCESS_TOKEN";
public const string INSTANCE_URL = "INSTANCE_URL";
public const string INVOICE_ID = "invoiceId";
private string authenticateUrl = null;
protected void Page_Load(object sender, EventArgs e)
{
Logger.LogInfoMessage("I am in Authenticate");
string accessToken = (string)Session[ACCESS_TOKEN];
Logger.LogInfoMessage("Access Token is:" + accessToken);
if (accessToken == null)
{
Logger.LogInfoMessage("Redirecting to:" + authenticateUrl);
Response.Redirect(authenticateUrl);
return;
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
authenticateUrl = ENVIRONMENT
+ "/services/oauth2/authorize?response_type=code&client_id="
+ CONSUMER_KEY + "&redirect_uri="
+ HttpUtility.UrlEncode(REDIRECT_URL, System.Text.Encoding.UTF8);
}
}
錯誤,我得到的屏幕截圖是按如下:
什麼是您的參數字符串包含的,什麼是響應主體當你得到400個狀態碼說(它應該有關於失敗原因的更多細節) – superfell