OWIN身份验证管道以及如何正确使用Katana中间件? [英] The OWIN authentication pipeline, and how to use Katana middleware correctly?

查看:95
本文介绍了OWIN身份验证管道以及如何正确使用Katana中间件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始研究新的ASP.Net Identity框架和Katana中间件,那里有大量的代码和文档,但是我看到似乎有很多相互矛盾的信息,我猜测是代码更新频率增加的结果.

I've recently started looking at the new ASP.Net Identity framework and the Katana middleware, there's a surprising amount of code and documentation out there, but I'm seeing what appears to be a lot of conflicting information, which I guess is a result of the increasing frequency of code updates.

我希望针对内部ADFS 2服务使用WsFederation身份验证,但是OWIN身份验证管道的工作方式让我有些困惑,我希望有人可以提供一些权威信息.

I'm looking to use WsFederation Authentication against an internal ADFS 2 service, but the way the OWIN authentication pipeline works has me a little confused and I'm hoping someone can offer some definitive information.

特别是,我对连接中间件的顺序以及在各种情况下需要哪些模块的顺序很感兴趣,我想摆脱所有不需要的东西,同时确保该过程尽可能安全.

Specifically, I'm interested in the order in which middleware should be hooked up and which modules are required in various scenarios, I'd like to get rid of anything that doesn't need to be there and at the same time ensure that the process is as secure as possible.

例如,似乎应该将UseWsFederationAuthenticationUseCookieAuthentication结合使用,但是我不确定正确的AuthenticationType是什么(

For example, it would appear that UseWsFederationAuthentication should be used in conjunction with UseCookieAuthentication, but I'm not sure what the correct AuthenticationType would be (this post suggests that it's just an identifier string, but is it's value significant?) or even if we still need to use SetDefaultSignInAsAuthenticationType.

我还注意到了Katana项目讨论板上的主题,Tratcher提到了一个常见错误,但对于代码的哪一部分有错误,并不是很具体.

I also noticed this thread on the Katana Project discussions board, where Tratcher mentions a common mistake, but isn't very specific as to which part of the code is in error.

我个人而言,现在使用以下命令(通过自定义SAML令牌处理程序将令牌字符串读取到有效的XML文档中),它对我有用,但是否最佳?

Personally, I'm now using the following (with a custom SAML Token handler to read the token string into a valid XML document), it works for me, but is it optimal?

var appURI = ConfigurationManager.AppSettings["app:URI"];
var fedPassiveTokenEndpoint = ConfigurationManager.AppSettings["wsFederation:PassiveTokenEndpoint"];
var fedIssuerURI = ConfigurationManager.AppSettings["wsFederation:IssuerURI"];
var fedCertificateThumbprint = ConfigurationManager.AppSettings["wsFederation:CertificateThumbprint"];

var audienceRestriction = new AudienceRestriction(AudienceUriMode.Always);

audienceRestriction.AllowedAudienceUris.Add(new Uri(appURI));

var issuerRegistry = new ConfigurationBasedIssuerNameRegistry();

issuerRegistry.AddTrustedIssuer(fedCertificateThumbprint, fedIssuerURI);

app.UseCookieAuthentication(
    new CookieAuthenticationOptions
    {
        AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType // "Federation"
    }
);

app.UseWsFederationAuthentication(
    new WsFederationAuthenticationOptions
    {
        Wtrealm = appURI,
        SignOutWreply = appURI,
        Configuration = new WsFederationConfiguration
        {
            TokenEndpoint = fedPassiveTokenEndpoint
        },
        TokenValidationParameters = new TokenValidationParameters
        {
            AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType
        },
        SecurityTokenHandlers = new SecurityTokenHandlerCollection
        {                        
            new SamlSecurityTokenHandlerEx
            {
                CertificateValidator = X509CertificateValidator.None,
                Configuration = new SecurityTokenHandlerConfiguration
                {
                    AudienceRestriction = audienceRestriction,
                    IssuerNameRegistry = issuerRegistry
                }
            }
        }
    }
);

非常感谢您能为我消除这种困惑.

Many thanks for anything you can offer to help clear up this confusion for me.

推荐答案

正如@Tratcher所说,AuthenticationType参数被Microsoft.Owin.Security用作查找身份验证中间件实例的关键字.

As @Tratcher said, the AuthenticationType parameter is used by Microsoft.Owin.Security as a key to do lookups of authentication middleware instances.

下面的代码将使用以下简单的帮助方法,要求对所有请求进行身份验证.在实践中,您更可能在敏感控制器上使用[Authorize]属性,但是我想要一个不依赖任何框架的示例:

The code below will use the following simple helper method to require that all requests are authenticated. In practice you're more likely to use an [Authorize] attribute on sensitive controllers, but I wanted an example that doesn't rely on any frameworks:

private static void AuthenticateAllRequests(IAppBuilder app, params string[] authenticationTypes)
{
    app.Use((context, continuation) =>
    {
        if (context.Authentication.User != null &&
            context.Authentication.User.Identity != null &&
            context.Authentication.User.Identity.IsAuthenticated)
        {
            return continuation();
        }
        else
        {
            context.Authentication.Challenge(authenticationTypes);
            return Task.Delay(0);
        }
    });
}

context.Authentication.Challenge(authenticationTypes)调用将根据提供的每种身份验证类型发出身份验证质询.我们将只提供一种,即WS-Federation身份验证类型.

The context.Authentication.Challenge(authenticationTypes) call will issue an authentication challenge from each of the provided authentication types. We're just going to provide the one, our WS-Federation authentication type.

因此,首先,这是一个简单地使用WS-Federation的站点的最佳" Owin启动配置示例,如下所示:

So first, here's an example of the "optimal" Owin Startup configuration for a site that's simply using WS-Federation, as you are:

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

    app.UseCookieAuthentication(new CookieAuthenticationOptions());

    app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
    {
        AuthenticationType = "WS-Fed Auth (Primary)",
        Wtrealm = ConfigurationManager.AppSettings["app:URI"],
        MetadataAddress = ConfigurationManager.AppSettings["wsFederation:MetadataEndpoint"]
    });

    AuthenticateAllRequests(app, "WS-Fed Auth (Primary)");

    app.UseWelcomePage();
}

