private bool IsXsrfSafe(
			string cookie,
			string xsrfToken,
			IAccessToken accessToken,
			AuthenticationMode authMode
		) {

			if( authMode == AuthenticationMode.SkipXsrfValidation ) {
				return true;
			}

			bool isBrowserUser = !string.IsNullOrEmpty( cookie );
			if( !isBrowserUser ) {
				return true;
			}

			// we must now validate that the xsrf tokens match

			string xsrfTokenFromAccessToken = accessToken.GetXsrfToken();

			bool xsrfTokensEqual = xsrfTokenFromAccessToken == xsrfToken;
			bool xsrfTokenContainsValue = !string.IsNullOrEmpty( xsrfToken );

			if( !xsrfTokensEqual || !xsrfTokenContainsValue ) {
				return false;
			}

			return true;
		}
 internal FakeAccessTokenProvider(string token)
 {
     this.accessToken = new FakeAccessToken()
         {
             AccessToken = token
         };
 }
		public D2LPrincipal( IAccessToken accessToken ) {
			m_accessToken = accessToken;

			m_tenantId = new Lazy<Guid>( GetTenantId );

			m_scopes = new Lazy<List<Scope>>(
				() => m_accessToken.GetScopes().ToList()
			);

			long userId;
			if ( !m_accessToken.TryGetUserId( out userId ) ) {
				m_principalType = PrincipalType.Service;
				return;
			}

			m_userId = userId;

			long actualUserId;
			if ( !m_accessToken.TryGetActualUserId( out actualUserId ) ) {
				// Doing this means that code that wants to ignore
				// impersonation can do so with less branching.
				m_actualUserId = userId;
				return;
			}

			m_actualUserId = actualUserId;
		}
 public FakeAccessTokenProvider(string token, string userId)
 {
     this.accessToken = new MockAccessToken()
     {
         AccessToken = token,
         UserId = userId
     };
 }
		public D2LPrincipal( IAccessToken accessToken ) {
			m_accessToken = accessToken;

			m_userId = accessToken.GetUserId();
			m_tenantId = new Lazy<Guid>( GetTenantId );
			m_principalType = string.IsNullOrEmpty( m_userId ) ? PrincipalType.Service : PrincipalType.User;
			m_scopes = new Lazy<List<Scope>>( () => m_accessToken.GetScopes().ToList() );
		}
 public MockTokenAuthenticationFactory(string userId, string accessToken)
 {
     Token = new MockAccessToken
     {
         UserId      = userId,
         LoginType   = LoginType.OrgId,
         AccessToken = accessToken
     };
 }
 public MockTokenAuthenticationFactory(string userId, string accessToken)
 {
     Token = new MockAccessToken
     {
         UserId = userId,
         LoginType = LoginType.OrgId,
         AccessToken = accessToken
     };
 }
 public MockTokenAuthenticationFactory()
 {
     Token = new MockAccessToken
     {
         UserId = "Test",
         LoginType = LoginType.OrgId,
         AccessToken = "abc"
     };
 }
        /// <summary>Tests if this IAccessToken is considered equal to another.</summary>
        /// <param name="other">The i access token to compare to this object.</param>
        /// <returns>true if the objects are considered equal, false if they are not.</returns>
        public bool Equals(IAccessToken other)
        {
            if (this.ClientId == other.ClientId && this.RedirectUri == other.RedirectUri && this.Subject == other.Subject && this.ValidTo == other.ValidTo)
            {
                return true;
            }

            return false;
        }
Esempio n. 10
0
        /// <summary>Tests if this IAccessToken is considered equal to another.</summary>
        /// <param name="other">The i access token to compare to this object.</param>
        /// <returns>true if the objects are considered equal, false if they are not.</returns>
        public virtual bool Equals(IAccessToken other)
        {
            if (this.GetIdentifier() != other.GetIdentifier())
            {
                return(true);
            }

            return(false);
        }
 public MockTokenAuthenticationFactory()
 {
     Token = new MockAccessToken
     {
         UserId      = "Test",
         LoginType   = LoginType.OrgId,
         AccessToken = "abc"
     };
 }
Esempio n. 12
0
        public void Login(
            AzureAccount account,
            AzureEnvironment environment)
        {
            ShowDialog promptBehavior = ShowDialog.Always;

            var tenants = ListAccountTenants(account, environment, promptBehavior).ToArray();

            account.SetProperty(AzureAccount.Property.Tenants, null);
            string accountId = null;

            List <AzureSubscription> azureSubscriptions = new List <AzureSubscription>();
            List <string>            authtokens         = new List <string>();

            for (int i = 0; i < tenants.Count(); i++)
            {
                var tenant = tenants[i].Id.ToString();

                IAccessToken token = AcquireAccessToken(account, environment, tenant, ShowDialog.Auto);

                if (accountId == null)
                {
                    accountId = account.Id;
                    account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant);
                }
                else if (accountId.Equals(account.Id, StringComparison.OrdinalIgnoreCase))
                {
                    account.SetOrAppendProperty(AzureAccount.Property.Tenants, tenant);
                }
                else
                {   // if account ID is different from the first tenant account id we need to ignore current tenant
                    Console.WriteLine(string.Format(
                                          "Account ID '{0}' for tenant '{1}' does not match home Account ID '{2}'",
                                          account.Id,
                                          tenant,
                                          accountId));
                    account.Id = accountId;
                    token      = null;
                }

                int found = TryGetTenantSubscription(token, account, environment, tenant, azureSubscriptions, authtokens);
            }

            for (int i = 0; i < azureSubscriptions.Count; ++i)
            {
                var subscription = azureSubscriptions[i];

                Console.WriteLine("Subscription:");
                Console.WriteLine("  Name    = {0}", subscription.Name);
                Console.WriteLine("  Id      = {0}", subscription.Id);
                Console.WriteLine("  State   = {0}", subscription.State);
                Console.WriteLine("  Account = {0}", subscription.Account);

                ShowIoTHubsInSubscription(subscription.Id.ToString(), authtokens[i]).Wait();
            }
        }
Esempio n. 13
0
        private async Task RunTest(
            bool signJwt,
            DateTime jwtExpiry,
            Type expectedExceptionType = null
            )
        {
            string             keyId              = Guid.NewGuid().ToString();
            D2LSecurityToken   signingToken       = D2LSecurityTokenUtility.CreateActiveToken(id: keyId);
            SigningCredentials signingCredentials = null;

            if (signJwt)
            {
                signingCredentials = signingToken.GetSigningCredentials();
            }

            var jwtToken = new JwtSecurityToken(
                issuer: "someissuer",
                signingCredentials: signingCredentials,
                expires: jwtExpiry
                );

            var    tokenHandler  = new JwtSecurityTokenHandler();
            string serializedJwt = tokenHandler.WriteToken(jwtToken);

            IPublicKeyProvider publicKeyProvider = PublicKeyProviderMock.Create(
                m_jwksEndpoint,
                keyId,
                signingToken
                ).Object;

            IAccessTokenValidator tokenValidator = new AccessTokenValidator(
                publicKeyProvider
                );

            IAccessToken accessToken = null;
            Exception    exception   = null;

            try {
                accessToken = await tokenValidator.ValidateAsync(
                    accessToken : serializedJwt
                    ).ConfigureAwait(false);
            } catch (Exception e) {
                exception = e;
            }

            if (expectedExceptionType != null)
            {
                Assert.IsNull(accessToken, "Unexpected access token returned from validation");
                Assert.IsNotNull(exception, "Expected an exception but got null");
                Assert.AreEqual(expectedExceptionType, exception.GetType(), "Wrong exception type");
            }
            else
            {
                Assert.IsNotNull(accessToken, "Expected an access token but got none");
            }
        }
        private async Task RunTest(
            string request_authorizationHeader,
            Type expectedExceptionType           = null,
            PrincipalType?expected_principalType = null
            )
        {
            IAccessToken token = AccessTokenMock.Create().Object;

            IAccessTokenValidator tokenValidator = AccessTokenValidatorMock.Create(
                accessToken: ACCESS_TOKEN,
                accessTokenAfterValidation: token,
                expectedExceptionType: expectedExceptionType
                ).Object;

            IRequestAuthenticator authenticator = new RequestAuthenticator(tokenValidator);

            var httpRequestMessage = new HttpRequestMessage()
                                     .WithAuthHeader(request_authorizationHeader);

            ID2LPrincipal principal = null;
            Exception     exception = null;

            try {
                principal = await authenticator.AuthenticateAsync(
                    httpRequestMessage
                    ).SafeAsync();
            } catch (Exception e) {
                exception = e;
            }

            CheckExpectations(
                principal,
                exception,
                expectedExceptionType,
                expected_principalType);

            exception = null;

            HttpRequest httpRequest = RequestBuilder
                                      .Create()
                                      .WithAuthHeader(request_authorizationHeader);

            try {
                principal = await authenticator.AuthenticateAsync(
                    httpRequest
                    ).SafeAsync();
            } catch (Exception e) {
                exception = e;
            }

            CheckExpectations(
                principal,
                exception,
                expectedExceptionType,
                expected_principalType);
        }
Esempio n. 15
0
        public async Task <bool> DeleteAccessToken(IAccessToken accessToken)
        {
            var Service = StoreConstants.TokenServiceClient;

            if (accessToken == null || string.IsNullOrEmpty(accessToken.Token))
            {
                throw new ArgumentException("accessToken.token MUST be set", "accessToken");
            }
            return(await DeleteAccessToken(accessToken.Token));
        }
