Esempio n. 1
0
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> Add(string model)
        {
            if (!await _antiForgery.IsRequestValidAsync(Request.HttpContext))
            {
                return(new StatusCodeResult(401));
            }

            if (!Request.Cookies.ContainsKey("sid") || !_sessionService.IsValid(Request.Cookies["sid"]))
            {
                return(new StatusCodeResult(401));
            }

            var twit = new TwitModel()
            {
                Text     = model,
                Time     = DateTime.Now,
                Username = _sessionService.GetName(Request.Cookies["sid"])
            };

            using (var db = new AppDbContext()){
                db.Twits.Add(twit);
                db.SaveChanges();
            }
            return(RedirectToAction("Twits", "Public"));
        }
Esempio n. 2
0
        public void Configure(IApplicationBuilder app, IAntiforgery antiforgery, ILoggerFactory loggerFactory)
        {
            app.UseAuthentication();

            app.Use(async(context, next) =>
            {
                var logger = loggerFactory.CreateLogger("ValidRequestMW");

                //Don't validate POST for login
                if (context.Request.Path.Value.Contains("login"))
                {
                    await next();
                    return;
                }

                logger.LogInformation(context.Request.Cookies["XSRF-TOKEN"]);
                logger.LogInformation(context.Request.Headers["x-XSRF-TOKEN"]);

                //On POST requests it will validate the XSRF header
                if (!await antiforgery.IsRequestValidAsync(context))
                {
                    /****************************************************
                     *
                     *
                     * For some reason when the cookie and the header are sent in on the /create POST this validation always fails
                     *
                     *
                     ***************************************************/
                    context.Response.StatusCode = 401;

                    logger.LogError("INVALID XSRF TOKEN");
                    return;
                }
                await next();
            });

            app.UseRouter(r =>
            {
                r.MapGet("", async context => { await context.Response.WriteAsync("hello world"); });

                //This returns a XSRF-TOKEN cookie
                //Client will take this value and add it as a X-XSRF-TOKEN header and POST to /create
                r.MapPost("login", async(context) =>
                {
                    antiforgery.SetCookieTokenAndHeader(context);
                    context.Response.Redirect("/");
                });

                //If XSRF validaiton is correct we should hit this route
                r.MapPost("create", async context =>
                {
                    context.Response.StatusCode = 201;
                    await context.Response.WriteAsync("Created");
                });
            });
        }
Esempio n. 3
0
 public override async Task <ActivityExecutionResult> ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
 {
     if (await _antiforgery.IsRequestValidAsync(_httpContextAccessor.HttpContext))
     {
         return(Outcomes("Done", "Valid"));
     }
     else
     {
         return(Outcomes("Done", "Invalid"));
     }
 }
Esempio n. 4
0
        public async Task Invoke(HttpContext httpContext)
        {
            var validatedRequest = await _antiforgery.IsRequestValidAsync(httpContext);

            if (validatedRequest)
            {
                await _next(httpContext);
            }
            else
            {
                httpContext.Response.StatusCode = 400;
            }
        }
            public void OnResourceExecuting(ResourceExecutingContext context)
            {
                var isJwtClient = _httpContextAccessor.HttpContext.Request.Headers["Authorization"].ToString().StartsWith("Bearer ");

                if (!isJwtClient)// && !_webHostEnvironment.IsFrontDevMode())
                {
                    bool isRequestValid = _antiforgery.IsRequestValidAsync(context.HttpContext).Result;
                    if (!isRequestValid)
                    {
                        throw new AntiforgeryValidationException(string.Empty);
                    }
                    //_antiforgery.ValidateRequestAsync(context.HttpContext); //no idea why this is not throwing an exception when NO token is provided
                }
            }
Esempio n. 6
0
        public async Task Invoke(HttpContext context)
        {
            if (context.Request.Path.Value == "/" || IsLogin(context) || IsLogout(context))
            {
                var tokens = _antiforgery.GetAndStoreTokens(context);
                context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
                                                new CookieOptions()
                {
                    HttpOnly = false, Secure = true
                });
            }
            var valid = await _antiforgery.IsRequestValidAsync(context);

            if (valid)
            {
                await _next.Invoke(context);
            }
        }
        protected bool ParseAntiForgeryHeader(IAntiforgery antiforgery, CrudMessagesDto dto, HttpContext httpContext)
        {
            //foreach(var header in httpContext.Request.Headers)
            //{
            //    System.Diagnostics.Trace.WriteLine(header.ToString());
            //}
            var task = antiforgery.IsRequestValidAsync(httpContext);

            task.Wait();
            var validRequest = task.Result;

            if (!validRequest)
            {
                dto.ErrorMessage = "Broken antiforgery";
                return(false);
            }
            return(true);
        }