请注意使用"WS-Fed Auth (Primary)" AuthenticationType来唯一标识我们已配置的WS-Federation中间件实例.这意味着,例如,如果有此要求,则可以将"WS-Fed Auth (Secondary)"与单独的WS-Federation服务器一起用作后备.

Note the use of the "WS-Fed Auth (Primary)" AuthenticationType to uniquely identify the WS-Federation middleware instance we've configured. This means that you could, for example, use a "WS-Fed Auth (Secondary)" with a separate WS-Federation server as a fallback, if you had that requirement.

此配置将执行以下操作:

This configuration will do the following:

  1. 首先,告诉Owin安全管道,默认情况下,我们要使用默认CookeAuthentication AthenticationType值对请求进行身份验证. (这只是该CookieAuthenticationDefaults类上的常量字符串,它是CookieAuthenticationOptions.AuthenticationType属性使用的默认值.)
  2. 接下来,使用所有默认选项注册一个cookie身份验证中间件实例,使其对应于我们在步骤1中将其设置为默认值的AuthenticationType密钥.
  3. 接下来,使用我们在Web.config文件中定义的选项和自定义AuthenticationType值注册WS-Federation身份验证中间件实例,以便我们以后可以引用它.
  4. 完成所有身份验证中间件的注册后,我们告诉管道对所有请求进行身份验证(通过我们的自定义帮助程序方法,该方法调用Microsoft.Owin.Security方法来向未身份验证的请求发出质询)
  5. 最后,如果用户已通过身份验证,请显示欢迎页面!
  1. First, tell the Owin security pipeline that by default we want to authenticate requests with the default CookeAuthentication AthenticationType value. (That's just a constant string on that CookieAuthenticationDefaults class, and it's the default value used by the CookieAuthenticationOptions.AuthenticationType property.)
  2. Next, register a cookie authentication middleware instance with all default options, so it corresponds to the AuthenticationType key that we set as the default in step 1.
  3. Next, register a WS-Federation authentication middleware instance with options that we define in the Web.config file, and with a custom AuthenticationType value so we can refer to it later.
  4. After all the authentication middleware registrations are done, we tell the pipeline to authenticate all requests (via our custom helper method that calls the Microsoft.Owin.Security methods for issuing challenges to any unauthenticated request)
  5. Finally, if the user has been authenticated, show the welcome page!

