在旧的.Net Web窗体(aspx)站点中使用ASP.Net Core 2.2 Auth Cookies进行SSO [英] Using ASP.Net Core 2.2 Auth Cookies in old .Net Web Forms (aspx) site for SSO

查看:62
本文介绍了在旧的.Net Web窗体(aspx)站点中使用ASP.Net Core 2.2 Auth Cookies进行SSO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TLDR:如何获得旧版Web窗体应用程序可以理解的Asp.Net Core 2.2加密身份验证cookie?

TLDR: How can I get an Asp.Net Core 2.2 encrypted auth cookie understood by a legacy Web Forms app?

DR:

我发现自己处在一种情况下,我试图让一个旧的Web窗体(aspx)网站使用新的闪亮的.NET Core 2.2 MVC网站在浏览器中设置的身份验证cookie.有问题的Web窗体应用程序是用 Visual Basic 编写的,而.Net Core应用程序是用 C#编写的.一切都由IIS/IIS Express(来自Visual Studio)托管.

I find myself in a situation where I'm trying to get a legacy Web forms (aspx) site to use an auth cookie set in the browser by a new and shiny .NET Core 2.2 MVC site. The Web Forms app in question is written in Visual Basic, the .Net Core app in C#. Everything is hosted by IIS/IIS Express (from Visual Studio).

该cookie似乎设置得很好,并且为了使事情变得容易(目前),所有事物都托管在同一台计算机上(我的Windows 10专业版Dell XPS).Cookie加密的加密/机器密钥位于磁盘上定义明确的位置..Net Core应用程序(现在我们称其为"Auth Portal")基本上是AWS Cognito的前端.