Esempio n. 8
0
        public async Task InvokeAsync(
            HttpContext context,
            IAntiforgery antiforgery,
            ILogger <AntiforgeryMiddleware> logger,
            IOptions <AntiforgeryConfiguration> configuration)
        {
            AntiforgeryLogMessages.RequestValidating(logger, context);

            var isRequestValid = await antiforgery.IsRequestValidAsync(context);

            if (!isRequestValid)
            {
                AntiforgeryLogMessages.RequestValidationFailed(logger);
                context.Response.StatusCode  = StatusCodes.Status400BadRequest;
                context.Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Json;
                await context.Response.WriteAsync(
                    JsonConvert.SerializeObject(AntiforgeryValidationError.Default));

                return;
            }
            AntiforgeryLogMessages.RequestValidationSucceeded(logger);

            var tokenSet = antiforgery.GetAndStoreTokens(context);

            var requestTokenCookieKey = configuration.Value.RequestTokenCookieName ?? AntiforgeryDefaults.RequestTokenCookieName;

            context.Response.Cookies.Append(
                key: requestTokenCookieKey,
                value: tokenSet.RequestToken,
                options: new CookieOptions()
            {
                SameSite = SameSiteMode.Strict,
                Secure   = true
            });
            AntiforgeryLogMessages.RequestTokenCookieAttached(logger, requestTokenCookieKey, tokenSet.RequestToken);

            await _next.Invoke(context);
        }
Esempio n. 9
0
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            if (context.Request.Headers["X-REQUEST-CSRF-TOKEN"].FirstOrDefault()?.Equals("true") == true && await antiforgery.IsRequestValidAsync(context))
            {
                var token = antiforgery.GetAndStoreTokens(context);
                context.Response.Headers.Add("X-RESPONSE-CSRF-TOKEN-NAME", token.HeaderName);
                context.Response.Headers.Add("X-RESPONSE-CSRF-TOKEN-VALUE", token.RequestToken);
            }

            await next(context);
        }