代码错误

因此,您可以通过以下几种方法来出错.

Wrong Code

So there are a couple ways you can go wrong here.

为了进行实验,我尝试这样做,您会立即看到问题所在:

To experiment, I tried doing this, and you'll see right away what the problem is:

public void Configuration(IAppBuilder app)
{
    var x = app.GetDefaultSignInAsAuthenticationType();

    app.SetDefaultSignInAsAuthenticationType(x);
}

该首次通话将为您提供您在第一条评论中提到的异常:

That first call will give you the exception you mentioned in your first comment:

在IAppBuilder属性中找不到SignInAsAuthenticationType的默认值.如果以错误的顺序添加身份验证中间件或缺少身份验证中间件,则可能会发生这种情况."

"A default value for SignInAsAuthenticationType was not found in IAppBuilder Properties. This can happen if your authentication middleware are added in the wrong order, or if one is missing."

对-因为默认情况下,Microsoft.Owin.Security管道不假定您要使用的中间件(即,甚至不知道Microsoft.Owin.Security.Cookies),所以它不知道什么应该是默认值.

Right - because by default the Microsoft.Owin.Security pipeline doesn't assume anything about the middleware you're going to use (i.e., Microsoft.Owin.Security.Cookies isn't even known to be present), so it doesn't know what should be the default.

今天这花了我很多时间,因为我真的不知道自己在做什么:

This cost me a lot of time today because I didn't really know what I was doing:

public void Configuration(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType("WS-Fed AAD Auth");

    // ... remainder of configuration
}

因此,这将继续尝试在每次调用时使用WS-Federation 对调用方进行身份验证.并不是说这很昂贵,而是WS-Federation中间件实际上会发出问题每个请求都是一个挑战.因此,您永远无法进入,并且看到大量登录URL飞过您. :P

So, that's going to keep trying to authenticate the caller with WS-Federation on every call. It's not that that's super-expensive, it's that the WS-Federation middleware will actually issue a challenge on every request. So you can't ever get in, and you see a whole lot of login URLs fly past you. :P

因此,在管道中具有所有这些灵活性的最大好处是,您可以做一些非常酷的事情.例如,我有一个域,其中包含两个不同的Web应用程序,并在不同的子路径下运行,例如:example.com/fooexample.com/bar.您可以使用Owin的映射功能(如app.Map(...)中所示)为每个应用程序设置完全不同的身份验证管道.就我而言,一个正在使用WS联合身份验证,而另一个正在使用客户端证书.试图在整体式System.Web框架中做到这一点将是可怕的. :P

So what's great about having all this flexibility in the pipeline is that you can do some really cool things. For instance, I have a domain with two different web apps inside of it, running under different subpaths like: example.com/foo and example.com/bar. You can use Owin's mapping functionality (as in app.Map(...)) to set up a totally different authentication pipeline for each of those apps. In my case, one is using WS-Federation, while the other is using client certificates. Trying to do that in the monolithic System.Web framework would be horrible. :P

这篇关于OWIN身份验证管道以及如何正确使用Katana中间件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