Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在ASP.net Framework和Core 2之间使用身份验证Cookie进行单点登录_C#_Asp.net_Asp.net Core_Cookies_Asp.net Identity - Fatal编程技术网

C# 在ASP.net Framework和Core 2之间使用身份验证Cookie进行单点登录

C# 在ASP.net Framework和Core 2之间使用身份验证Cookie进行单点登录,c#,asp.net,asp.net-core,cookies,asp.net-identity,C#,Asp.net,Asp.net Core,Cookies,Asp.net Identity,我们有一系列通过共享ASP身份验证cookie使用单点登录的应用程序。这些应用程序是在Framework 4.6.1中构建的MVC应用程序。所有应用程序都在同一个域上,因此设置cookie域允许我们实现单点登录 我们正在研究使用.NETCore3添加新应用程序的可能性。我知道有文档可以在框架和核心组件之间设置共享cookie 我已经试着遵循这个指南,但是我看不到新的核心应用程序能够拾取cookie 在此处找到框架Sartup.Auth namespace Authentication {

我们有一系列通过共享ASP身份验证cookie使用单点登录的应用程序。这些应用程序是在Framework 4.6.1中构建的MVC应用程序。所有应用程序都在同一个域上,因此设置cookie域允许我们实现单点登录

我们正在研究使用.NETCore3添加新应用程序的可能性。我知道有文档可以在框架和核心组件之间设置共享cookie

我已经试着遵循这个指南,但是我看不到新的核心应用程序能够拾取cookie

在此处找到框架Sartup.Auth

namespace Authentication
{
    public partial class Startup
    {


    private static void ApplyRedirect(CookieApplyRedirectContext context)
    {
        Uri absoluteUri;
        if (Uri.TryCreate(context.RedirectUri, UriKind.Absolute, out absoluteUri))
        {
            var path = PathString.FromUriComponent(absoluteUri);
            if (path == context.OwinContext.Request.PathBase + context.Options.LoginPath)
            {
                context.RedirectUri = AppLocator.GetAppBaseUrl(AppType.Net) + "/Account/Account/Login" +
                    new QueryString(
                        context.Options.ReturnUrlParameter,
                        context.Request.Uri.AbsoluteUri);
            }
        }

        context.Response.Redirect(context.RedirectUri);
    }

    public void ConfigureAuth(IAppBuilder app)
    {

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            CookieName = ".AspNet.SharedCookie",
            CookieDomain = ConfigurationManager.AppSettings["CookieDomain"],
            AuthenticationType = "Identity.Application",
            LoginPath = new PathString("/Account/Login"),
            LogoutPath = new PathString("/Account/Logout"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User, int>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                    getUserIdCallback: (id) => (id.GetUserId<int>())),
                OnApplyRedirect = ApplyRedirect
            },
            ExpireTimeSpan = TimeSpan.FromMinutes(ApplicationConfiguration.GetCookieSessionTimoutInMinutes()),
            SlidingExpiration = true,

            TicketDataFormat = new AspNetTicketDataFormat(
                                    new DataProtectorShim(
                                        DataProtectionProvider.Create(new DirectoryInfo(@"c:\shared-auth-ticket-keys\"), (builder) => { builder.SetApplicationName("SharedCookieApp"); })
                                        .CreateProtector("Microsoft.AspNetCore.Authentication.Cookies." +
                "CookieAuthenticationMiddleware",
             "Identity.Application",
            "v2")))
        });

}
因此,它似乎在尝试使用正确的方法进行授权,但没有选择应该在应用程序之间共享的cookie。声明未创建标识,用户未显示为已验证

是否有人成功地跨框架和核心2/3应用程序生成了共享cookie。有什么我不知道的地方吗。我想知道这是否是因为我使用的是核心的框架标识,而不是相反的框架标识。但任何帮助或见解都将不胜感激

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace IdentityTest
{
    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.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
        });


        services.AddControllersWithViews();
        services.AddRazorPages();

        services.AddDataProtection()
            .PersistKeysToFileSystem(new DirectoryInfo(@"c:\shared-auth-ticket-keys\"))
            .SetApplicationName("SharedCookieApp");

        services.AddAuthentication("Identity.Application").AddCookie("Identity.Application",options=>
            {
                options.Cookie.Name = ".AspNet.SharedCookie";
                options.Cookie.Domain = "";
                options.Cookie.SameSite = SameSiteMode.None;
                options.Cookie.SecurePolicy = CookieSecurePolicy.None;
                options.DataProtectionProvider = DataProtectionProvider.Create(new DirectoryInfo(@"c:\shared-auth-ticket-keys\")).CreateProtector("Microsoft.AspNetCore.Authentication.Cookies." +
                "CookieAuthenticationMiddleware",
             "Identity.Application",
            "v2");
            });

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

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        var cookiePolicyOptions = new CookiePolicyOptions
        {
            MinimumSameSitePolicy = SameSiteMode.None,
            Secure = CookieSecurePolicy.None
        };

        app.UseCookiePolicy(cookiePolicyOptions);

        app.UseRouting();
        app.UseAuthentication();

        app.UseAuthorization();



        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
        });
    }
}
}
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
  Authorization failed.
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler[12]
 AuthenticationScheme: Identity.Application was challenged.