Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OAuth2 Authorization code was already redeemed please retry with a new valid code or use an existing refresh token #664

Closed
3 of 17 tasks
kastroph opened this issue Jan 17, 2023 · 11 comments

Comments

@kastroph
Copy link

kastroph commented Jan 17, 2023

Please provide us with the following information:

This issue is for a: (mark with an x)

- [x] bug report -> please search issues before submitting
- [ ] feature request
- [ ] documentation issue or request
- [x] regression (a behavior that used to work and stopped in a new release)

The issue was found for the following scenario:

Please add an 'x' for the scenario(s) where you found an issue

  1. Web app that signs in users
    1. with a work and school account in your organization: 1-WebApp-OIDC/1-1-MyOrg
    2. with any work and school account: /1-WebApp-OIDC/1-2-AnyOrg
    3. with any work or school account or Microsoft personal account: 1-WebApp-OIDC/1-3-AnyOrgOrPersonal
    4. with users in National or sovereign clouds 1-WebApp-OIDC/1-4-Sovereign
    5. with B2C users 1-WebApp-OIDC/1-5-B2C
  2. Web app that calls Microsoft Graph
    1. Calling graph with the Microsoft Graph SDK: 2-WebApp-graph-user/2-1-Call-MSGraph
    2. With specific token caches: 2-WebApp-graph-user/2-2-TokenCache
    3. Calling Microsoft Graph in national clouds: 2-WebApp-graph-user/2-4-Sovereign-Call-MSGraph
  3. Web app calling several APIs 3-WebApp-multi-APIs
  4. Web app calling your own Web API
    1. with a work and school account in your organization: 4-WebApp-your-API/4-1-MyOrg
    2. with B2C users: 4-WebApp-your-API/4-2-B2C
    3. with any work and school account: 4-WebApp-your-API/4-3-AnyOrg
  5. Web app restricting users
    1. by Roles: 5-WebApp-AuthZ/5-1-Roles
    2. by Groups: 5-WebApp-AuthZ/5-2-Groups
  6. Deployment to Azure
  7. Other (please describe)

Repro-ing the issue

Repro steps

This only happens in production

Expected behavior
Provide a valid authentication response

Actual behavior
Microsoft retunes Since updating to dot net 7 we keep seeing this error in production. This was working fine in dot net 6.

"OAuth2 Authorization code was already redeemed please retry with a new valid code or use an existing refresh token"

Possible Solution

Additional context/ Error codes / Screenshots

Any log messages given by the failure

Add any other context about the problem here, such as logs.

OS and Version?

Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?)
Windows Server

Versions

dot net 7.0.2

Attempting to troubleshooting yourself:

Mention any other details that might be useful


Thanks! We'll be in touch soon.

@kastroph
Copy link
Author

More information, the issue happnes after 23 hours in prduction. Recycling the IIS pool does not resolve the issue. However, if I do a full depoyment resloves the issue. Futhermore, it affects all users at the same time that are using the orgnastaions AD authicatiuion for the app.

@jmprieur
Copy link
Contributor

@kastroph : I think this might be due to this issue:
AzureAD/microsoft-identity-web#1995

See AzureAD/microsoft-identity-web#1995 (comment) and the following conversations, for the description of the problem and the workaround, until .NET 7 releases a patch.

@kastroph
Copy link
Author

@jmprieur Thank you for your reply.

I was actually following AzureAD/microsoft-identity-web#1995 (comment). I tried the workaround but it has no effect on the issue, this is why I have raised a new issue as it might be something different and we are getting close to the next patch release date.

This has been driving me nuts for the last two weeks trying to force Web Identity to work in production or fail in development so I can inspect the mode of failure

@jmprieur
Copy link
Contributor

jmprieur commented Jan 17, 2023

You mentioned that this is with .NET 7.1. Where did you get it? I'm only aware of .NET 7.0.2.
cc: @Tratcher
That's the first time I hear of this issue.

