Facebook login flow

This commit is contained in:
Josh Deck 2024-08-08 13:17:41 -04:00
parent 99a9ebe7ac
commit dd5da99f77
7 changed files with 148 additions and 10 deletions

View File

@ -4,5 +4,8 @@
{ {
public static string GoogleClientId = "656434530552-03u6d8t2lpf1phuq6qkq0getfh9d7di9.apps.googleusercontent.com"; public static string GoogleClientId = "656434530552-03u6d8t2lpf1phuq6qkq0getfh9d7di9.apps.googleusercontent.com";
public static string GoogleClientSecret = "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"; public static string GoogleClientSecret = "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";
public static string FacebookAppId = "791426466201326";
public static string FacebookClientSecret = "13ae28aac6727b898ba712eb78ab0f24";
} }
} }

View File

@ -1,5 +1,7 @@
@inherits LayoutComponentBase @inherits LayoutComponentBase
@inject NavigationManager _navigationManager
<TelerikRootComponent> <TelerikRootComponent>
<!-- Header <!-- Header
============================================= --> ============================================= -->
@ -14,11 +16,14 @@
<div id="logo" class="me-lg-0 ms-lg-auto"> <div id="logo" class="me-lg-0 ms-lg-auto">
@if(Session.Count == 0) @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> <a class="menu-link text-nowrap" style="font-size:medium" href="https://accounts.google.com/o/oauth2/v2/auth?access_type=online&client_id=@GoogleClientId&redirect_uri=@GoogleRedirect&response_type=code&scope=profile email&prompt=consent"><div>Sign in with Google</div></a>
<a class="menu-link text-nowrap" style="font-size:medium" href="https://www.facebook.com/v20.0/dialog/oauth?client_id=@FacebookId&redirect_uri=@FacebookRedirect&scope="><div>Sign in with Facebook</div></a>
} }
else else
{ {
<a class="menu-link text-nowrap" style="font-size:medium"><div>@Greeting</div></a> <a class="menu-link text-nowrap" style="font-size:medium"><div>@Greeting</div></a>
<a class="menu-link text-nowrap" href="#" style="font-size:medium" @onclick="SignOut"><div>Sign Out</div></a>
} }
<a href="demo-car.html"> <a href="demo-car.html">

View File

@ -3,9 +3,11 @@
public partial class MainLayout public partial class MainLayout
{ {
public static string Greeting = "Hello, {}"; public static string Greeting = "Hello, {}";
public string ClientId = CSharp.Credentials.GoogleClientId; public string GoogleClientId = CSharp.Credentials.GoogleClientId;
public string ClientSecret = CSharp.Credentials.GoogleClientSecret; public string GoogleClientSecret = CSharp.Credentials.GoogleClientSecret;
public static string Redirect = "https://localhost:7282/signin-google"; public string FacebookId = CSharp.Credentials.FacebookAppId;
public static string GoogleRedirect = "https://localhost:7282/signin-google";
public static string FacebookRedirect = "https://localhost:7282/signin-facebook";
public static Dictionary<string, string> Session = new Dictionary<string, string>(); public static Dictionary<string, string> Session = new Dictionary<string, string>();
@ -21,5 +23,14 @@
Greeting = "Hello, " + Session["name"]; Greeting = "Hello, " + Session["name"];
Console.Out.WriteLine("Updated greeting"); Console.Out.WriteLine("Updated greeting");
} }
public void SignOut()
{
Session = new Dictionary<string, string>();
_navigationManager.NavigateTo("/");
Console.WriteLine("Signed out");
}
} }
} }

View File

