首页 > 解决方案 > 打开 ID 连接 MVC 5

问题描述

互联网上有很多关于 OPEN ID CONNECT 的资料。不幸的是,所有这些材料都属于 ASP.NET Core。

我想在 MVC 5 上实现 OPEN ID 连接。

下面是运行良好的 Asp.net Core 的代码(我尝试过)。

     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;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            // identity server confoguration
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
             .AddCookie().AddOpenIdConnect(options => SetOpenIdConnectOptions(options));



            //end identity server
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment 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();
            }
            // identity server
            app.UseAuthentication();
            // indetity server
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

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


        // identity server configuration
        private void SetOpenIdConnectOptions(OpenIdConnectOptions options)
        {
           options.Authority = "XXX";

            options.ClientId = "XXX";

            options.RequireHttpsMetadata = false;
            options.SignInScheme = "Cookies";
            options.SaveTokens = true;
            options.Scope.Add("openid");
            options.Scope.Add("profile");
            options.Scope.Add("default-api");
            options.Scope.Add("offline_access");
            options.ClientSecret = "secret";
            options.ResponseType = "code id_token";
            options.GetClaimsFromUserInfoEndpoint = true;

        }
    }

所以我希望上面的代码在 MVC 5 上工作。我试图在 MVC 5 中编写上面的代码,但没有奏效。好像我错过了一些东西,因为我无法获得令牌 ID 或用户声明

下面是 MVC 5 的代码(我试过但没有工作)。

我无法获得令牌 ID 以及用户声明。


公共部分类启动{

    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "Cookies",
            LoginPath = new PathString("/Account/Login"),
            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, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });



        // Use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);


        //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);


        app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            RedirectUri = "XXX",
            Authority = "XXX",
            ClientId = "XXX",
            RequireHttpsMetadata = false,
            SaveTokens = true,
            Scope = "openid profile default-api offline_access",
            ClientSecret = "secret",
            ResponseType = "code id_token",
            UseTokenLifetime = false,
            SignInAsAuthenticationType = "Cookies",
        });


    }

}

提前感谢:)

标签: c#.netasp.net-mvcopenid-connect

解决方案


推荐阅读