Also which version of Microsoft.Identity.Web are you using?

@kastroph
Copy link
Author

Sorry @jmprieur I meant 7.0.2 (typo)
This is the Idenity packages we are uing
image

@jmprieur
Copy link
Contributor

@kastroph: Do you mind trying with 2.0.8-preview? We've changed the way we were handling options. This might work better?

@kastroph
Copy link
Author

@jmprieur Not at all, I have tested in devlopment and pushed it to production. I will moniter metrics for the next 72 hours and see if this resoves the issue.

@jmprieur
Copy link
Contributor

Thanks @kastroph

@kastroph
Copy link
Author

kastroph commented Jan 19, 2023

@jmprieur After, about 36 hours in production. I'm starting to see OAuth2 Authorization code+ was+ already redeemed
please retry with a new valid code or use an existing refresh token.

The push to production for 2.0.8-preview happened on 01/18/2023, 00:24
the last successful sign-in using Web Identity was on 01/19/2023, 11:47,
errors were produced on 01/19/2023, 12:08.

I found this in our logs

01/19/2023 12:29:44 False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.0 Microsoft Windows 6.3.9600 [2023-01-19 12:29:44Z - 540e8137-dc80-4067-acb6-89ae48515e7b] Only in-memory caching is used. The cache is not persisted and will be lost if the machine is restarted. It also does not scale for a web app or web API, where the number of users can grow large. In production, web apps and web APIs should use distributed caching like Redis. See https://aka.ms/msal-net-cca-token-cache-serialization
01/19/2023 12:29:44 False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.0 Microsoft Windows 6.3.9600 [2023-01-19 12:29:44Z - 540e8137-dc80-4067-acb6-89ae48515e7b] Request retry failed.
01/19/2023 12:29:44 False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.0 Microsoft Windows 6.3.9600 [2023-01-19 12:29:44Z - 540e8137-dc80-4067-acb6-89ae48515e7b] === Token Acquisition (1000) failed.
Host: login.microsoftonline.com.
01/19/2023 12:29:44 False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.0 Microsoft Windows 6.3.9600 [2023-01-19 12:29:44Z - 540e8137-dc80-4067-acb6-89ae48515e7b] Exception type: Microsoft.Identity.Client.MsalUiRequiredException
, ErrorCode: invalid_grant
HTTP StatusCode 400
CorrelationId 540e8137-dc80-4067-acb6-89ae48515e7b

01/19/2023 12:29:44 False MSAL 4.49.1.0 MSAL.NetCore .NET 7.0.0 Microsoft Windows 6.3.9600 [2023-01-19 12:29:44Z - 540e8137-dc80-4067-acb6-89ae48515e7b] Exception type: Microsoft.Identity.Client.MsalUiRequiredException
, ErrorCode: invalid_grant
HTTP StatusCode 400
CorrelationId xxxxxxxxxxxxxxxxx

