pil*_*noy 7 c# google-authentication asp.net-core blazor
我正在尝试在 Blazor 服务器应用程序上添加 Google 身份验证,但无法在我的本地主机上运行。当我单击“登录”按钮时,它会将我带到 Google 帐户选择器,在那里我选择一个用于登录的帐户。选择一个帐户后,它返回到我的 localhost 登录页面,其中 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");
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是 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("/");
}
}
}
Run Code Online (Sandbox Code Playgroud)
在 console.developers.google.com 中,已经设置了类型为“Web 应用程序”的 OAuth 2.0 客户端 ID,并将 ClientID 和 Secret 添加到项目的 secrets.json 文件中。
OAuth 客户端 ID 已使用以下授权重定向 URI 进行编辑:
https://localhost:44319/登录 https://localhost:44319/signin-google
我看不出为什么在选择 google 用户后返回 GoogleUser.IsAuthenticated = false 有什么问题。有任何想法吗?
| 归档时间: |
|
| 查看次数: |
815 次 |
| 最近记录: |