IdentityServer4: Failed to retrieve access token, An error was encountered while handling the remote login

1

I'm trying to build a basic project using IdentityServer authentication. The past days I've been picking up bits and pieces from everywhere, but mostly from FullStackMarc.

At the moment I'm able to get to the point where the Client-application requests a token from the IdentityServer. Then IdentityServer redirects to the RedirectUrl, which is allowed by the OAuth-client. That's where I'm getting the following error:

Failed to retrieve access token, An error was encountered while handling the remote login

Reproduction:

  1. git clone https://github.com/PieterjanDeClippel/AngularASPNETCoreOAuth
  2. cd AngularASPNETCoreOAuth\src\AuthServer\AuthServer.Infrastructure
  3. dotnet ef database update --context AppIdentityDbContext
  4. Now you should have a new database in LocalDB
  5. Open and launch both solutions
  6. You need to create a user for now (with PostMan)
POST https://localhost:44348/api/Account HTTP/1.1
Content-Type: application/json

{
    "name": "Bob",
    "email": "bob@example.com",
    "password": "Aze123°}"
}
  1. Put a breakpoint at AuthServer → AccountController:238
  2. The debug session of the ResourceAPI initially launches https://localhost:44344/api/Profile/login
  3. This action returns the challenge to login with my IdentityServer instance at https://localhost:44348/Account/Login
  4. Here you can login with:
    • Username: bob@example.com
    • Password: Aze123°}
  5. The application executes the Login-HttpPost action, which redirects successfully to the RedirectUrl with the state and code appended to the querystring
  6. Now IdentityServer requests a token by POSTing to Account/Token
  7. This calls the RequestClientCredentialsTokenAsync method, sending a request to https://localhost:44348/connect/token
  8. This request completes successfully, with a bearer token in the result. So tokenResponse.AccessToken = ey...

The tokenResponse.AccessToken is defined

  1. The Token-request completes with 200 response containing an IdentityModel.Client.TokenResponse
  2. Next, you're redirected to https://localhost:44344/signin-my-auth-server with the code and state queryparams
  3. Next, instead of handling the signin-request, the following exception is thrown (as shown in the image):

Failed to retrieve access token

An error was encountered while handling the remote login

Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler.HandleRequestAsync()

I would post my source code, but it's really a lot. It's available at https://github.com/PieterjanDeClippel/AngularASPNETCoreOAuth. I've put breakpoints at the following positions:

  • AccountController:228
  • AccountController:238
  • AccountController:245

Why isn't Identity able to read the access token from the response returned from the https://localhost:44348/Account/Token response?

EDIT:

I'm getting the following error in the console, but these errors appear before the last breakpoint is hit and the workflow is still successful up until then. So I don't think this is a breaking issue in this case.