The cookie appears to be set fine, and to make things easy (for now), all things are hosted on the same machine (My Windows 10 Professional Edition Dell XPS). The encryption/machine key for cookie encryption is in a well defined location on disk. The .Net Core app (Let's call it "Auth Portal" for now) is basically a front for AWS Cognito.

在Auth Portal中,该cookie的配置与 Startup.cs 中的相同:

In Auth Portal, the cookie is configured like so in Startup.cs:

services.Configure<CookiePolicyOptions>(options =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        var keyDir = Configuration["AuthSettings:CookieEncryptionKeyDir"];
        services.AddDataProtection()
            .PersistKeysToFileSystem(new DirectoryInfo(keyDir))
            .SetApplicationName(Configuration["ApplicationName"]);

        services.AddCognitoIdentity();
        services.AddSingleton(typeof(IAmazonCognitoIdentityProvider),
            _ => new AmazonCognitoIdentityProviderClient(RegionEndpoint.APSoutheast2)); // Oh no you know I'm using Sydney!

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie();

        services
            .ConfigureApplicationCookie(options =>
            {
                var parseSucceeded = int.TryParse(Configuration["AuthSettings:CookieExpiryHours"],
                    out var cookieExpiry);
                if (!parseSucceeded) _log.LogError("Failed to parse from configuration auth cookie expiry value");

                parseSucceeded = bool.TryParse(Configuration["AuthSettings:SSLCookieOnly"], out var secureCookieOnly);
                var securePolicy = secureCookieOnly ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest;
                if (!parseSucceeded) _log.LogError("Failed to parse from configuration cookie security policy");

                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan = TimeSpan.FromHours(cookieExpiry);
                options.SlidingExpiration = true;
                options.LoginPath = Configuration["AuthSettings:LoginUrl"];
                options.LogoutPath = Configuration["AuthSettings:LogoutUrl"];
                options.Cookie.Domain = Configuration["AuthSettings:TrustedDomains"];
                options.Cookie.Name = Configuration["AuthSettings:CookieName"];
                options.Cookie.SecurePolicy = securePolicy;
            });

        services
            .Configure<SecurityStampValidatorOptions>(o =>
            {
                o.ValidationInterval = TimeSpan.FromHours(1);
            });

        services.Configure<ForwardedHeadersOptions>(options =>
        {
            options.ForwardLimit = 2;
            options.ForwardedForHeaderName = "X-Forwarded-For-Auth-Portal";
        });

在Web窗体应用程序中,我将替换现有的默认sql身份验证.这是在线资源似乎枯竭的地方.我可以创建一个容易完成的自定义成员资格提供程序.但这并不能(可以理解)开箱即用地理解现有的cookie,即使我在auth设置表单中设置cookie名称也是如此

In the Web Forms app, I'm replacing the existing default sql auth. This is where the online resources seem to dry up. I can make a custom membership provider which I have done easily. But it does not (understandably) understand the existing cookie out of the box, even when I set the cookie name in the forms auth settings

<authentication mode="Forms">
  <forms timeout="60" name="my.sso.cookie" requireSSL="false" path="/"  />
</authentication>
<membership defaultProvider="CognitoMembershipProvider" userIsOnlineTimeWindow="60">
  <providers>
    <clear />
    <add name="CognitoMembershipProvider" type="TheOldWebFormsApp.Authentication.CognitoMembershipProvider" applicationName="MyWebForms" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="true" requiresUniqueEmail="false" passwordFormat="Clear" minRequiredNonalphanumericCharacters="0" minRequiredPasswordLength="3" maxInvalidPasswordAttempts="8" />
  </providers>
</membership>

我发现它会覆盖现有的cookie,我认为这是因为它认为cookie是不存在的cookie.

As I have found it will just overwrite the existing cookie which I'm assuming is because it deems and un-understandable cookie as a non-existent one.

我猜这是一个漫长的询问方法,问我如何才能使这个旧的Web Forms应用程序接受和解密Auth Portal cookie?

I guess this a very long winded way of asking how can i get this old Web Forms app to accept and decrypt the Auth Portal cookie?

干杯〜!

推荐答案

不幸的是,这是不可能的.与ASP.NET相比,ASP.NET Core使用完全不同的方法来加密cookie.后者基于机器密钥",但是ASP.NET Core使用数据保护提供程序和密钥环.两者从根本上是不兼容的,因此,即使您可以共享" cookie(以使每个人都能看到它),一个也将无法解密另一方设置的cookie.

Unfortunately, this is impossible. ASP.NET Core uses an entirely different methodology to encrypt cookies than ASP.NET does. The latter is based on a "machine key", but ASP.NET Core use data protection providers and a key ring. The two are fundamentally incompatible, so even if you can "share" the cookie, such that each one sees it, one will not be able to decrypt the cookie set by the other.

可以与ASP.NET MVC 5成功共享cookie,但这是因为它利用了OWIN,并且数据保护功能与OWIN兼容.这样,即使MVC 5本身也使用机器密钥,也可以使其改为使用数据保护,然后可以与ASP.NET Core站点共享相同的数据保护密钥存储.但是,Web窗体不支持OWIN,因此不能在那里实现相同的功能.简而言之,这完全是不行.

It is possible to successfully share cookies with ASP.NET MVC 5, but that's because it makes use of OWIN, and the data protection stuff is OWIN compatible. As such, even though MVC 5 also uses machine keys natively, it can be made to use data protection instead, and then it can share the same data protection key store with an ASP.NET Core site. However, Web Forms does not support OWIN, so the same cannot be achieved there. In short, this a complete no-go.

也许,另一种方法是依靠集中的身份提供程序,例如Identity Server,Auth0,Azure AD等.使用这种解决方案,由于每个站点都独立地与提供程序授权,因此不必共享cookie.可以使用相同的用户帐户.实际登录发生在身份提供者处,然后向该身份提供者授权的每个站点都从身份提供者获得身份,然后可以设置自己的cookie或任何其他内容.

An alternative, perhaps, is relying on a centralized identity provider, such as Identity Server, Auth0, Azure AD, etc. With such a solution, it's not necessary to share cookies as each site authorizes independently with the provider, but the same user account can be used. The actual login happens at the identity provider, then each site authorized with that identity provider is given the identity from the identity provider and can then set their own cookies or whatever with that.

这篇关于在旧的.Net Web窗体(aspx)站点中使用ASP.Net Core 2.2 Auth Cookies进行SSO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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