@ -0,0 +1,116 @@
@using System.Net.Http;
@using System.Text.Json;
@using TSC2.Components.Layout;
@page "/signin-facebook"
@inject NavigationManager _navigationManager
@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.FacebookAppId;
dct["redirect_uri"] = TSC2.Components.Layout.MainLayout.FacebookRedirect;
dct["client_secret"] = TSC2.Components.CSharp.Credentials.FacebookClientSecret;
dct["code"] = code;
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.GetAsync(string.Format("https://graph.facebook.com/v20.0/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}", dct["client_id"], dct["redirect_uri"], dct["client_secret"], dct["code"]));
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())
{
var id_json = await client.GetStringAsync("https://graph.facebook.com/me?fields=id&access_token=" + tokenResponse.access_token);
FacebookAuthResponse id_response = JsonSerializer.Deserialize<FacebookAuthResponse>(id_json);
Console.WriteLine("ID: " + id_response.id);
// Configure the request
List<KeyValuePair<string, string>> requestData = new List<KeyValuePair<string, string>>();
requestData.Add(new KeyValuePair<string, string>("access_token", tokenResponse.access_token));
var request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri("https://graph.facebook.com/me?access_token=" + tokenResponse.access_token),
Content = new FormUrlEncodedContent(requestData)
};
// Send the request
var profile_task = await client.SendAsync(request);
profile_json = await profile_task.Content.ReadAsStringAsync();
}
FacebookProfileResponse profileResponse = JsonSerializer.Deserialize<FacebookProfileResponse>(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("name", profileResponse.name);
MainLayout.UpdateGreeting();
Console.WriteLine("Signed in successfully. (FB)");
}
_navigationManager.NavigateTo("/");
}
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 FacebookAuthResponse
{
public string id { get; set; }
}
public class FacebookProfileResponse
{
public string name { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string id { get; set; }
}
}

View File

@ -4,7 +4,8 @@
@page "/signin-google" @page "/signin-google"
<h1>This is Google Page</h1> @inject NavigationManager _navigationManager
@code { @code {
[Parameter][SupplyParameterFromQuery] public string? code { get; set; } [Parameter][SupplyParameterFromQuery] public string? code { get; set; }
@ -23,7 +24,7 @@
dct["client_secret"] = TSC2.Components.CSharp.Credentials.GoogleClientSecret; dct["client_secret"] = TSC2.Components.CSharp.Credentials.GoogleClientSecret;
dct["code"] = code; dct["code"] = code;
dct["grant_type"] = "authorization_code"; dct["grant_type"] = "authorization_code";
dct["redirect_uri"] = TSC2.Components.Layout.MainLayout.Redirect; dct["redirect_uri"] = TSC2.Components.Layout.MainLayout.GoogleRedirect;
try try
{ {
string auth_json = ""; string auth_json = "";
@ -58,6 +59,7 @@
Console.WriteLine("Signed in successfully."); Console.WriteLine("Signed in successfully.");
} }
_navigationManager.NavigateTo("/");
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@ -165,7 +165,7 @@
<div class="slider-inner"> <div class="slider-inner">
<div class="row align-items-stretch flex-md-row-reverse mx-0"> <div class="row align-items-stretch flex-md-row-reverse mx-0">
<div class="col-md-8 col-sm-12 px-0 min-vh-40"> <div class="col-md-8 col-sm-12 px-0 min-vh-40">
<TelerikMap @ref="@MapRef" Zoom="@Zoom" Height="@MapHeight" Center="[40.68, 74.04]" OnMarkerClick="@OnMarkerClick"> <TelerikMap @ref="@MapRef" Zoom="@Zoom" Height="@MapHeight" Center="@Center" OnMarkerClick="@OnMarkerClick">
<MapLayers> <MapLayers>
<MapLayer Type="@MapLayersType.Tile" <MapLayer Type="@MapLayersType.Tile"
Attribution="@Attribution" Attribution="@Attribution"

View File

@ -32,13 +32,14 @@ namespace TSC2.Components.Pages
MapRef?.Refresh(); MapRef?.Refresh();
Console.WriteLine("Initial refresh"); Console.WriteLine("Initial refresh");
Center = [40.68, 74.04]; Center = [42.4649, -83.3684];
Zoom = 11; Zoom = 11;
Console.WriteLine("Map initialized @ " + Center[0] + " " + Center[1]); Console.WriteLine("Map initialized @ " + Center[0] + " " + Center[1]);
InitializeMapMarkers(Center); InitializeMapMarkers(Center);
MapRef?.Refresh(); MapRef?.Refresh();
Console.WriteLine("IsVisible: " + (MapRef == null ? "false" : "true")); Console.WriteLine("IsVisible: " + (MapRef == null ? "false" : "true"));
} }