at Microsoft.Identity.Client.OAuth2.OAuth2Client.ThrowServerException(HttpResponse response, RequestContext requestContext)
at Microsoft.Identity.Client.OAuth2.OAuth2Client.CreateResponse[T](HttpResponse response, RequestContext requestContext)
at Microsoft.Identity.Client.OAuth2.OAuth2Client.ExecuteRequestAsync[T](Uri endPoint, HttpMethod method, RequestContext requestContext, Boolean expectErrorsOn200OK, Boolean addCommonHeaders, Func2 onBeforePostRequestData) at Microsoft.Identity.Client.OAuth2.OAuth2Client.GetTokenAsync(Uri endPoint, RequestContext requestContext, Boolean addCommonHeaders, Func2 onBeforePostRequestHandler)
at Microsoft.Identity.Client.OAuth2.TokenClient.SendHttpAndClearTelemetryAsync(String tokenEndpoint, ILoggerAdapter logger)
at Microsoft.Identity.Client.OAuth2.TokenClient.SendHttpAndClearTelemetryAsync(String tokenEndpoint, ILoggerAdapter logger)
at Microsoft.Identity.Client.OAuth2.TokenClient.SendTokenRequestAsync(IDictionary2 additionalBodyParameters, String scopeOverride, String tokenEndpointOverride, CancellationToken cancellationToken) at Microsoft.Identity.Client.Internal.Requests.ConfidentialAuthCodeRequest.ExecuteAsync(CancellationToken cancellationToken) at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken) 01/19/2023 12:29:44 Exception occurred while processing message. MSAL.NetCore.4.49.1.0.MsalUiRequiredException: ErrorCode: invalid_grant Microsoft.Identity.Client.MsalUiRequiredException: AADSTS54005: OAuth2 Authorization code was already redeemed, please retry with a new valid code or use an existing refresh token. Trace ID: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Correlation ID: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Timestamp: 2023-01-19 12:29:44Z at Microsoft.Identity.Client.OAuth2.OAuth2Client.ThrowServerException(HttpResponse response, RequestContext requestContext) at Microsoft.Identity.Client.OAuth2.OAuth2Client.CreateResponse[T](HttpResponse response, RequestContext requestContext) at Microsoft.Identity.Client.OAuth2.OAuth2Client.ExecuteRequestAsync[T](Uri endPoint, HttpMethod method, RequestContext requestContext, Boolean expectErrorsOn200OK, Boolean addCommonHeaders, Func2 onBeforePostRequestData)
at Microsoft.Identity.Client.OAuth2.OAuth2Client.GetTokenAsync(Uri endPoint, RequestContext requestContext, Boolean addCommonHeaders, Func2 onBeforePostRequestHandler) at Microsoft.Identity.Client.OAuth2.TokenClient.SendHttpAndClearTelemetryAsync(String tokenEndpoint, ILoggerAdapter logger) at Microsoft.Identity.Client.OAuth2.TokenClient.SendHttpAndClearTelemetryAsync(String tokenEndpoint, ILoggerAdapter logger) at Microsoft.Identity.Client.OAuth2.TokenClient.SendTokenRequestAsync(IDictionary2 additionalBodyParameters, String scopeOverride, String tokenEndpointOverride, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.ConfidentialAuthCodeRequest.ExecuteAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.ApiConfig.Executors.ConfidentialClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenByAuthorizationCodeParameters authorizationCodeParameters, CancellationToken cancellationToken)
at Microsoft.Identity.Web.TokenAcquisition.AddAccountToCacheFromAuthorizationCodeAsync(IEnumerable1 scopes, String authCode, String authenticationScheme, String clientInfo, String codeVerifier, String userFlow) at Microsoft.Identity.Web.TokenAcquisitionAspNetCore.AddAccountToCacheFromAuthorizationCodeAsync(AuthorizationCodeReceivedContext context, IEnumerable1 scopes, String authenticationScheme)
at Microsoft.Identity.Web.MicrosoftIdentityWebAppAuthenticationBuilder.<>c__DisplayClass11_1.<b__1>d.MoveNext()
--- End of stack trace from previous location ---
at Microsoft.Identity.Web.MicrosoftIdentityWebAppAuthenticationBuilder.<>c__DisplayClass11_1.<b__1>d.MoveNext()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.RunAuthorizationCodeReceivedEventAsync(OpenIdConnectMessage authorizationResponse, ClaimsPrincipal user, AuthenticationProperties properties, JwtSecurityToken jwt)
at Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler.Han

@jmprieur
Copy link
Contributor

jmprieur commented Apr 14, 2023

@kastroph
Closing as this is fixed with the .NET 7.0 SDK update of mid-February.
feel free to reopen if you disagree

@TejendraPrasad
Copy link

@jmprieur, Just wanted to check is there fix available in .NET 6.0 SDK? as still .NET 6.0 is LTS until application gets migrated to .NET 7.0 OR direct .NET 8.0...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants