We have a web app connected with CRM Dynamics 365 that retrieve Accounts from crm through API. I can login successfully but when i try to retrieve accounts from crm i was not able to send the token and this error appears ( Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException: 'AADSTS54005: OAuth2 Authorization code was already redeemed, please retry with a new valid code or use an existing refresh token.)
Code:
protected void Page_Load(object sender, EventArgs e)
{
var queryString = Request.QueryString;
if (queryString != null && queryString["code"] != null)
{
var authCode = queryString["code"];
// get the access token using the authorization code
TokenCache tokenCache = new TokenCache();
AuthenticationContext authContext = new AuthenticationContext(string.Format(AuthorityUri, _configuration.ADTenant), tokenCache);
ClientCredential clientCredentials = new ClientCredential(_configuration.ClientId, _configuration.ClientSecret);
AuthenticationResult authResult = authContext.AcquireTokenByAuthorizationCode(authCode, new Uri(_configuration.RedirectUri), clientCredentials);
if (authResult.UserInfo != null)
{
Session["AuthResult"] = authResult;
}}}
protected void Login_Click(object sender, EventArgs e)
{
var authorityUri = string.Format(CompleteAuthUri, _configuration.ADTenant, _configuration.ClientId, _configuration.Resource, Server.UrlEncode(_configuration.RedirectUri));
Response.Redirect(authorityUri);}
protected void GetAccounts_Click(object sender, EventArgs e)
{
if (Session["AuthResult"] != null)
{
var authResult = (AuthenticationResult)Session["AuthResult"];
var webRequest = (HttpWebRequest)WebRequest.Create(new Uri("OrganizationURL/api/data/v9.1/accounts?$select=accountid,name&$top=10"));
webRequest.Method = "GET";
webRequest.ContentLength = 0;
webRequest.Headers.Add("Authorization", String.Format("Bearer {0}", authResult.AccessToken));
webRequest.Headers.Add("OData - MaxVersion", "4.0");
webRequest.Headers.Add("OData - Version", "4.0");
webRequest.ContentType = "application / json; charset = utf - 8"; }