1
votes

I have a web app with C# backend trying to get the Access Token from Azure AD. Using https://login.microsoftonline.com/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/oauth2/token. I have got the authorization code, but when requesting the Access Token I get this respons:

error: invalid_grant

error_description: AADSTS70000: Transmission data parser failure: Authorization Code is malformed or invalid.

I have checked that the redirect url is the exact same as the one I use in the request for the authorization code. And both redirect_uri, app_id_uri and client secret is url encoded.

        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;
            }
        }

UPDATE:

This is the request to get the authorization code:

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
1
Try a new request to the /authorize endpoint.SunnySun
@SunnySun-MSFT I do a new one for each request, not reusing the code.Nick3
After requesting a new authorization code and using the new code to request token, it still prompts the same error?SunnySun
@SunnySun-MSFT Yeah, same thing.Nick3
could you share your request for authorization code here?SunnySun

1 Answers

1
votes

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

From your request, I find your request is just for id_token, not include the authorization code, that's why prompts the code invalid, so you need to add code into the code request response_type=id_token+code.