Esempio n. 10
0
        public async Task <IActionResult> Invoke(string token)
        {
            if (!_securityTokenService.TryDecryptToken <WorkflowPayload>(token, out var payload))
            {
                _logger.LogWarning("Invalid SAS token provided");
                return(NotFound());
            }

            // Get the workflow type.
            var workflowType = await _workflowTypeStore.GetAsync(payload.WorkflowId);

            if (workflowType == null)
            {
                if (_logger.IsEnabled(LogLevel.Warning))
                {
                    _logger.LogWarning("The provided workflow with ID '{WorkflowTypeId}' could not be found.", payload.WorkflowId);
                }

                return(NotFound());
            }

            if (!workflowType.IsEnabled)
            {
                if (_logger.IsEnabled(LogLevel.Warning))
                {
                    _logger.LogWarning("The provided workflow with ID '{WorkflowTypeId}' is not enabled.", payload.WorkflowId);
                }

                return(NotFound());
            }

            // Get the activity record using the activity ID provided by the token.
            var startActivity = workflowType.Activities.FirstOrDefault(x => x.ActivityId == payload.ActivityId);

            if (startActivity == null)
            {
                if (_logger.IsEnabled(LogLevel.Warning))
                {
                    _logger.LogWarning("The provided activity with ID '{ActivityId}' could not be found.", payload.ActivityId);
                }

                return(NotFound());
            }

            // Instantiate and bind an actual HttpRequestEvent object to check its settings.
            var httpRequestActivity = _activityLibrary.InstantiateActivity <HttpRequestEvent>(startActivity);

            if (httpRequestActivity == null)
            {
                if (_logger.IsEnabled(LogLevel.Warning))
                {
                    _logger.LogWarning("Activity with name '{ActivityName}' could not be found.", startActivity.Name);
                }

                return(NotFound());
            }

            // Check if the HttpRequestEvent is configured to perform antiforgery token validation. If so, perform the validation.
            if (httpRequestActivity.ValidateAntiforgeryToken && (!await _antiforgery.IsRequestValidAsync(HttpContext)))
            {
                _logger.LogWarning("Antiforgery token validation failed.");
                return(BadRequest());
            }

            // If the activity is a start activity, start a new workflow.
            if (startActivity.IsStart)
            {
                // If a singleton, try to acquire a lock per workflow type.
                (var locker, var locked) = await _distributedLock.TryAcquireWorkflowTypeLockAsync(workflowType);

                if (locked)
                {
                    await using var acquiredLock = locker;

                    // Check if this is not a workflow singleton or there's not already an halted instance on any activity.
                    if (!workflowType.IsSingleton || !await _workflowStore.HasHaltedInstanceAsync(workflowType.WorkflowTypeId))
                    {
                        if (_logger.IsEnabled(LogLevel.Debug))
                        {
                            _logger.LogDebug("Invoking new workflow of type '{WorkflowTypeId}' with start activity '{ActivityId}'", workflowType.WorkflowTypeId, startActivity.ActivityId);
                        }

                        await _workflowManager.StartWorkflowAsync(workflowType, startActivity);
                    }
                }
            }
            else
            {
                // Otherwise, we need to resume all halted workflows on this activity.
                var workflows = await _workflowStore.ListAsync(workflowType.WorkflowTypeId, new[] { startActivity.ActivityId });

                if (!workflows.Any())
                {
                    if (_logger.IsEnabled(LogLevel.Warning))
                    {
                        _logger.LogWarning("No workflow found that is blocked on activity '{ActivityId}'", startActivity.ActivityId);
                    }

                    return(NotFound());
                }

                foreach (var workflow in workflows)
                {
                    var blockingActivity = workflow.BlockingActivities.FirstOrDefault(x => x.ActivityId == startActivity.ActivityId);

                    if (blockingActivity != null)
                    {
                        if (_logger.IsEnabled(LogLevel.Debug))
                        {
                            _logger.LogDebug("Resuming workflow with ID '{WorkflowId}' on activity '{ActivityId}'", workflow.WorkflowId, blockingActivity.ActivityId);
                        }

                        // If atomic, try to acquire a lock per workflow instance.
                        (var locker, var locked) = await _distributedLock.TryAcquireWorkflowLockAsync(workflow);

                        if (!locked)
                        {
                            continue;
                        }

                        await using var acquiredLock = locker;

                        // If atomic, check if the workflow still exists.
                        var haltedWorkflow = workflow.IsAtomic ? await _workflowStore.GetAsync(workflow.WorkflowId) : workflow;

                        if (haltedWorkflow == null)
                        {
                            continue;
                        }

                        // And if it is still halted on this activity.
                        blockingActivity = haltedWorkflow.BlockingActivities.FirstOrDefault(x => x.ActivityId == startActivity.ActivityId);
                        if (blockingActivity != null)
                        {
                            await _workflowManager.ResumeWorkflowAsync(haltedWorkflow, blockingActivity);
                        }
                    }
                }
            }

            return(GetWorkflowActionResult());
        }
        public async Task <IActionResult> Invoke(string token)
        {
            if (!_securityTokenService.TryDecryptToken <WorkflowPayload>(token, out var payload))
            {
                _logger.LogWarning("Invalid SAS token provided");
                return(NotFound());
            }

            // Get the workflow type.
            var workflowType = await _workflowTypeStore.GetAsync(payload.WorkflowId);

            if (workflowType == null)
            {
                _logger.LogWarning("The provided workflow type with ID '{WorkflowTypeId}' could not be found.", payload.WorkflowId);
                return(NotFound());
            }

            // Get the activity record using the activity ID provided by the token.
            var startActivity = workflowType.Activities.FirstOrDefault(x => x.ActivityId == payload.ActivityId);

            if (startActivity == null)
            {
                _logger.LogWarning("The provided activity with ID '{ActivityId}' could not be found.", payload.ActivityId);
                return(NotFound());
            }

            // Instantiate and bind an actual HttpRequestEvent object to check its settings.
            var httpRequestActivity = _activityLibrary.InstantiateActivity <HttpRequestEvent>(startActivity);

            if (httpRequestActivity == null)
            {
                _logger.LogWarning("Activity with name '{ActivityName}' could not be found.", startActivity.Name);
                return(NotFound());
            }

            // Check if the HttpRequestEvent is configured to perform antiforgery token validation. If so, perform the validation.
            if (httpRequestActivity.ValidateAntiforgeryToken && (!await _antiforgery.IsRequestValidAsync(HttpContext)))
            {
                _logger.LogWarning("Antiforgery token validation failed.");
                return(BadRequest());
            }

            // If the activity is a start activity, start a new workflow.
            if (startActivity.IsStart)
            {
                _logger.LogDebug("Invoking new workflow of type {WorkflowTypeId} with start activity {ActivityId}", workflowType.WorkflowTypeId, startActivity.ActivityId);
                await _workflowManager.StartWorkflowAsync(workflowType, startActivity);
            }
            else
            {
                // Otherwise, we need to resume a halted workflow.
                var workflow = (await _workflowStore.ListAsync(workflowType.WorkflowTypeId, new[] { startActivity.ActivityId })).FirstOrDefault();

                if (workflow == null)
                {
                    _logger.LogWarning("No workflow found that is blocked on activity {ActivityId}", startActivity.ActivityId);
                    return(NotFound());
                }

                var blockingActivity = workflow.BlockingActivities.FirstOrDefault(x => x.ActivityId == startActivity.ActivityId);

                if (blockingActivity != null)
                {
                    _logger.LogDebug("Resuming workflow with ID {WorkflowId} on activity {ActivityId}", workflow.WorkflowId, blockingActivity.ActivityId);
                    await _workflowManager.ResumeWorkflowAsync(workflow, blockingActivity);
                }
            }

            return(GetWorkflowActionResult());
        }
Esempio n. 12
0
        TryValidateAsync(HttpContext httpContext)
        {
            IAntiforgery antiforgery = GetAntiforgeryService(httpContext);

            return(await antiforgery.IsRequestValidAsync(httpContext));
        }