internal async Task Authenticate(HttpContext context, IOptions <AuthenticationMiddlewareConfig> config, IScSession session, IAuthorisationService authorisationService)
        {
            if (config.Value.IgnoreAuth)
            {
                var userService = context.RequestServices.GetService <IUserService>();
                session.CurrentUser = (await userService.GetAsync()).FirstOrDefault();
                return;
            }

            var ntoken = GetToken(context);

            if (!ntoken.HasValue || ntoken.Value == default(string))
            {
                // Missing token
                return;
            }

            var token = ntoken.Value;

            if (_tokenCache.TryGetValue(token, out UserAuthItem authItem))
            {
                if (DateTime.Now.Subtract(authItem.CacheTime).TotalMinutes > 30)
                {
                    _tokenCache.TryRemove(token, out authItem);
                }
                else
                {
                    session.CurrentUser = authItem.User;
                }
            }
            else
            {
                if (await authorisationService.CanAuthorise(token))
                {
                    var user = await authorisationService.Authorise(token);

                    if (user != null)
                    {
                        authItem = new UserAuthItem {
                            CacheTime = DateTime.Now, User = user
                        };
                        _tokenCache.TryAdd(token, authItem);
                        session.CurrentUser = user;
                    }
                }
            }

            if (session.CurrentUser == null)
            {
                session.InvalidToken = true;
            }
        }