public async Task Test_TraktAuthenticationModule_GetAuthorization() { string authorizationJson = await TestUtility.SerializeObject(MockAuthorization); authorizationJson.Should().NotBeNullOrEmpty(); TraktClient client = TestUtility.GetAuthenticationMockClient(GET_AUTHORIZATION_URI, MockAuthorizationPostContent, authorizationJson); client.Authentication.OAuthAuthorizationCode = MOCK_AUTH_CODE; TraktResponse <ITraktAuthorization> response = await client.Authentication.GetAuthorizationAsync(); response.Should().NotBeNull(); response.IsSuccess.Should().BeTrue(); response.HasValue.Should().BeTrue(); response.Value.Should().NotBeNull(); ITraktAuthorization responseAuthorization = response.Value; responseAuthorization.Should().NotBeNull(); responseAuthorization.AccessToken.Should().Be(MockAuthorization.AccessToken); responseAuthorization.TokenType.Should().Be(MockAuthorization.TokenType); responseAuthorization.ExpiresInSeconds.Should().Be(MockAuthorization.ExpiresInSeconds); responseAuthorization.RefreshToken.Should().Be(MockAuthorization.RefreshToken); responseAuthorization.Scope.Should().Be(MockAuthorization.Scope); responseAuthorization.CreatedAt.Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromSeconds(3600)); responseAuthorization.IsExpired.Should().BeFalse(); ITraktAuthorization clientAuthorization = client.Authorization; clientAuthorization.Should().NotBeNull(); clientAuthorization.AccessToken.Should().Be(responseAuthorization.AccessToken); clientAuthorization.TokenType.Should().Be(responseAuthorization.TokenType); clientAuthorization.ExpiresInSeconds.Should().Be(responseAuthorization.ExpiresInSeconds); clientAuthorization.RefreshToken.Should().Be(responseAuthorization.RefreshToken); clientAuthorization.Scope.Should().Be(responseAuthorization.Scope); clientAuthorization.CreatedAt.Should().Be(responseAuthorization.CreatedAt); clientAuthorization.IsExpired.Should().BeFalse(); }
public async Task Test_TraktAuthenticationModule_RevokeAuthorization_With_Token_And_ClientId_And_ClientSecret() { TraktClient client = TestUtility.GetAuthenticationMockClient(REVOKE_AUTHORIZATION_URI, MockAuthorizationRevokePostContent); client.Authorization = MockAuthorization; TraktNoContentResponse response = await client.Authentication.RevokeAuthorizationAsync(TestConstants.MOCK_ACCESS_TOKEN, TraktClientId, TraktClientSecret); response.Should().NotBeNull(); response.IsSuccess.Should().BeTrue(); ITraktAuthorization authorization = client.Authorization; authorization.Should().NotBeNull(); authorization.AccessToken.Should().NotBeNull().And.BeEmpty(); authorization.RefreshToken.Should().NotBeNull().And.BeEmpty(); authorization.Scope.Should().Be(TraktAccessScope.Public); authorization.TokenType.Should().Be(TraktAccessTokenType.Bearer); authorization.CreatedAt.Should().BeCloseTo(DateTime.UtcNow, CLOSE_TO_PRECISION); authorization.ExpiresInSeconds.Should().Be(7776000U); authorization.IsExpired.Should().BeTrue(); authorization.IsRefreshPossible.Should().BeFalse(); authorization.IsValid.Should().BeFalse(); }
public async Task Test_TraktAuthenticationModule_RevokeAuthorization() { TraktClient client = TestUtility.GetAuthenticationMockClient(REVOKE_AUTHORIZATION_URI, MockAuthorizationRevokePostContent); client.Authorization = MockAuthorization; TraktNoContentResponse response = await client.Authentication.RevokeAuthorizationAsync(); response.Should().NotBeNull(); response.IsSuccess.Should().BeTrue(); ITraktAuthorization authorization = client.Authorization; authorization.Should().NotBeNull(); authorization.AccessToken.Should().NotBeNull().And.BeEmpty(); authorization.RefreshToken.Should().NotBeNull().And.BeEmpty(); authorization.Scope.Should().Be(TraktAccessScope.Public); authorization.TokenType.Should().Be(TraktAccessTokenType.Bearer); authorization.CreatedAt.Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromSeconds(3600)); authorization.ExpiresInSeconds.Should().Be(7776000U); authorization.IsExpired.Should().BeTrue(); authorization.IsRefreshPossible.Should().BeFalse(); authorization.IsValid.Should().BeFalse(); }
public async Task Test_TraktAuthenticationModule_PollForAuthorization_With_Device_And_ClientId_And_ClientSecret() { string authorizationJson = await TestUtility.SerializeObject(MockAuthorization); authorizationJson.Should().NotBeNullOrEmpty(); TraktClient client = TestUtility.GetAuthenticationMockClient(POLL_FOR_AUTHORIZATION_URI, MockAuthorizationPollingPostContent, authorizationJson); TraktResponse <ITraktAuthorization> response = await client.Authentication.PollForAuthorizationAsync(MockDevice, TraktClientId, TraktClientSecret); response.Should().NotBeNull(); response.IsSuccess.Should().BeTrue(); response.HasValue.Should().BeTrue(); response.Value.Should().NotBeNull(); ITraktAuthorization responseAuthorization = response.Value; responseAuthorization.Should().NotBeNull(); responseAuthorization.AccessToken.Should().Be(MockAuthorization.AccessToken); responseAuthorization.TokenType.Should().Be(MockAuthorization.TokenType); responseAuthorization.ExpiresInSeconds.Should().Be(MockAuthorization.ExpiresInSeconds); responseAuthorization.RefreshToken.Should().Be(MockAuthorization.RefreshToken); responseAuthorization.Scope.Should().Be(MockAuthorization.Scope); responseAuthorization.CreatedAt.Should().BeCloseTo(DateTime.UtcNow, CLOSE_TO_PRECISION); responseAuthorization.IsExpired.Should().BeFalse(); ITraktAuthorization clientAuthorization = client.Authorization; clientAuthorization.Should().NotBeNull(); clientAuthorization.AccessToken.Should().Be(responseAuthorization.AccessToken); clientAuthorization.TokenType.Should().Be(responseAuthorization.TokenType); clientAuthorization.ExpiresInSeconds.Should().Be(responseAuthorization.ExpiresInSeconds); clientAuthorization.RefreshToken.Should().Be(responseAuthorization.RefreshToken); clientAuthorization.Scope.Should().Be(responseAuthorization.Scope); clientAuthorization.CreatedAt.Should().Be(responseAuthorization.CreatedAt); clientAuthorization.IsExpired.Should().BeFalse(); }
public async Task <Pair <bool, TraktResponse <ITraktAuthorization> > > CheckIfAuthorizationIsExpiredOrWasRevokedAsync(ITraktAuthorization authorization, bool autoRefresh = false, CancellationToken cancellationToken = default) { ITraktAuthorization currentAuthorization = _client.Authorization; _client.Authorization = authorization ?? throw new ArgumentNullException(nameof(authorization)); var result = new Pair <bool, TraktResponse <ITraktAuthorization> >(true, new TraktResponse <ITraktAuthorization>()); try { result = await CheckIfAuthorizationIsExpiredOrWasRevokedAsync(autoRefresh, cancellationToken).ConfigureAwait(false); if (result.First && autoRefresh && result.Second.IsSuccess) { _client.Authorization = result.Second.Value; } } finally { if (!result.First) { _client.Authorization = currentAuthorization; } } return(result); }
private async Task <TraktResponse <ITraktAuthorization> > ExecuteAuthorizationRequestAsync <TRequestBodyType>(IPostRequest <ITraktAuthorization, TRequestBodyType> request, bool isRefreshRequest, CancellationToken cancellationToken = default) where TRequestBodyType : IRequestBody { try { request.Validate(); ExtendedHttpRequestMessage requestMessage = await _requestMessageBuilder.Reset(request) .WithRequestBody(request.RequestBody) .DisableAPIVersionHeader() .DisableAPIClientIdHeader() .Build().ConfigureAwait(false); HttpResponseMessage responseMessage = await _client.HttpClientProvider.GetHttpClient().SendAsync(requestMessage, cancellationToken).ConfigureAwait(false); HttpStatusCode responseCode = responseMessage.StatusCode; Stream responseContentStream; if (responseCode == HttpStatusCode.OK) { responseContentStream = await ResponseMessageHelper.GetResponseContentStreamAsync(responseMessage).ConfigureAwait(false); IObjectJsonReader <ITraktAuthorization> objectJsonReader = JsonFactoryContainer.CreateObjectReader <ITraktAuthorization>(); ITraktAuthorization traktAuthorization = await objectJsonReader.ReadObjectAsync(responseContentStream, cancellationToken).ConfigureAwait(false); var response = new TraktResponse <ITraktAuthorization>() { Value = traktAuthorization, HasValue = traktAuthorization != null, IsSuccess = traktAuthorization != null }; if (responseMessage.Headers != null) { ResponseHeaderParser.ParseResponseHeaderValues(response, responseMessage.Headers); } _client.Authentication.Authorization = traktAuthorization; return(response); } else if (responseCode == HttpStatusCode.Unauthorized) // Invalid code { responseContentStream = await ResponseMessageHelper.GetResponseContentStreamAsync(responseMessage).ConfigureAwait(false); IObjectJsonReader <ITraktError> objectJsonReader = JsonFactoryContainer.CreateObjectReader <ITraktError>(); ITraktError traktError = await objectJsonReader.ReadObjectAsync(responseContentStream, cancellationToken).ConfigureAwait(false); var errorMessage = traktError != null ? ($"error on {(isRefreshRequest ? "refreshing" : "retrieving")} oauth access token\nerror: {traktError.Error}\ndescription: {traktError.Description}") : "unknown error"; throw new TraktAuthenticationOAuthException(errorMessage) { StatusCode = responseCode, RequestUrl = requestMessage.Url, RequestBody = requestMessage.RequestBodyJson, ServerReasonPhrase = responseMessage.ReasonPhrase }; } await ResponseErrorHandler.HandleErrorsAsync(requestMessage, responseMessage, isAuthorizationRequest : true, cancellationToken : cancellationToken).ConfigureAwait(false); } catch (Exception ex) { if (_client.Configuration.ThrowResponseExceptions) { throw; } return(new TraktResponse <ITraktAuthorization> { IsSuccess = false, Exception = ex }); } return(new TraktResponse <ITraktAuthorization>()); }
public async Task <TraktResponse <ITraktAuthorization> > PollForAuthorizationAsync(AuthorizationPollRequest request, CancellationToken cancellationToken = default) { try { request.Validate(); ExtendedHttpRequestMessage requestMessage = await _requestMessageBuilder.Reset(request) .WithRequestBody(request.RequestBody) .DisableAPIVersionHeader() .DisableAPIClientIdHeader() .Build().ConfigureAwait(false); HttpResponseMessage responseMessage; Stream responseContentStream; HttpStatusCode responseCode; string reasonPhrase = string.Empty; uint totalExpiredSeconds = 0; ITraktDevice device = request.RequestBody.Device; IObjectJsonReader <ITraktAuthorization> objectJsonReader = JsonFactoryContainer.CreateObjectReader <ITraktAuthorization>(); while (totalExpiredSeconds < device.ExpiresInSeconds) { responseMessage = await _client.HttpClientProvider.GetHttpClient().SendAsync(requestMessage, cancellationToken).ConfigureAwait(false); responseCode = responseMessage.StatusCode; reasonPhrase = responseMessage.ReasonPhrase; if (responseCode == HttpStatusCode.OK) // Success { responseContentStream = await ResponseMessageHelper.GetResponseContentStreamAsync(responseMessage).ConfigureAwait(false); ITraktAuthorization traktAuthorization = await objectJsonReader.ReadObjectAsync(responseContentStream, cancellationToken).ConfigureAwait(false); var response = new TraktResponse <ITraktAuthorization>() { Value = traktAuthorization, HasValue = traktAuthorization != null, IsSuccess = traktAuthorization != null }; if (responseMessage.Headers != null) { ResponseHeaderParser.ParseResponseHeaderValues(response, responseMessage.Headers); } _client.Authentication.Authorization = traktAuthorization; return(response); } else if (responseCode == HttpStatusCode.BadRequest) // Pending { await Task.Delay((int)device.IntervalInMilliseconds).ConfigureAwait(false); totalExpiredSeconds += device.IntervalInSeconds; requestMessage = await _requestMessageBuilder.Reset(request).WithRequestBody(request.RequestBody).Build().ConfigureAwait(false); continue; } await ResponseErrorHandler.HandleErrorsAsync(requestMessage, responseMessage, isInAuthorizationPolling : true, cancellationToken : cancellationToken).ConfigureAwait(false); break; } throw new TraktAuthenticationDeviceException("unknown exception") { RequestUrl = requestMessage.Url, RequestBody = requestMessage.RequestBodyJson, ServerReasonPhrase = reasonPhrase }; } catch (Exception ex) { if (_client.Configuration.ThrowResponseExceptions) { throw; } return(new TraktResponse <ITraktAuthorization> { IsSuccess = false, Exception = ex }); } }
public Task <Pair <bool, TraktResponse <ITraktAuthorization> > > CheckIfAuthorizationIsExpiredOrWasRevokedAsync(ITraktAuthorization authorization, bool autoRefresh = false, CancellationToken cancellationToken = default) { var requestHandler = new AuthenticationRequestHandler(Client); return(requestHandler.CheckIfAuthorizationIsExpiredOrWasRevokedAsync(authorization, autoRefresh, cancellationToken)); }