1. Controller:
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.VisualBasic;
using System.Security.Claims;
namespace GoogleAuthWithoutIdentity.Controllers
{
public class AccountController : Controller
{
public IActionResult Login()
{
return View();
}
///
/// Google Login Redirection To Google Login Page
///
///
public IActionResult GoogleLogin()
{
return new ChallengeResult(
GoogleDefaults.AuthenticationScheme,
new AuthenticationProperties
{
RedirectUri = Url.Action("GoogleResponse", "Account") // Where google responds back
});
}
///
/// Google Login Response After Login Operation From Google Page
///
///
public async Task GoogleResponse()
{
//Check authentication response as mentioned on startup file as o.DefaultSignInScheme = "External"
var authenticateResult = await HttpContext.AuthenticateAsync("External");
if (!authenticateResult.Succeeded)
return BadRequest(); // TODO: Handle this better.
//Check if the redirection has been done via google or any other links
if (authenticateResult.Principal.Identities.ToList()[0].AuthenticationType.ToLower() == "google")
{
//check if principal value exists or not
if (authenticateResult.Principal != null)
{
//get google account id for any operation to be carried out on the basis of the id
var googleAccountId = authenticateResult.Principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
//claim value initialization as mentioned on the startup file with o.DefaultScheme = "Application"
var claimsIdentity = new ClaimsIdentity("Application");
if (authenticateResult.Principal != null)
{
//Now add the values on claim and redirect to the page to be accessed after successful login
var details = authenticateResult.Principal.Claims.ToList();
claimsIdentity.AddClaim(authenticateResult.Principal.FindFirst(ClaimTypes.NameIdentifier));// Full Name Of The User
claimsIdentity.AddClaim(authenticateResult.Principal.FindFirst(ClaimTypes.Email)); // Email Address of The User
await HttpContext.SignInAsync("Application", new ClaimsPrincipal(claimsIdentity));
return RedirectToAction("Index", "Home");
}
}
}
return RedirectToAction("Index", "Home");
}
///
/// Google Login Sign out
///
///
public async Task SignOutFromGoogleLogin()
{ //Check if any cookie value is present
if (HttpContext.Request.Cookies.Count > 0)
{ //Check for the cookie value with the name mentioned for authentication and delete each cookie
var siteCookies = HttpContext.Request.Cookies.Where(c => c.Key.Contains(".AspNetCore.") || c.Key.Contains("Microsoft.Authentication"));
foreach (var cookie in siteCookies)
{
Response.Cookies.Delete(cookie.Key);
}
}
//signout with any cookie present
await HttpContext.SignOutAsync("External");
return RedirectToAction("Index", "Home");
}
}
}
2. Layout page:
@RenderBody()
@await RenderSectionAsync("Scripts", required: false)
3. Program.cs
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.Google;
var builder = WebApplication.CreateBuilder(args);
var configuration = builder.Configuration;
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddAuthentication(o =>
{
o.DefaultScheme = "Application";
o.DefaultSignInScheme = "External";
})
.AddCookie("Application")
.AddCookie("External")
.AddGoogle(googleOptions =>
{
googleOptions.ClientId = configuration["GoogleAuth:ClientId"];
googleOptions.ClientSecret = configuration["GoogleAuth:ClientSecret"];
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/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.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();