Esempio n. 16
0
 /// <summary>Initializes a new instance of the Sentinel.OAuth.Core.Models.OAuth.AccessToken class.</summary>
 /// <param name="accessToken">The access token.</param>
 public AccessToken(IAccessToken accessToken)
 {
     this.ClientId    = accessToken.ClientId;
     this.RedirectUri = accessToken.RedirectUri;
     this.Subject     = accessToken.Subject;
     this.Token       = accessToken.Token;
     this.Ticket      = accessToken.Ticket;
     this.ValidTo     = accessToken.ValidTo;
     this.Scope       = accessToken.Scope;
 }
Esempio n. 17
0
        /// <summary>
        /// Initializes a new instance of the Sentinel.OAuth.TokenManagers.SqlServerTokenRepository.Models.OAuth.SqlAccessToken class.
        /// </summary>
        /// <param name="accessToken">The access token.</param>
        public SqlAccessToken(IAccessToken accessToken)
            : base(accessToken)
        {
            if (accessToken is SqlAccessToken)
            {
                this.Id = ((SqlAccessToken)accessToken).Id;
            }

            this.Created = DateTimeOffset.UtcNow;
        }
Esempio n. 18
0
        public static string GetDomain(this IAccessToken token)
        {
            if (token != null && token.UserId != null && token.UserId.Contains('@'))
            {
                return(token.UserId.Split(
                           new[] { '@' },
                           StringSplitOptions.RemoveEmptyEntries).Last());
            }

            return(null);
        }
 public IList <AzureSubscription> ListAllSubscriptionsForTenant(IAccessToken accessToken, IAzureAccount account, IAzureEnvironment environment)
 {
     using (var subscriptionClient = AzureSession.Instance.ClientFactory.CreateCustomArmClient <SubscriptionClient>(
                environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager),
                new TokenCredentials(accessToken.AccessToken) as ServiceClientCredentials,
                AzureSession.Instance.ClientFactory.GetCustomHandlers()))
     {
         return((subscriptionClient.ListAllSubscriptions()?
                 .Select(s => s.ToAzureSubscription(account, environment, accessToken.TenantId))).ToList() ?? new List <AzureSubscription>());
     }
 }
Esempio n. 20
0
        /// <summary>
        /// Get the token string from the accesstoken
        /// </summary>
        /// <param name="accessToken">the token</param>
        /// <returns>token string</returns>
        private string GetTokenStrFromAccessToken(IAccessToken accessToken)
        {
            var tokenStr = string.Empty;

            accessToken.AuthorizeRequest((tokenType, tokenValue) =>
            {
                tokenStr = tokenValue;
            });
            WriteDebug(DateTime.Now.ToString() + ": token:" + tokenStr);
            return(tokenStr);
        }
Esempio n. 21
0
 public SecurityController(IMemberService memberService, DefaultUserManager userManager, IUserContainer userContainer, ISecurityService securityService, ICurrencyService currencyService, ISmsService smsService, ISignals signals, IAccessToken accessToken)
 {
     _memberService   = memberService;
     _userManager     = userManager;
     _userContainer   = userContainer;
     _securityService = securityService;
     _currencyService = currencyService;
     _smsService      = smsService;
     _signals         = signals;
     _accessToken     = accessToken;
 }
Esempio n. 22
0
        private void Initialize(IAccessToken token, string path, string httpMethod = default(string), string version = default(string))
        {
            _token     = (token as DroidAccessToken).ToNative();
            Path       = path;
            HttpMethod = httpMethod;
            Version    = version;

            GraphCallback callback = new GraphCallback();

            _request = new GraphRequest(_token, Path, null, null, callback);
        }
Esempio n. 23
0
        public async Task <IActionResult> LoginByPinCode([FromBody] PinCodeModel model)
        {
            IAccessToken accessToken = await m_auth_service.LoginByPinCode(model.Cellular, model.Email, model.PinCode);

            if (accessToken == null || accessToken.HasExpired)
            {
                return(Forbid());
            }

            return(Ok(new AccessTokenModel(accessToken)));
        }
Esempio n. 24
0
        public async Task <IActionResult> Login([FromBody] LoginModel model)
        {
            IAccessToken accessToken = await m_auth_service.SignIn(model.Name, model.Password);

            if (accessToken == null)
            {
                return(Forbid());
            }

            return(Ok(new AccessTokenModel(accessToken)));
        }
Esempio n. 25
0
        public async Task <IActionResult> GetActiveOrders([FromBody] AccessTokenModel model)
        {
            IAccessToken accessToken = await m_token_service.GetToken(model.Token);

            if (accessToken == null || accessToken.HasExpired)
            {
                return(BadRequest());
            }

            return(Ok((await m_order_provider.GetActiveOrders(accessToken.User)).Select(x => new OrderModel(accessToken, x)).ToArray()));
        }
