public void OnAuthentication(AuthenticationContext filterContext)
        {
            var mockToken = bool.Parse(ConfigurationManager.AppSettings["MockToken"]);
            var token     = mockToken ? ConfigurationManager.AppSettings["TestToken"] :
                            filterContext.RequestContext.HttpContext.Request.Cookies["x-access-token"]?.Value;

            if (string.IsNullOrWhiteSpace(token))
            {
                return;
            }

            IPrincipal principal;

            try
            {
                principal = Authenticator.CreatePrincipal(token);
            }

            catch (TokenExpiredException)
            {
                var clearCookie = new HttpCookie("x-access-token", "")
                {
                    Expires = DateTime.Now.AddDays(-1)
                };
                filterContext.RequestContext.HttpContext.Response.SetCookie(clearCookie);
                return;
            }

            var idManager = new BSIdentityManager();

            idManager.SetPrincipal(principal);
            filterContext.Principal        = principal;
            filterContext.HttpContext.User = principal;
        }
Exemple #2
0
        public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
            var mockToken      = bool.Parse(ConfigurationManager.AppSettings["MockToken"]);
            var requestCookies = context.Request.Headers.GetCookies("x-access-token").SingleOrDefault();
            var token          = mockToken ? ConfigurationManager.AppSettings["TestToken"] : requestCookies?["x-access-token"].Value;

            if (string.IsNullOrWhiteSpace(token))
            {
                context.ErrorResult = new AuthenticationFailureResult(new
                {
                    Error   = true,
                    Message = "Token is not provided"
                }, context.Request);
                return(Task.FromResult(0));
            }


            try
            {
                IPrincipal principal = Authenticator.CreatePrincipal(token);
                var        idManager = new BSIdentityManager();
                idManager.SetPrincipal(principal);
                context.Principal = principal;
            }

            catch (TokenExpiredException)
            {
                context.ErrorResult = new AuthenticationFailureResult(new
                {
                    Error   = true,
                    Message = "Token is invalid"
                }, context.Request);
                return(Task.FromResult(0));
            }

            return(Task.FromResult(0));
        }