Base class for all provider specific credentials. Provider specific subclasses include add their own specific information, for example access tokens, token secrets, etc.
        /// <summary>
        /// Gets the provider specific identity details for the ServiceUser
        /// </summary>
        /// <typeparam name="T">The provider type</typeparam>
        /// <returns>The provider credentials if found, otherwise null</returns>
        public async Task <T> GetIdentityAsync <T>() where T : ProviderCredentials, new()
        {
            if (this.Identity == null || !this.Identity.IsAuthenticated || string.IsNullOrEmpty(this.MobileAppAuthenticationToken))
            {
                return(null);
            }

            string gatewayUrl = ConfigurationManager.AppSettings["EMA_RuntimeUrl"];

            if (gatewayUrl == null)
            {
                throw new NullReferenceException(RResources.Missing_EmaRuntimeUrl);
            }

            AppServiceHttpClient client = this.CreateAppServiceHttpClient(new Uri(gatewayUrl));

            ProviderCredentials credentials = (ProviderCredentials) new T();
            TokenResult         tokenResult = await client.GetRawTokenAsync(this.MobileAppAuthenticationToken, credentials.Provider);

            if (!IsTokenValid(tokenResult))
            {
                return(null);
            }

            PopulateProviderCredentials(tokenResult, credentials);

            return((T)credentials);
        }
        private static User GetUserEntity(ProviderCredentials creds)
        {
            var userId = creds.UserClaims.Single(x => x.Type == ClaimTypes.NameIdentifier).Value;
            var cacheKey = UserCacheKeyPrefix + userId;

            User user = (User)Cache.Get(cacheKey);

            if (user != null)
            {
                return user;
            }

            lock (UserLoadLock)
            {
                using (var dbContext = new LinquaContext())
                {
                    user = dbContext.Users.SingleOrDefault(x => x.MicrosoftAccountId == userId);

                    const int AttemptsCount = 3;
                    int attempt = 1;

                    while (user == null)
                    {
                        user = new User(Guid.NewGuid(), userId, creds.UserClaims.SingleOrDefault(x => x.Type == ClaimTypes.Email)?.Value);

                        dbContext.Users.Add(user);

                        try
                        {
                            dbContext.SaveChanges();
                        }
                        catch (Exception)
                        {
                            if (attempt > AttemptsCount)
                            {
                                throw;
                            }

                            dbContext.Users.Remove(user);

                            attempt++;
                        }

                        user = dbContext.Users.SingleOrDefault(x => x.MicrosoftAccountId == userId);
                    }
                }
            }

            Cache.Set(cacheKey, user, DateTimeOffset.Now.AddHours(12));

            return user;
        }
 public ProviderCredentialsTests()
 {
     this.credsMock = new Mock<ProviderCredentials>("TestProvider") { CallBase = true };
     this.creds = this.credsMock.Object;
 }
 /// <summary>
 /// Returns the serialized JSON for this credentials object that should
 /// be returned in the claims of Mobile Service JWT tokens.
 /// </summary>
 /// <returns>The claim value</returns>
 internal string ToClaimValue(ProviderCredentials credentials)
 {
     return JsonConvert.SerializeObject(credentials, Formatting.None, this.tokenSerializerSettings);
 }
示例#5
0
 /// <summary>
 /// Returns the serialized JSON for this credentials object that should
 /// be returned in the claims of Mobile Service JWT tokens.
 /// </summary>
 /// <returns>The claim value</returns>
 internal string ToClaimValue(ProviderCredentials credentials)
 {
     return(JsonConvert.SerializeObject(credentials, Formatting.None, this.tokenSerializerSettings));
 }
        internal static void PopulateProviderCredentials(TokenResult tokenResult, ProviderCredentials credentials)
        {
            if (tokenResult.Claims != null)
            {
                credentials.Claims = new Dictionary <string, string>(tokenResult.Claims);
            }

            FacebookCredentials facebookCredentials = credentials as FacebookCredentials;

            if (facebookCredentials != null)
            {
                facebookCredentials.AccessToken = tokenResult.Properties.GetValueOrDefault(TokenResult.Authentication.AccessTokenName);
                facebookCredentials.UserId      = tokenResult.Claims.GetValueOrDefault(ClaimTypes.NameIdentifier);
                return;
            }

            GoogleCredentials googleCredentials = credentials as GoogleCredentials;

            if (googleCredentials != null)
            {
                googleCredentials.AccessToken  = tokenResult.Properties.GetValueOrDefault(TokenResult.Authentication.AccessTokenName);
                googleCredentials.RefreshToken = tokenResult.Properties.GetValueOrDefault(TokenResult.Authentication.RefreshTokenName);
                googleCredentials.UserId       = tokenResult.Claims.GetValueOrDefault(ClaimTypes.NameIdentifier);

                string expiresOn = tokenResult.Properties.GetValueOrDefault("AccessTokenExpiration");
                if (!string.IsNullOrEmpty(expiresOn))
                {
                    googleCredentials.AccessTokenExpiration = DateTimeOffset.Parse(expiresOn, CultureInfo.InvariantCulture);
                }

                return;
            }

            AzureActiveDirectoryCredentials aadCredentials = credentials as AzureActiveDirectoryCredentials;

            if (aadCredentials != null)
            {
                aadCredentials.AccessToken = tokenResult.Properties.GetValueOrDefault(TokenResult.Authentication.AccessTokenName);
                aadCredentials.ObjectId    = tokenResult.Properties.GetValueOrDefault("ObjectId");
                aadCredentials.TenantId    = tokenResult.Properties.GetValueOrDefault("TenantId");
                aadCredentials.UserId      = tokenResult.Claims.GetValueOrDefault(ClaimTypes.NameIdentifier);
                return;
            }

            MicrosoftAccountCredentials microsoftAccountCredentials = credentials as MicrosoftAccountCredentials;

            if (microsoftAccountCredentials != null)
            {
                microsoftAccountCredentials.AccessToken  = tokenResult.Properties.GetValueOrDefault(TokenResult.Authentication.AccessTokenName);
                microsoftAccountCredentials.RefreshToken = tokenResult.Properties.GetValueOrDefault(TokenResult.Authentication.RefreshTokenName);
                microsoftAccountCredentials.UserId       = tokenResult.Claims.GetValueOrDefault(ClaimTypes.NameIdentifier);

                string expiresOn = tokenResult.Properties.GetValueOrDefault("AccessTokenExpiration");
                if (!string.IsNullOrEmpty(expiresOn))
                {
                    microsoftAccountCredentials.AccessTokenExpiration = DateTimeOffset.Parse(expiresOn, CultureInfo.InvariantCulture);
                }

                return;
            }

            TwitterCredentials twitterCredentials = credentials as TwitterCredentials;

            if (twitterCredentials != null)
            {
                twitterCredentials.AccessToken       = tokenResult.Properties.GetValueOrDefault(TokenResult.Authentication.AccessTokenName);
                twitterCredentials.AccessTokenSecret = tokenResult.Properties.GetValueOrDefault("AccessTokenSecret");
                twitterCredentials.UserId            = tokenResult.Claims.GetValueOrDefault(ClaimTypes.NameIdentifier);
                return;
            }
        }