我正在尝试在我的Blazor服务器应用程序上添加Google身份验证,但是无法使其在我的本地主机上运行。当我单击“登录”按钮时,它带我到Google帐户选择器,在此处选择要用于登录的帐户。选择帐户后,它返回到本地登录页面,在该页面上,OnGetCallbackAsync显示GoogleUser.IsAuthenticated为错误。
下面是Startup.cs
namespace RecruitmentApp
{
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.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
//options.UseSqlite("DataSource=app.db"));
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<IdentityUser>>();
services.AddSingleton<WeatherForecastService>();
services.AddAuthentication().AddGoogle(options =>
{
options.ClientId = Configuration["Authentication:Google:ClientId"];
options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
options.ClaimActions.MapJsonKey("urn:google:profile", "link");
options.ClaimActions.MapJsonKey("urn:google:image", "picture");
});
// From: https://github.com/aspnet/Blazor/issues/1554
// Adds HttpContextAccessor
// Used to determine if a user is logged in
// and what their username is
services.AddHttpContextAccessor();
services.AddScoped<HttpContextAccessor>();
// Required for HttpClient support in the Blazor Client project
services.AddHttpClient();
services.AddScoped<HttpClient>();
// Pass settings to other components
services.AddSingleton<IConfiguration>(Configuration);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/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();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
//app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
这是Login.cshtml.cs中显示问题的代码。
namespace RecruitmentApp.Pages
{
[AllowAnonymous]
public class LoginModel : PageModel
{
public IActionResult OnGetAsync(string returnUrl = null)
{
string provider = "Google";
// Request a redirect to the external login provider.
var authenticationProperties = new AuthenticationProperties
{
RedirectUri = Url.Page("./Login",
pageHandler: "Callback",
values: new { returnUrl }),
};
return new ChallengeResult(provider, authenticationProperties);
}
public async Task<IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null)
{
// Get the information about the user from the external login provider
var GoogleUser = this.User.Identities.FirstOrDefault();
// -----> !!! PROBLEM GoogleUser.IsAuthenticated is returning false!!!!
if (GoogleUser.IsAuthenticated)
{
var authProperties = new AuthenticationProperties
{
IsPersistent = true,
RedirectUri = this.Request.Host.Value
};
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(GoogleUser), authProperties);
}
return LocalRedirect("/");
}
}
}
在console.developers.google.com中,已设置类型为“ Web应用程序”的OAuth 2.0客户端ID,并将ClientID和Secret添加到项目的secrets.json文件中。
已使用以下授权的重定向URI编辑了OAuth客户端ID:
https:// localhost:44319 /登录 https:// localhost:44319 / signin-google
我看不出为什么选择Google用户后会返回GoogleUser.IsAuthenticated = false。有什么想法吗?