我有一个带有C#后端的Web应用程序,试图从Azure AD获取访问令牌。使用https://login.microsoftonline.com/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/oauth2/token。我已经获得了授权码,但是当请求访问令牌时,我得到了以下响应:
error: invalid_grant
error_description: AADSTS70000: Transmission data parser failure: Authorization Code is malformed or invalid.
我检查了重定向URL是否与我在授权码请求中使用的URL完全相同。而且redirect_uri,app_id_uri和客户端密钥都经过url编码。
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
string parameter = "code=" + code;
parameter += "&client_id=" + client_id;
parameter += "&client_secret=" + client_secret;
parameter += "&redirect_uri=" + redirect_uri;
parameter += "&grant_type=authorization_code";
parameter += "&resource=" + app_id_uri;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byteArray = encoding.GetBytes(parameter);
request.ContentLength = byteArray.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream datastream = request.GetRequestStream();
datastream.Write(byteArray, 0, byteArray.Length);
datastream.Close();
WebResponse response = request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
return line;
}
}
更新:
这是获取授权码的请求:
https://login.microsoftonline.com/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/oauth2/authorize?client_id={CLIENT_ID}&response_type=id_token&redirect_uri={REDIRECT_URI}&response_mode=fragment&scope=openid&state=microsoftoauth&nonce=7362CAEA-9CA5-4B43-9BA3-34D7C303EBA7
答案 0 :(得分:1)
https://login.microsoftonline.com/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/oauth2/authorize?client_id= {CLIENT_ID}&response_type = id_token&redirect_uri = {REDIRECT_URI}&response_mode = fragment&scope = openid&state = microsoftoauth&nonce = 7362CAEA-9CA5-4B43-9BA3-34D7C303EBA7
从您的请求中,我发现您的请求仅用于id_token,不包括授权代码,这就是为什么提示代码无效的原因,因此您需要将code
添加到代码请求response_type=id_token+code
中。 / p>