Esempio n. 26
0
        protected virtual void SetAccessToken(HttpApplication application, OAuthRequestContext context)
        {
            IAccessToken accessToken = null;

            if (context.Parameters.Token == null && ServiceProviderContext.Settings.AllowConsumerRequests)
            {
                accessToken = new EmptyAccessToken(context.Consumer.Key);
            }
            else if (ServiceProviderContext.TokenStore.ContainsAccessToken(context.Parameters.Token))
            {
                accessToken = ServiceProviderContext.TokenStore.GetAccessToken(context.Parameters.Token);
            }

            if (accessToken == null)
            {
                OAuthRequestException.ThrowTokenRejected(null);
            }
            else
            {
                /*
                 * Ensure the token was issued to the same consumer as this request purports
                 * to be from.
                 */
                if (!accessToken.ConsumerKey.Equals(context.Parameters.ConsumerKey))
                {
                    OAuthRequestException.ThrowTokenRejected(null);
                }

                switch (accessToken.Status)
                {
                case TokenStatus.Authorized:
                    context.AccessToken = accessToken;
                    break;

                case TokenStatus.Expired:
                    OAuthRequestException.ThrowTokenExpired(null);
                    break;

                case TokenStatus.Used:
                    OAuthRequestException.ThrowTokenUsed(null);
                    break;

                case TokenStatus.Revoked:
                    OAuthRequestException.ThrowTokenRevoked(null);
                    break;

                case TokenStatus.Unauthorized:
                case TokenStatus.Unknown:
                default:
                    OAuthRequestException.ThrowTokenRejected(null);
                    break;
                }
            }
        }
