首页 文章

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

提问于
浏览
5

我们有一个以下环境:

  • 独立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?

......或者我在想这一切都错了?

作为参考,我非常有帮助,但我接下来将尝试使用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

1 回答

  • 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(注意:它不会对客户端应用程序产生任何影响) .

相关问题