Пример #1
0
        public void LoginAndEnrollAccount(string identity   = null,
                                          Endpoint endPoint = null,
                                          IAzureAuthenticatorService authenticator = null)
        {
            try
            {
                _requestedIdentity = identity;
                //set the endpoint
                if (endPoint != null)
                {
                    Endpoint = endPoint;
                }

                CacheToken token = AzureTokenCacheService.GetTokenByUpn(identity)[0];
                if (token != null)
                {
                    var tenantId = token.TenantId;
                    var aadId    = token.UserInfo?.UniqueId;
                    _enrollmentManager.RegisterAccountForMAM(identity, aadId, tenantId);
                    return;
                }
            }
            catch (Exception ex)
            {
                var status = new Status()
                {
                    Error      = ex.Message,
                    DidSucceed = false,
                    StatusCode = StatusCode.InternalError
                };

                _loggingService.LogError(typeof(EnrollmentService), ex, ex.Message);
                EnrollmentRequestStatus(status, _authenticationResult);
            }
        }
Пример #2
0
    public CachePolicy Index(ControllerContext context, IDictionary <string, object> args)
    {
        var token = CacheToken.FromCookies(context.HttpContext) + CacheToken.CreateToken("Index");

        return(null);

        return(new StandardCachePolicy(context.HttpContext, token, this, TimeSpan.FromMinutes(1), true));
    }
Пример #3
0
        public async Task <TItem> GetOrCreateAsync <TItem>(CacheToken token, Func <ICacheEntry, Task <TItem> > factory)
        {
            // Generate unique key
            var key = token.ToString();

            // Validate key
            ValidateKey(key);

            // Guaranteed single callback execution for multi threaded request for the same key.
            object cacheItem = new AsyncLazy <TItem>(async() =>
            {
                var fromCache = GetFromCache <TItem>(key);
                if (fromCache != null)
                {
                    return(fromCache);
                }

                var locker = _lockers.GetOrAdd(key, new SemaphoreSlim(1, 1));
                try
                {
                    await locker.WaitAsync().ConfigureAwait(false);

                    fromCache = GetFromCache <TItem>(key);
                    if (fromCache != null)
                    {
                        return(fromCache);
                    }

                    // No cache entry found, invoke entry & factory delegate
                    var entry = _memoryCache.CreateEntry(key);

                    // Invoke factory delegate
                    var obj = await factory(entry);

                    // Write result to cache
                    await WriteToCache(entry, key, obj);

                    if (_logger.IsEnabled(LogLevel.Information))
                    {
                        var type = obj != null
                            ? ((TItem)obj).GetType()
                            : typeof(TItem);
                        _logger.LogInformation("Added entry to cache of type {0} with key: {1}",
                                               type.Name, key);
                    }

                    return(obj);
                }
                finally
                {
                    locker.Release();
                    _lockers.TryRemove(key, out var _);
                }
            });
            var result = UnwrapAsyncLazy <TItem>(cacheItem);

            return(await result.ConfigureAwait(false));
        }
Пример #4
0
        public CacheToken GetOrCreateToken(Type type, params object[] varyBy)
        {
            var cacheToken = new CacheToken(type, varyBy);

            if (Tokens.ContainsKey(cacheToken))
            {
                return(Tokens.FirstOrDefault(t => t.Key == cacheToken).Key);
            }

            Tokens.TryAdd(cacheToken, type);
            return(cacheToken);
        }
Пример #5
0
        public void CancelTokens(Type type, params object[] varyBy)
        {
            var cancellationToken = new CacheToken(type, varyBy);
            var tokens            = GetTokensForType(type);

            foreach (var token in tokens)
            {
                if (cancellationToken == token)
                {
                    CancelToken(token);
                }
            }
        }
