Redirect if claim is missing in RequiresAuthentication

时间:2017-04-06 17:21:01

标签: nancy

I'm working on setting up two-factor in my application and I'm trying to make it redirect back to the verification page if the user is logged in but not verified (I'm keeping track of if the user is verified in the sessions table which is added to ClaimsPrincipal 'IsVerified').

The problem i'm having is the example I am using from the documentation doesn't seem to be working properly:

public static class ModuleSecurity
    {
        public static string[] ExcludedPaths = { "/", "/login", "/login/verify", "/admin/settings", "/login/tf/setup" };

        public static void RequiresAuthentication(this NancyModule module)
        {
            module.Before.AddItemToEndOfPipeline(RequiresAuthentication);
        }

        private static Response RequiresAuthentication(NancyContext context)
        {
            // Check if user is authenticated
            if (context.CurrentUser == null)
                return new Response() { StatusCode = HttpStatusCode.Unauthorized };

            if (context.CurrentUser.FindFirst("RequireVerification")?.Value == "True" && context.CurrentUser.FindFirst("IsVerified")?.Value != "True" && !ExcludedPaths.Any(x => x.ToLower() == context.Request.Path.ToLower()))
                return new Response().WithHeader("Location", "/login/verify").WithContentType("text/html").WithStatusCode(HttpStatusCode.SeeOther);

            return null;
        }
    }

Putting break points in I see the "module.Before.AddItemToEndOfPipeline" is executed but it is not executing the other method I have.

1 个答案:

答案 0 :(得分:0)

然后问题是我把它添加到BEFORE管道但是我在调​​用路径后调用this.RequiresClaims(所以我需要AFTER管道)。我可以通过添加扩展和使用module.AddBeforeOrExecute选项来实现此目的。