我正在使用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
时,有点难以理解如何执行此操作答案 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");
}
};
}