Пример #6
0
        public void CancelToken(CacheToken token)
        {
            if (Tokens.ContainsKey(token))
            {
                Tokens.TryRemove(token, out Type type);
            }

            _cacheDependency.CancelToken(token.ToString());

            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("Invalidated cache entry with key '{0}'",
                                       token.ToString());
            }
        }
        private async Task<bool> SetupHttpClient()
        {
            CacheToken token = null;

            token = await _azureAuthenticatorEndpointService.AcquireTokenSilentAsync(Endpoint);
            if (token == null || string.IsNullOrEmpty(token.Token))
            {
                token = await _azureAuthenticatorEndpointService.AuthenticateEndpoint(Endpoint);
            }
            if (token != null)
            {
                var authValue = new AuthenticationHeaderValue("Bearer", token.Token);
                _httpClient.DefaultRequestHeaders.Authorization = authValue;
                return true;
            }
            return false;
        }
        public void LoginAndEnrollAccount(
            string identity   = null,
            Endpoint endPoint = null,
            IAzureAuthenticatorService authenticator = null)
        {
            try
            {
                if (endPoint != null)
                {
                    Endpoint = endPoint;
                }

                if (Endpoint != null)
                {
                    SetAdalInformation(endPoint);
                }

                CacheToken token = AzureTokenCacheService.GetTokenByUpn(identity).FirstOrDefault();
                if (token != null)
                {
                    InvokeOnMainThread(() =>
                    {
                        //TODO
                        //debugging - bug with getting tokens via register method
                        //working with @Kyle at Microsoft on issue.  Only work around
                        //is to run LoginAndEnroll instead

                        //IntuneMAMEnrollmentManager.Instance.LoginAndEnrollAccount(identity);

                        IntuneMAMEnrollmentManager.Instance.RegisterAndEnrollAccount(identity);
                    });
                }
                else
                {
                    IntuneMAMEnrollmentManager.Instance.LoginAndEnrollAccount(identity);
                }
            }
            catch (Exception ex)
            {
                _loggingService.LogError(typeof(EnrollmentService), ex, ex.Message);
            }
        }
Пример #9
0
        public CacheToken GetOrCreateToken(Type type, params object[] varyBy)
        {
            var cacheToken = new CacheToken(type, varyBy);

            if (Tokens.ContainsKey(cacheToken))
            {
                // Equivalent to .First(t => t.Key == cacheToken).Key
                // LINQ is avoided for performance / allocation reasons
                foreach (var t in Tokens)
                {
                    if (t.Key == cacheToken)
                    {
                        return(t.Key);
                    }
                }
            }

            Tokens.TryAdd(cacheToken, type);
            return(cacheToken);
        }
Пример #10
0
        public async Task <TItem> GetOrCreateAsync <TItem>(CacheToken token, Func <ICacheEntry, Task <TItem> > factory)
        {
            if (token == null)
            {
                throw new ArgumentNullException(nameof(token));
            }

            // Item does not exist in cache
            var key = token.ToString();

            if (!_memoryCache.TryGetValue(key, out var obj))
            {
                // Create ICacheEntry
                var entry = _memoryCache.CreateEntry(key);

                // Invoke our func delegate
                obj = (object) await factory(entry);

                // Set expiration tokens
                entry.ExpirationTokens.Add(_cacheDependency.GetToken(key));

                // Set value
                entry.SetValue(obj);

                // need to manually call dispose instead of having a using
                // statement in case the factory passed in throws, in which case we
                // do not want to add the entry to the cache
                entry.Dispose();

                if (_logger.IsEnabled(LogLevel.Information))
                {
                    var type = obj != null
                        ? ((TItem)obj).GetType()
                        : typeof(TItem);
                    _logger.LogInformation("Added entry to cache of type {0} with key: {1}",
                                           type.Name, key);
                }
            }

            return((TItem)obj);
        }
Пример #11
0
 public MyCachePolicy(HttpContextBase context, CacheToken cacheToken, ICachePolicyProvider provider) : base(context, cacheToken, provider, TimeSpan.FromDays(1), true, "~/StaticCaches", true)
 {
 }
Пример #12
0
    public CachePolicy CreateCachePolicy(ControllerContext context, ActionDescriptor action, IDictionary <string, object> parameters)
    {
        var cacheToken = CacheToken.FromVirtualPath(context.HttpContext) + CacheToken.FromQueryString(context.HttpContext);

        return(new MyCachePolicy(context.HttpContext, cacheToken, this));
    }
 /// <summary>
 /// 创建 CacheToken
 /// </summary>
 /// <param name="typeName">类型名,一般可以取 Action 的名称</param>
 /// <param name="parameters">参数列表,一般可以使用 Action 的参数列表</param>
 /// <returns>针对指定类型和参数的 CacheToken</returns>
 public static CacheToken CreateToken(string typeName, IDictionary <string, object> parameters)
 {
     return(CacheToken.CreateToken(typeName, parameters.Select(pair => pair.Key + ":" + pair.Value).ToArray()));
 }