예제 #1
0
        public override async Task <int> ExecuteAsync(
            InitCommandArguments arguments,
            CancellationToken cancellationToken)
        {
            using IDisposable command = Output.WriteCommand();

            AccessToken?accessToken =
                await arguments.AuthArguments
                .RequestTokenAsync(Output, cancellationToken)
                .ConfigureAwait(false);

            var context = new InitCommandContext(
                arguments.Name.Value()?.Trim() ?? Path.GetFileName(Environment.CurrentDirectory),
                FileSystem.ResolvePath(arguments.Path.Value()?.Trim()),
                new Uri(arguments.Uri.Value !),
                accessToken?.Token,
                accessToken?.Scheme,
                CustomHeaderHelper.ParseHeadersArgument(arguments.CustomHeaders.Values));

            if (await ExecuteInternalAsync(context, cancellationToken).ConfigureAwait(false))
            {
                return(0);
            }

            return(1);
        }
예제 #2
0
        public override async Task <int> ExecuteAsync(
            InitCommandArguments arguments,
            CancellationToken cancellationToken = default)
        {
            using IDisposable command = Output.WriteCommand();

            AccessToken?accessToken =
                await arguments.AuthArguments
                .RequestTokenAsync(Output, cancellationToken)
                .ConfigureAwait(false);

            var context = new InitCommandContext(
                arguments.Schema.Value()?.Trim() ?? "schema",
                FileSystem.ResolvePath(arguments.Path.Value()?.Trim()),
                new Uri(arguments.Uri.Value !),
                accessToken?.Token,
                accessToken?.Scheme);

            if (await ExecuteInternalAsync(context, cancellationToken).ConfigureAwait(false))
            {
                return(0);
            }

            return(1);
        }
예제 #3
0
        public override async Task <int> ExecuteAsync(
            DownloadCommandArguments arguments,
            CancellationToken cancellationToken)
        {
            using IDisposable command = Output.WriteCommand();

            AccessToken?accessToken =
                await arguments.AuthArguments
                .RequestTokenAsync(Output, cancellationToken)
                .ConfigureAwait(false);

            var context = new DownloadCommandContext(
                new Uri(arguments.Uri.Value !),
                FileSystem.ResolvePath(arguments.FileName.Value()?.Trim(), "schema.graphql"),
                accessToken?.Token,
                accessToken?.Scheme);

            FileSystem.EnsureDirectoryExists(
                FileSystem.GetDirectoryName(context.FileName));

            return(await DownloadSchemaAsync(
                       context, cancellationToken)
                   .ConfigureAwait(false)
                ? 0 : 1);
        }
        public virtual async Task <AccessToken> GetTokenAsync(CancellationToken cancellationToken)
        {
            if (!this.accessToken.HasValue || AccessTokenExpired)
            {
                this.accessToken = await this.tokenCredential.GetTokenAsync(new TokenRequestContext(this.scopes), cancellationToken).ConfigureAwait(false);
            }

            return(this.accessToken.Value);
        }
        internal CommunicationUserIdentifierAndToken(CommunicationIdentity identity, CommunicationIdentityAccessToken accessToken)
        {
            if (identity == null)
            {
                throw new ArgumentNullException(nameof(identity));
            }

            Identity            = identity;
            InternalAccessToken = accessToken;
            User         = new CommunicationUserIdentifier(identity.Id);
            _accessToken = accessToken is null ? null : new AccessToken(accessToken.Token, accessToken.ExpiresOn);
        }
