【发布时间】:2016-11-02 23:16:32
【问题描述】:
我已经阅读了很多关于使用外部身份验证服务进行基本用户身份验证的指南,但我就是无法让这该死的事情发挥作用。
我从一个具有用户级安全性的“样板”.NET Core 项目开始。我已经创建了我的 Google 和 Facebook Auth 密钥,并包含了必要的库。我这样设置我的用户类:
public class ApplicationUser : IdentityUser<Guid>
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string Nickname { get; set; }
}
我的 Startup.cs 文件如下所示:
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder =
new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", true);
if (env.IsDevelopment())
builder.AddUserSecrets();
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(
options => options.UseNpgsql(Configuration.GetConnectionString("ApplicationDb")));
services.AddIdentity<ApplicationUser, ApplicationRole>(opt =>
{
opt.Password.RequireNonAlphanumeric = false;
opt.Password.RequireUppercase = false;
opt.Password.RequireLowercase = false;
opt.Password.RequireDigit = false;
opt.Password.RequiredLength = 8;
opt.User.RequireUniqueEmail = true;
opt.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_=+~@.";
opt.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
opt.Lockout.MaxFailedAccessAttempts = 5;
opt.SignIn.RequireConfirmedEmail = true;
opt.SignIn.RequireConfirmedPhoneNumber = false;
})
.AddEntityFrameworkStores<ApplicationDbContext, Guid>()
.AddDefaultTokenProviders();
services.AddMvc(options => { options.Filters.Add(new RequireHttpsAttribute()); });
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
// 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.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentity();
//Add external authentication middleware below.To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
var facebookOptions = new FacebookOptions
{
AppId = Configuration["Authentication:Facebook:AppId"],
AppSecret = Configuration["Authentication:Facebook:AppSecret"]
};
app.UseFacebookAuthentication(facebookOptions);
var googleOptions = new GoogleOptions
{
ClientId = Configuration["Authentication:Google:AppId"],
ClientSecret = Configuration["Authentication:Google:AppSecret"]
};
app.UseGoogleAuthentication(googleOptions);
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
}
}
到目前为止,一切都很好。我启动项目,点击“登录”链接,我可以选择用 Google 或 Facebook 登录。我选择了 Google,然后...第一次尝试时,我得到 Google 的批准提示,然后我返回注册页面,在该页面中我创建了带有昵称等的本地帐户。
现在,我可以为我的帐户添加本地密码了。一切都在顺利进行。因此,在删除我的 cookie 后,我注销并尝试使用我的 Google 凭据再次登录。令人惊讶的是,我再次被带到注册页面,但我无法注册,因为我已经注册了。我的本地密码也不起作用。
所以我对此进行了深入研究。在AccountController 中有一个名为ExternalLoginCallback 的方法,似乎所有的魔法都发生了。我的方法是这样的:
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
if (remoteError != null)
{
ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
return View(nameof(Login));
}
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
return RedirectToAction(nameof(Login));
// Sign in the user with this external login provider if the user already has a login.
var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, false);
if (result.Succeeded)
{
_logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
return RedirectToAction(nameof(SendCode), new
{
ReturnUrl = returnUrl
});
if (result.IsLockedOut)
return View("Lockout");
// If the user does not have an account, then ask the user to create an account.
ViewData["ReturnUrl"] = returnUrl;
ViewData["LoginProvider"] = info.LoginProvider;
var email = info.Principal.FindFirstValue(ClaimTypes.Email);
var firstName = info.Principal.FindFirstValue(ClaimTypes.GivenName);
var lastName = info.Principal.FindFirstValue(ClaimTypes.Surname);
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel
{
Email = email,
FirstName = firstName,
LastName = lastName
});
}
我在代码通过_signInManager.GetExternalLoginInfoAsync() 调用时对其进行跟踪,结果是NotAllowed?
NotAllowed 是 4 个可能的结果之一,据我所知,另外 3 个是 Succeeded、RequiresTwoFactor 和 IsLockedOut。其他 3 个值被发送到其他地方,所以我必须假设当不存在本地帐户时需要 NotAllowed...除非存在本地计数。
谁能告诉我这里发生了什么?一旦我与 Google(或 Facebook,那里发生了同样的事情)签约,我就无法重新登录他们,并且几乎没有有用的反馈来确定实际问题是什么。
【问题讨论】:
标签: c# asp.net-core asp.net-identity owin google-authentication