0

This method RequestClientCredentialsTokenAsync to generate token (oauth2) works fine for me when I call it from unit test, but from the API MVC .Net Framework 4.6.1 I have this exception : ( I am sorry, the exception is in french language)

<Error> <Message> Une erreur s'est produite lors de l'envoi de la demande. </Message> <ExceptionMessage> Une erreur s'est produite lors de l'envoi de la demande. </ExceptionMessage> <ExceptionType>System.InvalidOperationException</ExceptionType> <StackTrace> à JwtBearerAuthentication.JwtAssertionTokenManager.AcquireAccessToken() dans C:\Users\S851029\source\repos\Sources\AF.EFormSignature.JwtBearerAuthentication\JwtAssertionTokenManager.cs:ligne 55 à JwtBearerAuthentication.JwtAssertionTokenManager.GetAccessToken(Boolean forceRefresh) dans C:\Users\S851029\source\repos\Sources\AF.EFormSignature.JwtBearerAuthentication\JwtAssertionTokenManager.cs:ligne 28 à AF.EFormSignature.Web.Controllers.IdentiteNumeriqueController.RecuperationStatutIdentite() dans C:\Users\S851029\source\repos\Sources\AF.EFormSignature.Web\Controllers\IdentiteNumeriqueController.cs:ligne 72 à lambda_method(Closure , Object , Object[] ) à System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters) à System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) à System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary2 arguments, CancellationToken cancellationToken) --- Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée --- à System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) à System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) à System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext() --- Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée --- à System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) à System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) à System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext() --- Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée --- à System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) à System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) à System.Web.Http.Filters.AuthorizationFilterAttribute.d__2.MoveNext() --- Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée --- à System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) à System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) à System.Web.Http.Controllers.ExceptionFilterResult.d__0.MoveNext() An error has occurred. Une erreur s'est produite lors de l'envoi de la demande. System.Net.Http.HttpRequestException à System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) à System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) à IdentityModel.Client.HttpClientTokenRequestExtensions.d__7.MoveNext() An error has occurred. Impossible de se connecter au serveur distant System.Net.WebException à System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context) à System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar) An error has occurred. Une tentative de connexion a échoué car le parti connecté n’a pas répondu convenablement au-delà d’une certaine durée ou une connexion établie a échoué car l’hôte de connexion n’a pas répondu 171.18.28.75:443 System.Net.Sockets.SocketException à System.Net.Sockets.Socket.InternalEndConnect(IAsyncResult asyncResult) à System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult) à System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)

        private string AcquireAccessToken()
        {
            // Build assertion
            var authenticationToken = GetAuthenticationToken();
            HttpClientHandler handler = new HttpClientHandler();
            handler.DefaultProxyCredentials = CredentialCache.DefaultCredentials;
            HttpMessageInvoker msg = new HttpMessageInvoker(handler);
            TokenClientOptions tokenClientOptions = new TokenClientOptions();
            tokenClientOptions.Address = TokenEndpointUrl;
            tokenClientOptions.ClientId = ClientId;
            tokenClientOptions.ClientSecret = ClientSecret;

            TokenClient tokenClient = new TokenClient(msg, tokenClientOptions);
            var payload = new Dictionary<string, string> {
                { "client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" },
                { "client_assertion", authenticationToken }
            };
            // Send authorization parameters using HTTP POST method and the Form Serialization
            // See http://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication
            var tokenResponse = tokenClient.RequestClientCredentialsTokenAsync(Scope, payload);
            if (tokenResponse.Result.IsError)
            {
                throw new InvalidOperationException(tokenResponse.Result.Exception.Message, tokenResponse.Result.Exception);
            }
            var accessToken = tokenResponse.Result.AccessToken;
            // Get token expiration date to configure cache expiration
            var accessTokenExpiration = GetTokenExpirationDate(accessToken);
            // Cache access token to prevent calling MAAM server for each request
            WriteTokenToCache(GenerateTokenCacheKey(), accessToken, new DateTimeOffset(accessTokenExpiration));
            return accessToken;
        }
Meet Sinojia
  • 121
  • 1
  • 1
  • 8
  • 1
    No problem, please translate error to English. – zsolt Mar 06 '20 at 20:04
  • A connection attempt failed because the connected party did not respond properly beyond a certain time, or an established connection failed because the connection host did not respond 171.18.28.75:443 System.Net. Sockets.SocketException to System.Net.Sockets.Socket.InternalEndConnect (IAsyncResult asyncResult) to System.Net.Sockets.Socket.EndConnect (IAsyncResult asyncResult) to System.Net.ServicePoint.ConnectSocketInternal (Boolean connectFailure, Socket s4, Socket s6, socket, IPAddress & address, ConnectSocketState state, IAsyncResult asyncResult, Exception & exception) – Firas Farhat Mar 06 '20 at 20:25
  • keep in your mind that the same method works for me when i call it from unit test o.O – Firas Farhat Mar 06 '20 at 20:27
  • It looks like a network connection error. Do you use appropriate connection parameters (url, clientid, secret etc) ? – zsolt Mar 06 '20 at 20:31
  • yes, the parameters used in the unit test are the same also used with the API framework – Firas Farhat Mar 06 '20 at 20:35
  • tokenResponse.Result contains this error : HttpErrorReason = {"The object reference is not defined to an instance of an object."}, ExpiresIn = 0, Exception = {"An error occurred while sending the request. "} IdentityModel.Client.TokenResponse – Firas Farhat Mar 06 '20 at 20:40
  • just guessing, is authenticationToken instantiated and does it have good value? – zsolt Mar 06 '20 at 21:10
  • I have a good value for the auithenticationToken but always i have the same exception. like i said, this function work very well when i call it from unit test, i guess that i have problem with identityModel and web api framework 4.6.1.. – Firas Farhat Mar 07 '20 at 17:07

0 Answers0