System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'PersistedGrants'.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at System.Data.SqlClient.SqlDataReader.get_MetaData()
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite, String method)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader()
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider._TrackEntities[TOut,TIn](IEnumerable`1 results, QueryContext queryContext, IList`1 entityTrackingInfos, IList`1 entityAccessors)+MoveNext()
   at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
ClientConnectionId:42c02e4f-a9a8-4a0e-929b-eed3008cd38b
Error Number:208,State:1,Class:16
Exception thrown: 'System.Data.SqlClient.SqlException' in Microsoft.EntityFrameworkCore.dll
IdentityServer4.EntityFramework.TokenCleanup: Error: Exception removing expired grants: Invalid object name 'PersistedGrants'.

And off course the table PersistedGrants doesn't exist, and creating another migration does not modify the database structure.

EDIT 2:

This is the output of the logfile I'm getting after I added Serilog:

2021-01-03 16:34:52.005 +01:00 [INF] Starting IdentityServer4 version 3.0.1.0
2021-01-03 16:34:52.184 +01:00 [INF] Using the default authentication scheme Identity.Application for IdentityServer
2021-01-03 16:34:52.184 +01:00 [DBG] Using Identity.Application as default ASP.NET Core scheme for authentication
2021-01-03 16:34:52.184 +01:00 [DBG] Using Identity.External as default ASP.NET Core scheme for sign-in
2021-01-03 16:34:52.184 +01:00 [DBG] Using Identity.External as default ASP.NET Core scheme for sign-out
2021-01-03 16:34:52.184 +01:00 [DBG] Using Identity.Application as default ASP.NET Core scheme for challenge
2021-01-03 16:34:52.186 +01:00 [DBG] Using Identity.Application as default ASP.NET Core scheme for forbid
2021-01-03 16:34:52.375 +01:00 [DBG] Starting grant removal
2021-01-03 16:34:52.460 +01:00 [DBG] Login Url: /Account/Login
2021-01-03 16:34:52.462 +01:00 [DBG] Login Return Url Parameter: ReturnUrl
2021-01-03 16:34:52.462 +01:00 [DBG] Logout Url: /Account/Logout
2021-01-03 16:34:52.462 +01:00 [DBG] ConsentUrl Url: /consent
2021-01-03 16:34:52.462 +01:00 [DBG] Consent Return Url Parameter: returnUrl
2021-01-03 16:34:52.462 +01:00 [DBG] Error Url: /home/error
2021-01-03 16:34:52.462 +01:00 [DBG] Error Id Parameter: errorId
2021-01-03 16:34:58.811 +01:00 [DBG] Augmenting SignInContext
2021-01-03 16:34:58.812 +01:00 [DBG] Adding idp claim with value: local
2021-01-03 16:34:58.812 +01:00 [DBG] Adding amr claim with value: pwd
2021-01-03 16:34:58.821 +01:00 [INF] AuthenticationScheme: Identity.Application signed in.
2021-01-03 16:35:03.096 +01:00 [DBG] Request path /.well-known/openid-configuration matched to endpoint type Discovery
2021-01-03 16:35:03.100 +01:00 [DBG] Endpoint enabled: Discovery, successfully created handler: IdentityServer4.Endpoints.DiscoveryEndpoint
2021-01-03 16:35:03.100 +01:00 [INF] Invoking IdentityServer endpoint: IdentityServer4.Endpoints.DiscoveryEndpoint for /.well-known/openid-configuration
2021-01-03 16:35:03.101 +01:00 [DBG] Start discovery request
2021-01-03 16:35:03.189 +01:00 [DBG] Request path /.well-known/openid-configuration/jwks matched to endpoint type Discovery
2021-01-03 16:35:03.189 +01:00 [DBG] Endpoint enabled: Discovery, successfully created handler: IdentityServer4.Endpoints.DiscoveryKeyEndpoint
2021-01-03 16:35:03.190 +01:00 [INF] Invoking IdentityServer endpoint: IdentityServer4.Endpoints.DiscoveryKeyEndpoint for /.well-known/openid-configuration/jwks
2021-01-03 16:35:03.191 +01:00 [DBG] Start key discovery request
2021-01-03 16:35:03.228 +01:00 [DBG] Request path /connect/token matched to endpoint type Token
2021-01-03 16:35:03.232 +01:00 [DBG] Endpoint enabled: Token, successfully created handler: IdentityServer4.Endpoints.TokenEndpoint
2021-01-03 16:35:03.232 +01:00 [INF] Invoking IdentityServer endpoint: IdentityServer4.Endpoints.TokenEndpoint for /connect/token
2021-01-03 16:35:03.234 +01:00 [DBG] Start token request.
2021-01-03 16:35:03.236 +01:00 [DBG] Start client validation
2021-01-03 16:35:03.238 +01:00 [DBG] Start parsing Basic Authentication secret
2021-01-03 16:35:03.239 +01:00 [DBG] Start parsing for secret in post body
2021-01-03 16:35:03.240 +01:00 [DBG] Parser found secret: PostBodySecretParser
2021-01-03 16:35:03.240 +01:00 [DBG] Secret id found: CarfacPlusClient
2021-01-03 16:35:03.247 +01:00 [DBG] client configuration validation for client CarfacPlusClient succeeded.
2021-01-03 16:35:03.252 +01:00 [DBG] Secret validator success: HashedSharedSecretValidator
2021-01-03 16:35:03.252 +01:00 [DBG] Client validation success
2021-01-03 16:35:03.255 +01:00 [DBG] Start token request validation
2021-01-03 16:35:03.258 +01:00 [DBG] Start client credentials token request validation
2021-01-03 16:35:03.272 +01:00 [DBG] CarfacPlusClient credentials token request validation success
2021-01-03 16:35:03.280 +01:00 [INF] Token request validation success, {"ClientId":"CarfacPlusClient","ClientName":"Angular SPA","GrantType":"client_credentials","Scopes":"email","AuthorizationCode":null,"RefreshToken":null,"UserName":null,"AuthenticationContextReferenceClasses":null,"Tenant":null,"IdP":null,"Raw":{"grant_type":"client_credentials","scope":"email","client_id":"CarfacPlusClient","client_secret":"***REDACTED***"},"$type":"TokenRequestValidationLog"}
2021-01-03 16:35:03.297 +01:00 [DBG] Getting claims for access token for client: CarfacPlusClient
2021-01-03 16:35:03.360 +01:00 [DBG] Token request success.

All seems fine to me...

oauth
identityserver4
asp.net-core-3.1
asked on Stack Overflow Jan 3, 2021 by Pieterjan • edited Jan 3, 2021 by Pieterjan

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0