Esempio n. 27
0
        public override async Task <string> GetAccessTokenAsync()
        {
            if (this.accessToken != null)
            {
                if (this.accessToken.ValidToUtc > DateTime.UtcNow.AddSeconds(this.RefreshBeforeExpirationSeconds))
                {
                    return(this.accessToken.Token);
                }

                await this.StorageLock.WaitAsync();

                try
                {
                    if (this.accessToken.ValidToUtc <= DateTime.UtcNow.AddSeconds(this.RefreshBeforeExpirationSeconds))
                    {
                        var newToken = await this.RequestAccessTokenAsync();

                        this.accessToken = newToken;
                        return(newToken.Token);
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    this.StorageLock.Release();
                }
            }

            await this.StorageLock.WaitAsync();

            try
            {
                if (this.accessToken == null)
                {
                    var newToken = await this.RequestAccessTokenAsync();

                    this.accessToken = newToken;
                    return(newToken.Token);
                }

                return(this.accessToken.Token);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                this.StorageLock.Release();
            }
        }
Esempio n. 28
0
        private RenewTokenFuncAsync GetTokenRenewer(IAccessToken accessToken)
        {
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
            RenewTokenFuncAsync renewer = async(Object state, CancellationToken cancellationToken) =>
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
            {
                var tokenStr = GetTokenStrFromAccessToken(accessToken);
                return(new NewTokenAndFrequency(tokenStr, new TimeSpan(0, 1, 0)));
            };
            return(renewer);
        }
Esempio n. 29
0
        public async Task <IAccessToken> InsertAccessToken(IAccessToken accessToken)
        {
            var Service        = StoreConstants.TokenServiceClient;
            var newAccessToken = new AccessToken(accessToken);

            newAccessToken.IssuedAt = DateTimeOffset.UtcNow.DateTime;
            var uri     = string.Format("api/oauth/token/accesstoken/create");
            var success = await Service.PostAsync <bool, AccessToken>(uri, newAccessToken);

            return(newAccessToken);
        }
Esempio n. 30
0
        public async Task <IActionResult> GetData([FromBody] AccessTokenModel model)
        {
            IAccessToken accessToken = await m_token_service.GetToken(model.Token);

            if (accessToken == null || accessToken.HasExpired)
            {
                return(NotFound());
            }

            return(Ok(new UserDataModel(accessToken.User)));
        }
Esempio n. 31
0
        public static AzureTenant ToAzureTenant(this TenantIdDescription other, IAccessToken accessToken)
        {
            var tenant = new AzureTenant()
            {
                Id = other.TenantId
            };

            tenant.SetProperty(AzureTenant.Property.Directory, accessToken?.GetDomain());

            return(tenant);
        }
Esempio n. 32
0
        public async Task ProvisionAccessTokenAsync_AlreadyCached_UsesCachedValueAndDoesNotCallThroughToAccessTokenProvider()
        {
            m_serviceTokenCacheMock.Setup(x => x.GetAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(new CacheResponse(true, BuildTestToken())));

            IAccessTokenProvider cachedAccessTokenProvider = GetCachedAccessTokenProvider();

            IAccessToken token =
                await cachedAccessTokenProvider.ProvisionAccessTokenAsync(m_claims, m_scopes, m_serviceTokenCacheMock.Object).ConfigureAwait(false);

            Assert.NotNull(token);
        }
        /// <param name="token">An access token</param>
        /// <param name="claimName">The name of the claim whose value is returned</param>
        /// <returns>The claim value</returns>
        internal static string GetClaimValue(this IAccessToken token, string claimName)
        {
            string claimValue = null;
            Claim  claim      = token.Claims.FirstOrDefault(x => x.Type == claimName);

            if (claim != null)
            {
                claimValue = claim.Value;
            }

            return(claimValue);
        }
Esempio n. 34
0
 /// <summary>
 /// Set the access token to use for authentication
 /// when creating azure management clients from this
 /// subscription. This also updates the <see cref="ActiveDirectoryUserId"/> field.
 /// </summary>
 /// <param name="token">The access token to use. If null,
 /// clears out the token and the active directory login information.</param>
 public void SetAccessToken(IAccessToken token)
 {
     if (token != null)
     {
         ActiveDirectoryUserId = token.UserId;
     }
     else
     {
         ActiveDirectoryUserId = null;
     }
     accessToken = token;
 }
Esempio n. 35
0
        public async Task ProvisionAccessTokenAsync_ServiceClaimProvided_ServiceCacheUsed()
        {
            m_serviceTokenCacheMock.Setup(x => x.GetAsync(It.IsAny <string>()))
            .Returns(Task.FromResult(new CacheResponse(true, BuildTestToken(specifyUserClaim: false))));

            IAccessTokenProvider cachedAccessTokenProvider = GetCachedAccessTokenProvider();

            IAccessToken token =
                await cachedAccessTokenProvider.ProvisionAccessTokenAsync(m_claims, m_scopes, m_serviceTokenCacheMock.Object).ConfigureAwait(false);

            Assert.NotNull(token);
        }
Esempio n. 36
0
        /// <summary>Deletes the specified access token.</summary>
        /// <param name="accessToken">The access token.</param>
        /// <returns><c>True</c> if successful, <c>false</c> otherwise.</returns>
        public async Task <bool> DeleteAccessToken(IAccessToken accessToken)
        {
            var token = this.accessTokens.FirstOrDefault(x => x.Key == accessToken.Token);

            if (token.Value != null)
            {
                AccessToken removedToken;
                return(this.accessTokens.TryRemove(token.Key, out removedToken));
            }

            return(false);
        }
Esempio n. 37
0
 void VerifyToken(IAccessToken checkToken, string expectedAccessToken, string expectedUserId, string expectedTenant)
 {
     Assert.True(checkToken is RawAccessToken);
     Assert.Equal(expectedAccessToken, checkToken.AccessToken);
     Assert.Equal(expectedUserId, checkToken.UserId);
     Assert.Equal(expectedTenant, checkToken.TenantId);
     checkToken.AuthorizeRequest((type, token) =>
     {
         Assert.Equal(expectedAccessToken, token);
         Assert.Equal("Bearer", type);
     });
 }
Esempio n. 38
0
 private SubscriptionCloudCredentials CreateCredentials()
 {
     if (accessToken == null && ActiveDirectoryUserId == null)
     {
         return(new CertificateCloudCredentials(SubscriptionId, Certificate));
     }
     if (accessToken == null)
     {
         accessToken = TokenProvider.GetCachedToken(this, ActiveDirectoryUserId);
     }
     return(new AccessTokenCredential(SubscriptionId, accessToken));
 }
Esempio n. 39
0
        public OAuthPrincipal(IAccessToken accessToken)
        {
            if (accessToken == null)
                throw new ArgumentNullException("accessToken");

            if (accessToken.RequestToken == null)
                throw new ArgumentException("Access token must have a request token", "accessToken");

            if (accessToken.RequestToken.AuthenticatedUser == null)
                throw new ArgumentException("Request token must have an authenticated user", "accessToken");

            this.accessToken = accessToken;
            requestToken = accessToken.RequestToken;
            identity = RequestToken.AuthenticatedUser;
        }
        public IAccessToken Authenticate(ref AzureAccount account, AzureEnvironment environment, string tenant, SecureString password,
            ShowDialog promptBehavior)
        {
            if (account.Id == null)
            {
                account.Id = "test";
            }

            Token = new MockAccessToken
            {
                UserId = account.Id,
                LoginType = LoginType.OrgId,
                AccessToken = Token.AccessToken
            };

            return Token;
        }
Esempio n. 41
0
        /// <summary>
        /// Creates an OAuthPrincipal from an access token
        /// </summary>
        /// <param name="accessToken">Access token</param>
        public OAuthPrincipal(IAccessToken accessToken)
        {
            if (accessToken == null)
                throw new ArgumentNullException("accessToken");

            if (accessToken.RequestToken == null)
                throw new ArgumentException("Access token must have a request token", "accessToken");

            if (accessToken.RequestToken.AuthenticatedUser == null)
                throw new ArgumentException("Request token must have an authenticated user", "accessToken");

            this.AccessToken = accessToken;
            this.RequestToken = accessToken.RequestToken;

            if (ServiceProviderContext.Settings.ImpersonateUserForProtectedResources)
                this.Identity = this.RequestToken.AuthenticatedUser;
            else
                this.Identity = ServiceProviderContext.DummyIdentity;
        }
		public static Mock<IAccessTokenValidator> Create(
			string accessToken,
			IAccessToken accessTokenAfterValidation,
			Type expectedExceptionType
		) {
			var mock = new Mock<IAccessTokenValidator>();

			var invocation = mock.Setup( v => v.ValidateAsync( accessToken ) );

			if( expectedExceptionType == typeof( ValidationException ) ) {
				invocation.Throws( new ValidationException( "" ) );
			} else if( expectedExceptionType != null ) {
				invocation.Throws( ( Exception )Activator.CreateInstance( expectedExceptionType, "" ) );
			} else {
				Assert.IsNotNull( accessTokenAfterValidation );
				invocation.ReturnsAsync( accessTokenAfterValidation );
			}

			return mock;
		}
Esempio n. 43
0
        public static List<AzureTenant> MergeTenants(
            this AzureAccount account,
            IEnumerable<TenantIdDescription> tenants,
            IAccessToken token)
        {
            List<AzureTenant> result = null;
            if (tenants != null)
            {
                var existingTenants = new List<AzureTenant>();
                account.SetProperty(AzureAccount.Property.Tenants, null);
                tenants.ForEach((t) =>
                {
                    existingTenants.Add(new AzureTenant { Id = new Guid(t.TenantId), Domain = token.GetDomain() });
                    account.SetOrAppendProperty(AzureAccount.Property.Tenants, t.TenantId);
                });

                result = existingTenants;
            }

            return result;
        }
Esempio n. 44
0
 public override bool Update(IAccessToken token)
 {
     throw new NotSupportedException("Tokens cannot be updated in the token store--it is fixed.");
 }
Esempio n. 45
0
        private int TryGetTenantSubscription(IAccessToken accessToken,
            AzureAccount account,
            AzureEnvironment environment,
            string tenantId,
            List<AzureSubscription> azureSubscriptions,
            List<string> authtokens)
        {
            using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient<SubscriptionClient>(
                new TokenCloudCredentials(accessToken.AccessToken),
                environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
            {
                var subscriptions = (subscriptionClient.Subscriptions.List().Subscriptions ??
                                        new List<Microsoft.Azure.Subscriptions.Models.Subscription>())
                                    .Where(s => "enabled".Equals(s.State, StringComparison.OrdinalIgnoreCase) ||
                                                "warned".Equals(s.State, StringComparison.OrdinalIgnoreCase));

                account.SetProperty(AzureAccount.Property.Subscriptions, subscriptions.Select(i => i.SubscriptionId).ToArray());

                foreach (var subscriptionFromServer in subscriptions)
                {
                    var currentSubscription = new AzureSubscription
                    {
                        Id = new Guid(subscriptionFromServer.SubscriptionId),
                        Account = accessToken.UserId,
                        Environment = environment.Name,
                        Name = subscriptionFromServer.DisplayName,
                        State = subscriptionFromServer.State,
                        Properties = new Dictionary<AzureSubscription.Property, string>
                        {
                            { AzureSubscription.Property.Tenants, accessToken.TenantId }
                        }
                    };

                    azureSubscriptions.Add(currentSubscription);
                    authtokens.Add(accessToken.AccessToken);
                }

                return subscriptions.Count();
            }
        }
        /// <summary>Inserts the specified access token. Called when creating an access token.</summary>
        /// <param name="accessToken">The access token.</param>
        /// <returns>The inserted access token. <c>null</c> if the insertion was unsuccessful.</returns>
        public async Task<IAccessToken> InsertAccessToken(IAccessToken accessToken)
        {
            var token = (SqlAccessToken)accessToken;

            using (var connection = this.OpenConnection())
            {
                var id =
                    await
                    connection.QueryAsync<long>(
                        "INSERT INTO AccessTokens (ClientId, RedirectUri, Subject, Scope, Token, Ticket, ValidTo, Created) VALUES (@ClientId, @RedirectUri, @Subject, @Scope, @Token, @Ticket, @ValidTo, @Created); SELECT CAST(SCOPE_IDENTITY() as bigint);",
                        new
                        {
                            token.ClientId,
                            token.RedirectUri,
                            token.Subject,
                            Scope = string.Join(" ", token.Scope),
                            token.Token,
                            token.Ticket,
                            token.ValidTo,
                            token.Created
                        });

                var data = await connection.QueryAsync("SELECT * FROM AccessTokens WHERE Id = @Id", new { Id = id });
                var entities =
                    data.Select(
                        x =>
                        new SqlAccessToken()
                        {
                            ClientId = x.ClientId,
                            Created = x.Created,
                            Id = x.Id,
                            RedirectUri = x.RedirectUri,
                            Subject = x.Subject,
                            Token = x.Token,
                            Ticket = x.Ticket,
                            ValidTo = x.ValidTo,
                            Scope = x.Scope != null ? x.Scope.ToString().Split(' ') : new string[0]
                        });

                return entities.FirstOrDefault();
            }
        }
        /// <summary>Deletes the specified access token.</summary>
        /// <param name="accessToken">The access token.</param>
        /// <returns><c>True</c> if successful, <c>false</c> otherwise.</returns>
        public async Task<bool> DeleteAccessToken(IAccessToken accessToken)
        {
            var token = (RavenAccessToken)accessToken;

            using (var session = this.OpenAsyncSession())
            {
                var match = await session.LoadAsync<RavenAccessToken>(token.Id);

                session.Delete(match);
                await session.SaveChangesAsync();

                return true;
            }
        }
Esempio n. 48
0
        /// <summary>
        /// Updates the the given access token in the store. 
        /// </summary>
        /// <param name="token">The token to update</param>
        /// <returns><c>true</c>, iff the token was successfully updated
        /// in the store.</returns>
        public virtual bool Update(IAccessToken token)
        {
            if (token == null)
                throw new ArgumentNullException("token");

            lock (SyncRoot)
            {
                if (!this.ContainsAccessToken(token.Token))
                    return false;
                else
                    this.AccessTokenDictionary[token.Token] = token;
            }

            return true;
        }
        /// <summary>Deletes the specified access token.</summary>
        /// <param name="accessToken">The access token.</param>
        /// <returns><c>True</c> if successful, <c>false</c> otherwise.</returns>
        public async Task<bool> DeleteAccessToken(IAccessToken accessToken)
        {
            var token = (SqlAccessToken)accessToken;

            using (var connection = this.OpenConnection())
            {
                var rows =
                    await
                    connection.ExecuteAsync(
                        "DELETE FROM AccessTokens WHERE Id = @Id",
                        new { Id = token.Id });

                return rows == 1;
            }
        }
Esempio n. 50
0
        /// <summary>
        /// Removes the specified access token from the store.
        /// </summary>
        /// <param name="token">The token to remove</param>
        /// <returns><c>true</c>, iff the token was successfully removed
        /// from the store. This will return <c>false</c> if the token
        /// did not exist in the store.</returns>
        public virtual bool Remove(IAccessToken token)
        {
            if (token == null)
                throw new ArgumentNullException("token");

            lock (SyncRoot)
            {
                if (!this.ContainsAccessToken(token.Token))
                    return false;
                else
                    return this.AccessTokenDictionary.Remove(token.Token);
            }
        }
        private bool TryGetTenantSubscription(IAccessToken accessToken,
            AzureAccount account,
            AzureEnvironment environment,
            string tenantId,
            string subscriptionId,
            string subscriptionName,
            out AzureSubscription subscription,
            out AzureTenant tenant)
        {
            using (var subscriptionClient = AzureSession.ClientFactory.CreateCustomClient<SubscriptionClient>(
                new TokenCloudCredentials(accessToken.AccessToken),
                environment.GetEndpointAsUri(AzureEnvironment.Endpoint.ResourceManager)))
            {
                Subscriptions.Models.Subscription subscriptionFromServer = null;

                try
                {
                    if (subscriptionId != null)
                    {
                        subscriptionFromServer = subscriptionClient.Subscriptions.Get(subscriptionId).Subscription;
                    }
                    else
                    {
                        var subscriptions = (subscriptionClient.Subscriptions.List().Subscriptions ?? 
                                                new List<Microsoft.Azure.Subscriptions.Models.Subscription>())
                                            .Where(s => "enabled".Equals(s.State, StringComparison.OrdinalIgnoreCase) ||
                                                        "warned".Equals(s.State, StringComparison.OrdinalIgnoreCase));

                        if (subscriptions.Any())
                        {
                            if (subscriptionName != null)
                            {
                                subscriptionFromServer = subscriptions.FirstOrDefault(
                                    s => s.DisplayName.Equals(subscriptionName, StringComparison.OrdinalIgnoreCase));
                            }
                            else
                            {
                                if (subscriptions.Count() > 1)
                                {
                                    WriteWarningMessage(string.Format(
                                        "TenantId '{0}' contains more than one active subscription. First one will be selected for further use. " +
                                        "To select another subscription, use Set-AzureRmContext.",
                                        tenantId));
                                }
                                subscriptionFromServer = subscriptions.First();
                            }
                        }
                    }
                }
                catch (CloudException ex)
                {
                    WriteWarningMessage(ex.Message);
                }

                if (subscriptionFromServer != null)
                {
                    subscription = new AzureSubscription
                    {
                        Id = new Guid(subscriptionFromServer.SubscriptionId),
                        Account = accessToken.UserId,
                        Environment = environment.Name,
                        Name = subscriptionFromServer.DisplayName,
                        Properties = new Dictionary<AzureSubscription.Property, string> { { AzureSubscription.Property.Tenants, accessToken.TenantId } }
                    };

                    tenant = new AzureTenant();
                    tenant.Id = new Guid(accessToken.TenantId);
                    tenant.Domain = accessToken.GetDomain();
                    return true;
                }

                subscription = null;

                if (accessToken != null && accessToken.TenantId != null)
                {
                    tenant = new AzureTenant();
                    tenant.Id = Guid.Parse(accessToken.TenantId);
                    if (accessToken.UserId != null)
                    {
                        var domain = accessToken.UserId.Split(new[] { '@' }, StringSplitOptions.RemoveEmptyEntries);
                        if (domain.Length == 2)
                        {
                            tenant.Domain = domain[1];
                        }
                    }
                    return true;
                }

                tenant = null;
                return false;
            }
        }
 public AccessTokenCredential(string subscriptionId, IAccessToken token)
 {
     this.subscriptionId = subscriptionId;
     this.token = token;
 }
        /// <summary>Deletes the specified access token.</summary>
        /// <param name="accessToken">The access token.</param>
        /// <returns><c>True</c> if successful, <c>false</c> otherwise.</returns>
        public async Task<bool> DeleteAccessToken(IAccessToken accessToken)
        {
            var i = 0;
            var tokens = this.accessTokens.Where(x => x.Value.ClientId == accessToken.ClientId && x.Value.RedirectUri == accessToken.RedirectUri && x.Value.Subject == accessToken.Subject).ToList();

            foreach (var token in tokens)
            {
                AccessToken removedToken;
                if (this.accessTokens.TryRemove(token.Key, out removedToken))
                {
                    i++;
                }
            }

            return i == 1;
        }
 public AccessTokenCredential(Guid subscriptionId, IAccessToken token)
 {
     this.subscriptionId = subscriptionId;
     this.token = token;
     this.TenantID = token.TenantId;
 }
Esempio n. 55
0
 public AccessTokenResponse(IAccessToken token)
 {
     _token = token;
 }
Esempio n. 56
0
 public override bool Remove(IAccessToken token)
 {
     throw new NotSupportedException("Tokens cannot be removed from the token store--it is fixed.");
 }
        /// <summary>Inserts the specified access token. Called when creating an access token.</summary>
        /// <param name="accessToken">The access token.</param>
        /// <returns>The inserted access token. <c>null</c> if the insertion was unsuccessful.</returns>
        public async Task<IAccessToken> InsertAccessToken(IAccessToken accessToken)
        {
            var token = (RavenAccessToken)accessToken;

            using (var session = this.OpenAsyncSession())
            {
                await session.StoreAsync(token);
                await session.SaveChangesAsync();

                return accessToken;
            }
        }
Esempio n. 58
0
        private bool Equals(IAccessToken other)
        {
            if (other == null)
                return false;

            return string.Equals(this.Token, other.Token)
                && string.Equals(this.Secret, other.Secret)
                && this.Status == other.Status
                && string.Equals(this.ConsumerKey, other.ConsumerKey)
                && ((this.RequestToken == null && other.RequestToken == null ) || (this.RequestToken != null && this.RequestToken.Equals(other.RequestToken)));
        }        
        /// <summary>Inserts the specified access token.</summary>
        /// <param name="accessToken">The access token.</param>
        /// <returns>The inserted access token. <c>null</c> if the insertion was unsuccessful.</returns>
        public async Task<IAccessToken> InsertAccessToken(IAccessToken accessToken)
        {
            var token = (AccessToken)accessToken;

            if (this.accessTokens.TryAdd(Guid.NewGuid(), token))
            {
                return accessToken;
            }

            return null;
        }
Esempio n. 60
0
 public override bool Add(IAccessToken token)
 {
     throw new NotSupportedException("Tokens cannot be added to the token store--it is fixed.");
 }