IT rekvalifikace s garancí práce. Seniorní programátoři vydělávají až 160 000 Kč/měsíc a rekvalifikace je prvním krokem. Zjisti, jak na to!
Hledáme nové posily do ITnetwork týmu. Podívej se na volné pozice a přidej se do nejagilnější firmy na trhu - Více informací.
Avatar
Adam Gajdečka:20.6.2018 8:59

Jsem ochoten vám i zaplatit za vyřešení, piště případně adam.gajdecka@gmail.com

Ahoj, mám dvě aplikace. Hlavní postavenou na ASP .NET MVC a druhou na ASP .NET CORE 2.0. Potřebuji se přihlašovat do obou aplikací pomocí první aplikace a vytvořit tak SSO.

Mi se to podařilo na localhostu podle návodu https://docs.microsoft.com/…okie-sharing?…

Na localhostu se to spouští pomocí IIS Express. Funguje to, ale na serveru IIS to nefunguje. Práva ke složce keyring mají obě aplikace, klíče se tam ukládají. Do aplikace na Core se tam uživatel nepřihlásí

První aplikace 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;
        }
    }

Druhá aplikace
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?}");
        });
    }
}

Zkusil jsem: Na obou webech mám HTTPS, zkoušel jsem to i zprovoznit mezi http a nejde.
Na localhostu to nefunguje mezi https a http verzí webu, což mi nevadí, ale proč to nejde nevím.

Chci docílit: Chci se přihlásit přes jednotné přihlášení a následně budu přesměrován do druhé aplikace (core 2.0).

Editováno 20.6.2018 9:00
 
Odpovědět
20.6.2018 8:59
Avatar
Adam Gajdečka:20.6.2018 9:01

Běží mi to na Windows Server 2016

 
Nahoru Odpovědět
20.6.2018 9:01
Děláme co je v našich silách, aby byly zdejší diskuze co nejkvalitnější. Proto do nich také mohou přispívat pouze registrovaní členové. Pro zapojení do diskuze se přihlas. Pokud ještě nemáš účet, zaregistruj se, je to zdarma.

Zobrazeno 2 zpráv z 2.