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

Sam*_*rie 5 authentication nancy owin 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中间件,但我将非常感谢SO可能提供的任何指导.

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

Kév*_*let 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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