Google authentication

This commit is contained in:
Josh Deck 2024-08-05 13:13:29 -04:00
parent 4f2a725d12
commit 26f2455373
6 changed files with 149 additions and 2 deletions

View File

@ -0,0 +1,8 @@
namespace TSC2.Components.CSharp
{
public class Credentials
{
public static string GoogleClientId = "656434530552-03u6d8t2lpf1phuq6qkq0getfh9d7di9.apps.googleusercontent.com";
public static string GoogleClientSecret = "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";
}
}

View File

@ -8,14 +8,25 @@
<div class="container-fluid">
<div class="header-row flex-lg-row-reverse">
<!-- Logo
<!-- Logo and sign-in buttons
============================================= -->
<div id="logo" class="me-lg-0 ms-lg-auto">
@if(Session.Count == 0)
{
<a class="menu-link text-nowrap" style="font-size:medium" href="https://accounts.google.com/o/oauth2/v2/auth?access_type=online&client_id=@ClientId&redirect_uri=@Redirect&response_type=code&scope=profile email&prompt=consent"><div>Sign in with Google</div></a>
}
else
{
<a class="menu-link text-nowrap" style="font-size:medium"><div>@Greeting</div></a>
}
<a href="demo-car.html">
<img class="logo-default" srcset="img/logo.jpg, img/logo.jpg@2x.png 2x" src="img/logo.jpg@2x.png" alt="TheShopCritics Logo">
</a>
</div><!-- #logo end -->
<div class="primary-menu-trigger">
<button class="cnvs-hamburger" type="button" title="Open Mobile Menu">
<span class="cnvs-hamburger-box"><span class="cnvs-hamburger-inner"></span></span>
@ -34,7 +45,7 @@
<li class="menu-item"><a class="menu-link" href="demo-car-interiors.html"><div>Interiors</div></a></li>
<li class="menu-item"><a class="menu-link" href="demo-car-faqs.html"><div>FAQs</div></a></li>
<li class="menu-item"><a class="menu-link" href="demo-car-blog.html"><div>Blog</div></a></li>
<li class="menu-item"><a class="menu-link" href="demo-car-contact.html"><div>Contacts</div></a></li>
<li class="menu-item"><a class="menu-link" href="demo-car-contact.html"><div>Contacts</div></a></li>
</ul>
</nav><!-- #primary-menu end -->

View File

@ -0,0 +1,25 @@
namespace TSC2.Components.Layout
{
public partial class MainLayout
{
public static string Greeting = "Hello, {}";
public string ClientId = CSharp.Credentials.GoogleClientId;
public string ClientSecret = CSharp.Credentials.GoogleClientSecret;
public static string Redirect = "https://localhost:7282/signin-google";
public static Dictionary<string, string> Session = new Dictionary<string, string>();
public static void UpdateGreeting()
{
if (Session.Count == 0)
{
return;
}
// This should only execute if the user is signed in AND is the first render
Greeting = "Hello, " + Session["name"];
Console.Out.WriteLine("Updated greeting");
}
}
}

View File

@ -0,0 +1,98 @@
@using System.Net.Http;
@using System.Text.Json;
@using TSC2.Components.Layout;
@page "/signin-google"
<h1>This is Google Page</h1>
@code {
[Parameter][SupplyParameterFromQuery] public string? code { get; set; }
[Parameter][SupplyParameterFromQuery] public string? scope { get; set; }
[Parameter][SupplyParameterFromQuery] public string? authuser { get; set; }
[Parameter][SupplyParameterFromQuery] public string? prompt { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender) // Executes every page load; run inexpensive rendering code here
{
if (!firstRender)
return;
var dct = new Dictionary<string, string>();
dct["client_id"] = TSC2.Components.CSharp.Credentials.GoogleClientId;
dct["client_secret"] = TSC2.Components.CSharp.Credentials.GoogleClientSecret;
dct["code"] = code;
dct["grant_type"] = "authorization_code";
dct["redirect_uri"] = TSC2.Components.Layout.MainLayout.Redirect;
try
{
string auth_json = "";
string profile_json = "";
// Get access token for the auth session
using(var client = new HttpClient())
using(var content = new FormUrlEncodedContent(dct))
{
HttpResponseMessage response = await client.PostAsync("https://oauth2.googleapis.com/token", content);
auth_json = await response.Content.ReadAsStringAsync();
}
OAuthTokenResponse tokenResponse = JsonSerializer.Deserialize<OAuthTokenResponse>(auth_json);
Console.WriteLine("AUTH: " + auth_json);
// Use the access token to access their information; name, email, & token
using (var client = new HttpClient())
{
profile_json = await client.GetStringAsync("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + tokenResponse.access_token);
// I think this is the json response?? who knows!
}
GoogleProfileResponse profileResponse = JsonSerializer.Deserialize<GoogleProfileResponse>(profile_json);
Console.WriteLine("PROFILE: " + profile_json);
if (MainLayout.Session.Count == 0) // Fpr security, only add to the session if nothing exists in the session.
{
MainLayout.Session.Add("id", profileResponse.id);
MainLayout.Session.Add("email", profileResponse.email);
MainLayout.Session.Add("name", profileResponse.name);
MainLayout.UpdateGreeting();
Console.WriteLine("Signed in successfully.");
}
}
catch (Exception ex)
{
// Handler
Console.WriteLine("ERORR" + ex);
}
}
// Data classes to handle the Http responses
public class OAuthTokenResponse
{
public string access_token { get; set; }
public int expires_in { get; set; }
public string refresh_token { get; set; }
public string scope { get; set; }
public string token_type { get; set; }
public string id_token { get; set; }
public string error { get; set; }
public string error_description { get; set; }
public bool IsSuccess => string.IsNullOrEmpty(error);
}
public class GoogleProfileResponse
{
public string id { get; set; }
public string email { get; set; }
public string email_verified { get; set; }
public string family_name { get; set; }
public string given_name { get; set; }
public string name { get; set; }
public string picture { get; set; }
public string profile { get; set; }
}
}

View File

@ -9,6 +9,10 @@ builder.Services.AddTelerikBlazor();
var app = builder.Build();
// Note secrets for login auth
var GoogleClientId = builder.Configuration["Authentication:Google:ClientId"];
var GoogleClientSecret = builder.Configuration["Authentication:Google:ClientSecret"];
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{

View File

@ -3,6 +3,7 @@
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>0a14eb84-bad8-4797-b17f-12714e7c3dc9</UserSecretsId>
</PropertyGroup>
<ItemGroup>