【发布时间】:2018-07-09 22:16:29
【问题描述】:
我有一个带有 EF Identity DB 的 Identity Server 4 解决方案。我可以使用我的电子邮件和外部 gmail 帐户登录,但是当我尝试使用 OpenID(用户名和密码)登录时,我收到以下错误。问题可能与存储在 Identity DB 表中的信息有关。我是 Identity Server 的新手,这是我第一次尝试使用 EF Identity DB。如果有助于解决问题,我可以发布数据库信息。
源码:https://github.com/gotnetdude/GotNetDude-PublicRepository/tree/master/AuthServer
身份服务器日志文件: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。我决定与其对用户 ID 使用另一个 OpenId 进行挑战,不如更新帐户控制器登录管理器 passwordsigninasync 方法:
//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; }
}
最后,我删除了授权启动类的 OpenID Connect 挑战。
进行上述更改后,我可以使用 EF Identity DB 用户名而不是使用 OpenID 的电子邮件登录。就我的目的而言,这是一个足够好的解决方案。我感谢所有的贡献,请随时给我留下任何 cmets。保罗
【问题讨论】:
-
您的示例代码中的那些是真正的键吗?
-
@ti7 你是说谷歌客户端?它来自一个样本:github.com/IdentityServer/IdentityServer4.Samples/blob/release/…
-
不,OpenId 连接挑战...这篇文章证明了授权服务器中的可选挑战是正确的。问题似乎与 AccountService 类 BuildLoginViewModelAsync 方法中注释掉的代码有关。见上面我的cmets。此代码也是示例代码,但已被注释掉。我正在尝试让用户登录 openid 工作。目标是将ldap用户id信息导入权限服务器进行单点登录。
标签: asp.net-mvc asp.net-identity identityserver4 claims-based-identity