我的Web应用程序中的OAuth to Discord出现问题。我正在尝试两个请求:一个请求获取用户ID,另一个请求获取特定服务器内用户的角色。但是我遇到的问题是,在我的第二次api调用中,出现了未授权错误。我不太确定要使授权代码的持续时间长于第一次调用所需的时间。这是我的代码:
public IActionResult Admin(string code)
{
string client_id = configuration["Discord:AppId"];
string client_sceret = configuration["Discord:AppSecret"];
string redirect_url = "http://localhost:52476/Account/Admin";
/*Get Access Token */
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://discordapp.com/api/oauth2/token");
webRequest.Method = "POST";
string parameters = "client_id=" + client_id + "&client_secret=" + client_sceret + "&grant_type=authorization_code&code=" + code + "&redirect_uri=" + redirect_url + "";
byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
Stream postStream = webRequest.GetRequestStream();
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
WebResponse response = webRequest.GetResponse();
postStream = response.GetResponseStream();
StreamReader reader = new StreamReader(postStream);
string responseFromServer = reader.ReadToEnd();
JObject jResponse = JObject.Parse(responseFromServer);
JValue access_token = (JValue)jResponse["access_token"];
JValue expires = (JValue)jResponse["expires_in"];
/* Get User ID */
HttpWebRequest webRequest1 = (HttpWebRequest)WebRequest.Create("https://discordapp.com/api/users/@me");
webRequest1.Method = "Get";
webRequest1.ContentLength = 0;
webRequest1.Headers.Add("Authorization", "Bearer " + access_token);
webRequest1.ContentType = "application/x-www-form-urlencoded";
string apiResponse1 = "";
string discordID = string.Empty;
using (HttpWebResponse response1 = webRequest1.GetResponse() as HttpWebResponse)
{
using (StreamReader reader1 = new StreamReader(response1.GetResponseStream()))
{
apiResponse1 = reader1.ReadToEnd();
JObject joResponse = JObject.Parse(apiResponse1);
JValue result = (JValue)joResponse["id"];
discordID = result.ToString();
}
}
/*Get Info from Discord Server by ID*/
string guildId = configuration["Discord:GuildId"];;
string url = string.Format("https://discordapp.com/api/guilds/{0}/members/{1}", guildId, discordID);
HttpWebRequest webRequest2 = (HttpWebRequest)WebRequest.Create(url);
webRequest2.Method = "Get";
webRequest2.ContentLength = 0;
webRequest2.Headers.Add("Authorization", "Bearer " + refresh_token);
webRequest2.ContentType = "application/x-www-form-urlencoded";
string apiResponse2 = "";
using (HttpWebResponse response1 = webRequest2.GetResponse() as HttpWebResponse)
{
StreamReader reader1 = new StreamReader(response1.GetResponseStream());
apiResponse2 = reader1.ReadToEnd();
}
ViewBag.Test = apiResponse2;
return View();
}