Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.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# 开放ID连接MVC 5_C#_.net_Asp.net Mvc_Openid Connect - Fatal编程技术网

C# 开放ID连接MVC 5

C# 开放ID连接MVC 5,c#,.net,asp.net-mvc,openid-connect,C#,.net,Asp.net Mvc,Openid Connect,互联网上有很多关于开放ID连接的资料。不幸的是,所有这些材料都属于ASP.NET核心 我想在MVC5上实现开放ID连接 下面是Asp.net内核的代码,它运行良好(我尝试过) 公共类启动 { 公共启动(IConfiguration配置) { 配置=配置; } 公共IConfiguration配置{get;} //此方法由运行时调用。请使用此方法将服务添加到容器中。 public void配置服务(IServiceCollection服务) { 配置(选项=> { //此lambda确定给定请求是

互联网上有很多关于开放ID连接的资料。不幸的是,所有这些材料都属于ASP.NET核心

我想在MVC5上实现开放ID连接

下面是Asp.net内核的代码,它运行良好(我尝试过)

公共类启动
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
配置(选项=>
{
//此lambda确定给定请求是否需要非必要cookie的用户同意。
options.checkApprovered=context=>true;
options.MinimumSameSitePolicy=SameSiteMode.None;
});
//身份服务器配置
services.AddAuthentication(选项=>
{
options.DefaultScheme=CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme=OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie().AddOpenIdConnect(选项=>SetOpenIdConnectOptions(选项));
//终端身份服务器
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
公共无效配置(IApplicationBuilder应用程序,IHostingEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
//默认的HSTS值为30天。您可能希望在生产场景中更改此值,请参阅https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
//身份服务器
app.UseAuthentication();
//独立服务器
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“默认”,
模板:“{controller=Home}/{action=Index}/{id?}”);
});
}
//身份服务器配置
私有void SetOpenIdConnectOptions(OpenIdConnectOptions)
{
options.Authority=“XXX”;
options.ClientId=“XXX”;
options.RequireHttpsMetadata=false;
options.signnscheme=“Cookies”;
options.SaveTokens=true;
options.Scope.Add(“openid”);
选项。范围。添加(“配置文件”);
options.Scope.Add(“默认api”);
options.Scope.Add(“脱机访问”);
options.ClientSecret=“secret”;
options.ResponseType=“代码id\U令牌”;
options.GetClaimsFromUserInfoEndpoint=true;
}
}
所以我希望上面的代码能够在MVC5上运行。我试图用MVC5编写上述代码,但没有成功。似乎我遗漏了什么,因为我无法获取令牌ID或用户声明

下面是MVC5的代码(我试过了,但没有成功)

我无法获取令牌id和用户声明。


公共部分类启动 {

public void ConfigureAuth(IAppBuilder应用程序)
{
//将数据库上下文、用户管理器和登录管理器配置为每个请求使用一个实例
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext(ApplicationUserManager.Create);
app.CreatePerOwinContext(ApplicationSignInManager.Create);
//使应用程序能够使用cookie存储登录用户的信息
//以及使用cookie临时存储用户登录第三方登录提供商的信息
//配置登录cookie
app.UseCookieAuthentication(新的CookieAuthenticationOptions
{
AuthenticationType=“Cookies”,
LoginPath=新路径字符串(“/Account/Login”),
Provider=新CookieAuthenticationProvider
{
//允许应用程序在用户登录时验证安全戳。
//这是一种安全功能,在您更改密码或向帐户添加外部登录时使用。
OnValidateIdentity=SecurityStampValidator.OnValidateIdentity(
validateInterval:TimeSpan.FromMinutes(30),
regenerateIdentity:(管理器,用户)=>user.GenerateUserIdentityAsync(管理器))
}
});
//使用cookie临时存储有关使用第三方登录提供程序登录的用户的信息
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
//app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
//允许应用程序在验证双因素身份验证过程中的第二个因素时临时存储用户信息。
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie,TimeSpan.FromMinutes(5));
//使应用程序能够记住第二个登录验证因素,如电话或电子邮件。
//选中此选项后,登录过程中的第二步验证将在您登录的设备上被记住。
//这类似于登录时的RememberMe选项。
app.useTowFactoryMemberBrowserCookie(DefaultAuthenticationTypes.TwoFactoryRememberBrowserCookie);
app.UseOpenIdConnectAuthentication(
     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;

        }
    }

    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",
        });


    }

}