예제 #6
0
        private async ValueTask <AccessToken> RefreshCachedTokenWithRetryHelperAsync(
            ITrace trace)
        {
            try
            {
                Exception?lastException   = null;
                const int totalRetryCount = 2;
                for (int retry = 0; retry < totalRetryCount; retry++)
                {
                    if (this.cancellationToken.IsCancellationRequested)
                    {
                        DefaultTrace.TraceInformation(
                            "Stop RefreshTokenWithIndefiniteRetries because cancellation is requested");

                        break;
                    }

                    using (ITrace getTokenTrace = trace.StartChild(
                               name: nameof(this.RefreshCachedTokenWithRetryHelperAsync),
                               component: TraceComponent.Authorization,
                               level: Tracing.TraceLevel.Info))
                    {
                        try
                        {
                            this.cachedAccessToken = await this.tokenCredential.GetTokenAsync(
                                requestContext : this.tokenRequestContext,
                                cancellationToken : default);

                            if (!this.cachedAccessToken.HasValue)
                            {
                                throw new ArgumentNullException("TokenCredential.GetTokenAsync returned a null token.");
                            }

                            if (this.cachedAccessToken.Value.ExpiresOn < DateTimeOffset.UtcNow)
                            {
                                throw new ArgumentOutOfRangeException($"TokenCredential.GetTokenAsync returned a token that is already expired. Current Time:{DateTime.UtcNow:O}; Token expire time:{this.cachedAccessToken.Value.ExpiresOn:O}");
                            }

                            if (!this.userDefinedBackgroundTokenCredentialRefreshInterval.HasValue)
                            {
                                double refreshIntervalInSeconds = (this.cachedAccessToken.Value.ExpiresOn - DateTimeOffset.UtcNow).TotalSeconds * DefaultBackgroundTokenCredentialRefreshIntervalPercentage;

                                // Ensure the background refresh interval is a valid range.
                                refreshIntervalInSeconds = Math.Max(refreshIntervalInSeconds, TokenCredentialCache.MinimumTimeBetweenBackgroundRefreshInterval.TotalSeconds);
                                refreshIntervalInSeconds = Math.Min(refreshIntervalInSeconds, TokenCredentialCache.MaxBackgroundRefreshInterval.TotalSeconds);
                                this.systemBackgroundTokenCredentialRefreshInterval = TimeSpan.FromSeconds(refreshIntervalInSeconds);
                            }

                            return(this.cachedAccessToken.Value);
                        }
예제 #7
0
        public override string GetAuthorizationHeader()
        {
            lock (_tokenLock)
            {
                // A new token is generated if it is the first time or the cached token is close to expiry.
                if (!_cachedAccessToken.HasValue ||
                    TokenHelper.IsCloseToExpiry(_cachedAccessToken.Value.ExpiresOn))
                {
                    _cachedAccessToken = _credential.GetToken(
                        new TokenRequestContext(CommonConstants.IotHubAadTokenScopes),
                        new CancellationToken());
                }
            }

            return($"Bearer {_cachedAccessToken.Value.Token}");
        }
        public override async Task <int> ExecuteAsync(
            PublishClientCommandArguments arguments,
            CancellationToken cancellationToken)
        {
            using IDisposable command = Output.WriteCommand();

            AccessToken?accessToken =
                await arguments.AuthArguments
                .RequestTokenAsync(Output, cancellationToken)
                .ConfigureAwait(false);

            var context = new PublishClientCommandContext(
                new Uri(arguments.Registry.Value !),
                arguments.EnvironmentName.Value !,
                arguments.SchemaName.Value !,
                arguments.ClientName.Value !,
                arguments.ExternalId.Value !,
                arguments.SearchDirectory.Value()?.Trim() ?? FileSystem.CurrentDirectory,
                arguments.QueryFileName.Values.Where(t => t is { }).ToList() !,
        public override async Task <int> ExecuteAsync(
            PublishSchemaCommandArguments arguments,
            CancellationToken cancellationToken)
        {
            using IDisposable command = Output.WriteCommand();

            AccessToken?accessToken =
                await arguments.AuthArguments
                .RequestTokenAsync(Output, cancellationToken)
                .ConfigureAwait(false);

            var context = new PublishSchemaCommandContext(
                new Uri(arguments.Registry.Value !),
                arguments.EnvironmentName.Value !,
                arguments.SchemaName.Value !,
                arguments.SchemaFileName.Value !,
                arguments.Tag.HasValue()
                    ? arguments.Tag.Values
                .Where(t => t !is { })
        // The HTTP protocol uses this method to get the bearer token for authentication.
        public override string GetAuthorizationHeader()
        {
#if NET451
            throw new InvalidOperationException($"TokenCredential is not supported on NET451");
#else
            lock (_tokenLock)
            {
                // A new token is generated if it is the first time or the cached token is close to expiry.
                if (!_cachedAccessToken.HasValue ||
                    TokenHelper.IsCloseToExpiry(_cachedAccessToken.Value.ExpiresOn))
                {
                    _cachedAccessToken = _credential.GetToken(
                        new TokenRequestContext(CommonConstants.IotHubAadTokenScopes),
                        new CancellationToken());
                }
            }

            return($"{TokenType} {_cachedAccessToken.Value.Token}");
#endif
        }
예제 #11
0
        /// <inheritdoc />
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var now = DateTimeOffset.Now;

            if (_authorizedUris == null)
            {
                throw new InvalidOperationException($"The '{nameof(CustomAuthorizationMessageHandler)}' is not configured. " +
                                                    $"Call '{nameof(CustomAuthorizationMessageHandler.ConfigureHandler)}' and provide a list of endpoint urls to attach the token to.");
            }

            if (_authorizedUris.Any(uri => uri.IsBaseOf(request.RequestUri !)))
            {
                if (_lastToken == null || now >= _lastToken.Expires.AddMinutes(-5))
                {
                    var tokenResult = _tokenOptions != null ?
                                      await _provider.RequestAccessToken(_tokenOptions) :
                                      await _provider.RequestAccessToken();

                    if (tokenResult.TryGetToken(out var token))
                    {
                        _lastToken    = token;
                        _cachedHeader = new AuthenticationHeaderValue("Bearer", _lastToken.Value);
                    }
                    else
                    {
                        _lastToken    = null;
                        _cachedHeader = null;
                    }
                }

                if (_cachedHeader != null)
                {
                    // We don't try to handle 401s and retry the request with a new token automatically since that would mean we need to copy the request
                    // headers and buffer the body and we expect that the user instead handles the 401s. (Also, we can't really handle all 401s as we might
                    // not be able to provision a token without user interaction).
                    request.Headers.Authorization = _cachedHeader;
                }
            }

            return(await base.SendAsync(request, cancellationToken));
        }
예제 #12
0
        public override async Task <int> ExecuteAsync(
            UpdateCommandArguments arguments,
            CancellationToken cancellationToken)
        {
            using IDisposable command = Output.WriteCommand();

            AccessToken?accessToken =
                await arguments.AuthArguments
                .RequestTokenAsync(Output, cancellationToken)
                .ConfigureAwait(false);

            var context = new UpdateCommandContext(
                arguments.Uri.HasValue() ? new Uri(arguments.Uri.Value() !.Trim()) : null,
                FileSystem.ResolvePath(arguments.Path.Value()?.Trim()),
                accessToken?.Token,
                accessToken?.Scheme);

            return(context.Path is null
                ? await FindAndUpdateSchemasAsync(context, cancellationToken)
                   .ConfigureAwait(false)
                : await UpdateSingleSchemaAsync(context, context.Path, cancellationToken)
                   .ConfigureAwait(false));
        }
예제 #13
0
 private bool IsTokenValid(AccessToken?token)
 => token != null && UtcNow() < token?.ExpiresOn;
예제 #14
0
 public void Login(AccessToken token)
 {
     _loginCredentials = token;
     _user             = GetUser <User>(new ViewerQuery());
 }
 public void SetAuthentication(AccessToken accessToken)
 {
     this.accessToken = accessToken;
 }
예제 #16
0
 public AccessInfo2(AccessToken?Token,
                    AccessStatus Status)
 {
     this.Token  = Token;
     this.Status = Status;
 }
 public ExchangeRefreshTokenResponse(AccessToken token, bool success = false, string?message = null) : base(success, message)
 {
     AccessToken = token;
 }
예제 #18
0
 public DisabledAccessTokenValueObject(CustomIdentityUser?customIdentityUser, AccessToken?accessToken)
 {
     CustomIdentityUser = customIdentityUser;
     AccessToken        = accessToken;
 }