• Digital accessories
  • Server
  • Digital life
  • Privacy policy
  • Contact us
  1. Home
  2. Server
  3. c# - Google Authentication in Server-Side Blazor not working ...

c# - Google Authentication in Server-Side Blazor not working ...

Rsdaa 16/01/2022 1024

I'm trying to add Google Authentication on my Blazor server app, and can't get it to work on my localhost. When I click the Login button, it brings me to the Google account chooser, where I pick an account to use for logging in. After I pick an account, it goes back to my localhost Login page where the OnGetCallbackAsync shows that GoogleUser.IsAuthenticated is false.

Below is the 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=398940public void ConfigureServices(IServiceCollection services){services.AddDbContext(options =>options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));//options.UseSqlite("DataSource=app.db"));services.AddDefaultIdentity(options => options.SignIn.RequireConfirmedAccount = false).AddEntityFrameworkStores();services.AddRazorPages();services.AddServerSideBlazor();services.AddScoped>();services.AddSingleton();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 isservices.AddHttpContextAccessor();services.AddScoped();// Required for HttpClient support in the Blazor Client projectservices.AddHttpClient();services.AddScoped();// Pass settings to other componentsservices.AddSingleton(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");});}}}

And here is the code inside Login.cshtml.cs where the problem is showing.

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 OnGetCallbackAsync(string returnUrl = null, string remoteError = null){// Get the information about the user from the external login providervar 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("/");}}}

In console.developers.google.com, an OAuth 2.0 Client ID has been set-up with the type "Web application", with ClientID and Secret added to the secrets.json file of the project.

The OAuth Client ID has been edited with the following authorized Redirect URIs:

https://localhost:44319/Loginhttps://localhost:44319/signin-google

I can't see what's wrong why it's returning GoogleUser.IsAuthenticated = false after choosing the google user. Any ideas?


PREV: Hosting your own web server at home - The Silicon Underground

NEXT: How to Move a Live WordPress Site to Local Server

Popular Articles

Hot Articles
Back to Top