/// <inheritdoc />
        public async Task <IToken> IsValidAsync(ICredentials creds)
        {
            var domain = ConfigurationManager.AppSettings.Get <string>("Domain", null);

            if (string.IsNullOrWhiteSpace(domain))
            {
                throw new Exception("The 'Domain' appsetting value in the web.config must be populated.");
            }

            var group = ConfigurationManager.AppSettings.Get <string>("DomainGroup", null);

            if (string.IsNullOrWhiteSpace(group))
            {
                throw new Exception("The 'DomainGroup' appsetting value in the web.config must be populated.");
            }

            var userDomain = GetDomain(creds.User) ?? domain;
            var netCreds   = new NetworkCredential(GetUserName(creds.User), creds.Password, userDomain);

            if (ADService.ValidateCredentialsAgainstDomain(netCreds) && ADService.IsUserInGroup(netCreds, domain, group))
            {
                var userClient = ClientsCache.Generic.GetValueOrNew <EntityClientAdminAsync <User, long>, bool>(typeof(User).Name, true);
                var odataUser  = await userClient.GetAsync(creds.User);

                IUser user = odataUser?.Object;
                if (user == null)
                {
                    user = await StoreUser(creds);
                }
                return(await BuildAsync(creds, user, odataUser?.RelatedEntityCollection));
            }
            return(null);
        }
        internal async Task <IUser> StoreUser(ICredentials creds)
        {
            IUser user       = null;
            var   userClient = ClientsCache.Generic.GetValueOrNew <EntityClientAdminAsync <User, long>, bool>(typeof(User).Name, true);
            // Do not store the password.
            var tmpUser = new User {
                Username = creds.User, ExternalAuth = true, Enabled = true, IsHashed = false
            };
            var users = await userClient.PostAsync(new List <User> {
                tmpUser
            });

            if (users?.Count > 0)
            {
                user = users[0].Object;
            }
            return(user);
        }
 /// <inheritdoc />
 public async Task <IToken> BuildAsync(ICredentials creds, IUser user, List <RelatedEntityCollection> relatedEntityCollections)
 {
     return(await TokenGenerator.BuildAsync(creds, user, relatedEntityCollections));
 }