如何使用NancyFx和IdentityServer3(非API网站)设置基于cookie的身份验证

时间:2015-10-16 15:08:07

标签: authentication owin nancy identityserver3

我们有以下环境:

  • 独立IdentityServer3实例(发出引用令牌,而不是jwt)
  • ASP.NET WebAPI资源服务器
  • 针对IdSvr进行身份验证的.NET客户端应用程序(通过资源所有者流程)

...现在我们要开始添加一个OWIN托管的Web应用程序,该应用程序将使用NancyFx来提供服务器呈现的页面以及几个AngularJS SPA。此Nancy网站不会托管任何API,但可能会使用现有API中的数据。我想在OWIN管道中添加身份验证,以帮助保护我们的Angular应用程序不被发送给无法访问的用户。

这与发送SPA代码相反,让Angular确定用户是否应该看到任何内容。在这种情况下,我们已经公开了javascript代码库,我们希望避免这种情况。

我试图了解如何配置此Nancy站点以使用隐式流对IdentityServer身份验证用户。我之前已经在独立SPA中实现了这种身份验证方案(其中所有身份验证都由AngularJS代码处理,令牌存储在HTML5本地存储中),但我对如何在OWIN管道中正确处理此问题感到有些迷失。

我认为OWIN cookie认证中间件是答案,但这是否意味着以下内容?

  • 我需要将用户重定向到IdentityServer(使用正确的url参数进行隐式流程)?
  • IdentityServer会在成功登录时将用户重定向回我的网站,那么我是否挂钩到OWIN授权管理器以设置相应的cookie?

......或者我认为这一切都错了?

作为参考,我已经阅读了以下帖子,他们非常乐于助人,但我还没有看到OWIN的全局。我接下来将尝试使用UseOpenIdConnectAuthentication中间件,但我将非常感谢此处可能提供的任何指导。

http://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/

https://github.com/IdentityServer/IdentityServer3/issues/487

1 个答案:

答案 0 :(得分:4)

从根本上说,在通过OWIN托管的Nancy应用程序中实现OpenID Connect身份验证与在任何MVC / Katana应用程序中实现它完全没有区别(Thinktecture团队为此方案提供了示例:https://github.com/IdentityServer/IdentityServer3.Samples/tree/master/source/Clients/MVC%20OWIN%20Client

你基本上需要3件事:cookie中间件,OpenID Connect中间件和Nancy中间件:

public class Startup {
    public void Configuration(IAppBuilder app) {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions {
            AuthenticationMode = AuthenticationMode.Active,
            AuthenticationType = CookieAuthenticationDefaults.AuthenticationType
        });

        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions {
            AuthenticationMode = AuthenticationMode.Active,

            // Set the address of your OpenID Connect server:
            Authority = "http://localhost:54541/"

            // Set your client identifier here:
            ClientId = "myClient",

            // Set the redirect_uri and post_logout_redirect_uri
            // corresponding to your application:
            RedirectUri = "http://localhost:56765/oidc",
            PostLogoutRedirectUri = "http://localhost:56765/"
        });

        app.UseNancy(options => options.PerformPassThrough = context => context.Response.StatusCode == HttpStatusCode.NotFound);
    }
}

如果您正在寻找功能演示,可以查看https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/tree/dev/samples/Nancy/Nancy.Client(注意:它不会将IdentityServer3用于OIDC服务器部分,但它不会对客户端应用程序产生任何影响)。

相关问题