简体   繁体   中英

Why does SSO between ASP.NET MVC and ASP.NET Core 2.0 only work on localhost?

I have a problem with SSO between my two web apps. I am using code from this tutorial https://docs.microsoft.com/en-us/aspnet/core/security/cookie-sharing?view=aspnetcore-2.1&tabs=aspnetcore2x

First app based on ASP .NET MVC:

public partial class Startup
    {
        public CronJobs _cronJobs;
        public Startup() { }

        public Startup(CronJobs cronJobs)
        {
            _cronJobs = cronJobs;
        }
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationUserDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);


            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
               // AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
               AuthenticationType = "Identity.Application",
                CookieName = ".AspNet.SharedCookie",
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity =
             SecurityStampValidator
                 .OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                     validateInterval: TimeSpan.FromMinutes(30),
                     regenerateIdentity: (manager, user) =>
                         user.GenerateUserIdentityAsync(manager))
                },
                TicketDataFormat = new AspNetTicketDataFormat(
         new DataProtectorShim(
             DataProtectionProvider.Create(new DirectoryInfo(@"c:\keyring"),
                 (builder) => { builder.SetApplicationName("SharedCookieApp"); })
             .CreateProtector(
                 "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
                 "Identity.Application",
                 "v2"))),
                CookieManager = new ChunkingCookieManager()
            });

            System.Web.Helpers.AntiForgeryConfig.UniqueClaimTypeIdentifier =
                "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name";

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            //

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
             app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);


            var hangfireContainer = new UnityContainer();
            GlobalConfiguration.Configuration.UseActivator(new UnityJobActivator(hangfireContainer));
            GlobalConfiguration.Configuration.UseSqlServerStorage("HangFireDB");


            app.UseHangfireServer();

            //this call placement is important
            var options = new DashboardOptions
            {
                Authorization = new[] { new CustomAuthorizationFilter() }
            };
            app.UseHangfireDashboard("/hangfire", options);
     
        }
    }

    public class CustomAuthorizationFilter : IDashboardAuthorizationFilter
    {

        public bool Authorize(DashboardContext context)
        {
            if (HttpContext.Current.User.IsInRole("admin"))
            {
               
                return true;
            }

            return false;
        }
    }

And my second app (Core 2.0)

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<CatalogDbContext>(options =>
          options.UseSqlServer(Configuration.GetConnectionString("CatalogConnection")));

        services.AddDbContext<UsersDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("UsersConnection")));

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<UsersDbContext>()
            .AddDefaultTokenProviders();

        services.AddDataProtection()
            .PersistKeysToFileSystem(GetKeyRingDirInfo())
            .SetApplicationName("SharedCookieApp");


        services.ConfigureApplicationCookie(options => {
            options.Cookie.Name = ".AspNet.SharedCookie";

        });


        services.AddTransient<UserManagerInfo>();

        services.AddMvc();
    }

    private DirectoryInfo GetKeyRingDirInfo()
    {


        var keyRingDirectoryInfo = new DirectoryInfo("C://keyring");
            if (keyRingDirectoryInfo.Exists)
            {
                return keyRingDirectoryInfo;
            }

        
            throw new Exception($"KeyRing folder could not be located");
        
        
       
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        var options = new RewriteOptions().AddRedirectToHttpsPermanent();

        app.UseRewriter(options);

        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/error");
            app.UseStatusCodePages();
            app.UseStatusCodePagesWithRedirects("/error/{0}");

        }
        app.UseStaticFiles();

        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

It's working on localhost. It is not working on IIS Windows Server 2016. No errors, but it not works.

Both apps have a permission to read and write to folder "keyring".

Please check the following and let me know if anything helped, I am ready to advise you further.

This may be caused by thousands of things. If nothing from the list helps, please provide further info on the configuration of IIS. - The way you deploy both apps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM