首页 文章

带有EF标识数据库的Identity Server 4 - OpenID Connect失败(1)

提问于
浏览
2

我有一个带有EF Identity DB的Identity Server 4解决方案 . 我可以使用我的电子邮件和外部Gmail帐户登录,但是当我尝试使用OpenID(用户名和密码)登录时,我收到以下错误 . 问题可能与存储在Identity DB表中的信息有关 . 我是Identity Server的新手,这是我第一次尝试使用EF Identity DB . 我可以发布数据库信息,如果它有助于解决问题 .

源代码:https://github.com/gotnetdude/GotNetDude-PublicRepository/tree/master/AuthServer

Identity Server日志文件:https://github.com/gotnetdude/GotNetDude-PublicRepository/blob/master/AuthServer_log.txt

MVC客户端日志:https://github.com/gotnetdude/GotNetDude-PublicRepository/blob/master/MVCClient_log.txt

这是AuthServer启动代码,我将oidc mvc客户端添加为失败的挑战选项(“OpenID Connect”) . 如果我使用电子邮件凭据登录,MVC客户端工作正常 . 我想这与mvc客户端上处理作用域的方式有关 . 任何建议表示赞赏 .

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using AuthServer.Data;
using AuthServer.Models;
using AuthServer.Services;
using System.Reflection;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Extensions.Logging;

namespace AuthServer
{
    public class Startup
    {
        #region "Startup"
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        #endregion

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

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

            // Add application services.
            services.AddTransient<IEmailSender, EmailSender>();

            services.AddMvc();

            string connectionString = Configuration.GetConnectionString("DefaultConnection");
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            // configure identity server with in-memory stores, keys, clients and scopes
            services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddAspNetIdentity<ApplicationUser>()
                // this adds the config data from DB (clients, resources)
                .AddConfigurationStore(options =>
                {
                    options.ConfigureDbContext = builder =>
                        builder.UseSqlServer(connectionString,
                            sql => sql.MigrationsAssembly(migrationsAssembly));
                })
                // this adds the operational data from DB (codes, tokens, consents)
                .AddOperationalStore(options =>
                {
                    options.ConfigureDbContext = builder =>
                        builder.UseSqlServer(connectionString,
                            sql => sql.MigrationsAssembly(migrationsAssembly));

                    // this enables automatic token cleanup. this is optional.
                    options.EnableTokenCleanup = true;
                    options.TokenCleanupInterval = 15; // interval in seconds. 15 seconds useful for debugging
                });

            services.AddAuthentication()
                .AddGoogle("Google", options =>
                {
                    options.ClientId = "434483408261-55tc8n0cs4ff1fe21ea8df2o443v2iuc.apps.googleusercontent.com";
                    options.ClientSecret = "3gcoTrEDPPJ0ukn_aYYT6PWo";
                })
                //.AddOpenIdConnect("oidc", "OpenID Connect", options =>
                //{
                //    //options.Authority = "https://demo.identityserver.io/";
                //    //options.ClientId = "implicit";
                //    //options.SaveTokens = true;
                .AddOpenIdConnect("oidc", "OpenID Connect", options =>
                {
                    options.Authority = "http://localhost:5000";
                    options.RequireHttpsMetadata = false;
                    options.SaveTokens = true;
                    options.ClientId = "mvc";
                    //options.Scope.Add("api1.APIScope");
                    //options.Scope.Add("api1.IdentityScope");
                    //options.Scope.Add("openid");
                    //options.GetClaimsFromUserInfoEndpoint = true;
                    //options.Scope.Add("email");
                    //options.Scope.Add("profile");
                    //options.Scope.Add("offline_access");

                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        NameClaimType = "name",
                        RoleClaimType = "role"
                    };
                });
        }
        #endregion

        #region "Configure"
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            // app.UseAuthentication(); // not needed, since UseIdentityServer adds the authentication middleware
            app.UseIdentityServer();

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

在使用AccountService,BuildLoginViewModelAsync方法一段时间后,我意识到电子邮件登录和用户ID登录都使用OpenId . 我决定用而不是用另一个OpenId来挑战用户ID,我会更新帐户控制器登录管理员密码签名同步方法:

//var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, lockoutOnFailure: false);

我还更新了登录视图:

<div class="form-group">
      @*<label asp-for="Email"></label>
        <input asp-for="User" class="form-control" />
        <span asp-validation-for="Email" class="text-danger"></span>*@
    <label asp-for="Username"></label>
    <input asp-for="Username" class="form-control" />
    <span asp-validation-for="Username" class="text-danger"></span>
    </div>

我还更新了InputViewModel:

public class LoginViewModel
    {
        [Required]
        //[EmailAddress]
        //public string Email { get; set; }
        public string Username { get;  set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [Display(Name = "Remember me?")]
        public bool RememberMe { get; set; }
        //public object Username { get; internal set; }
        public object RememberLogin { get; internal set; }
        public string Email { get; internal set; }
    }

最后,我删除了Authority启动类的OpenID Connect挑战 .

完成上面列出的更改后,我可以使用EF Identity DB用户名登录,而不是使用OpenID登录电子邮件 . 就我的目的而言,这是一个很好的解决方案 . 我感谢所有的贡献随时留下任何评论 . 保罗

1 回答

  • 0

    正如我在上一个问题中告诉你的那样 - 首先将服务和控制器恢复为默认状态 . 然后 - 删除此:

    .AddOpenIdConnect("oidc", "OpenID Connect", options =>
                {
                    options.Authority = "http://localhost:5000";
                    options.RequireHttpsMetadata = false;
                    options.SaveTokens = true;
                    options.ClientId = "mvc";
                    //options.Scope.Add("api1.APIScope");
                    //options.Scope.Add("api1.IdentityScope");
                    //options.Scope.Add("openid");
                    //options.GetClaimsFromUserInfoEndpoint = true;
                    //options.Scope.Add("email");
                    //options.Scope.Add("profile");
                    //options.Scope.Add("offline_access");
    
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        NameClaimType = "name",
                        RoleClaimType = "role"
                    };
                }
    

    从您的IdentityServer配置并调试 AccountService.csAccountController.cs . 您在DataBase配置中拥有允许客户端本地登录的事实并不能确保这一点 . 在代码中,在客户端到达授权 endpoints 之前,还存在这样的逻辑,并且可能存在某些不正常的事情 .

    所以3个步骤 - 恢复原始代码,删除混淆身份服务器的代码,以及 - debug .

相关问题