使用StatelessAuthenticationConfiguration时,建议的方法是在失败的身份验证时重定向到登录页面

时间:2017-04-25 10:48:38

标签: c# nancy

我正在使用Nancy.Authentication.Stateless 1.4.1并且需要知道在用户未经授权的情况下,向登录页面发出重定向的推荐方式是什么。

目前,身份验证的工作原理是它向客户端返回401。我希望能够拦截401(服务器端),而是将用户发送到登录页面。

我可以看到这可以通过此处所述的表单身份验证(https://github.com/NancyFx/Nancy/wiki/Forms-authentication

来实现

代码段(用于表单身份验证)

var formsAuthConfiguration =
new FormsAuthenticationConfiguration()
{
    RedirectUrl = "~/login",
    UserMapper = container.Resolve<IUserMapper>(),
};

使用StatelessAuthenticationConfiguration

时,有点难以理解如何执行此操作

1 个答案:

答案 0 :(得分:1)

您可以在After管道的自定义处理程序(请参阅The Application Before After and OnError pipelines)或模块的After hook(请参阅The before and after hooks)中手动实现此操作,该模块将使用重定向响应替换响应,因为它未经授权

要在应用程序级别启用它,您可以使用以下内容:

pipelines.AfterRequest.AddItemToEndOfPipeline(RedirectUnauthorizedRequests);

RedirectUnauthorizedRequests方法看起来像这样:

private static Action<NancyContext> RedirectUnauthorizedRequests()
{
    return context =>
    {
        if (context.Response.StatusCode == HttpStatusCode.Unauthorized)
        {
            context.Response = context.GetRedirect("/login");
        }
    };
}