Skip to content

Commit

Permalink
Google auth flow working
Browse files Browse the repository at this point in the history
  • Loading branch information
fergalmoran committed Jan 6, 2025
1 parent ac993dd commit c8217b0
Show file tree
Hide file tree
Showing 5 changed files with 104 additions and 6 deletions.
70 changes: 70 additions & 0 deletions mixyboos-api/Controllers/AuthController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using MixyBoos.Api.Data.Models;

namespace MixyBoos.Api.Controllers;

[Route("[controller]")]
public class AuthController(
SignInManager<MixyBoosUser> signInManager,
UserManager<MixyBoosUser> userManager,
IConfiguration config)
: ControllerBase {
[HttpGet("google-login")]
public IActionResult GoogleLogin() {
var properties = new AuthenticationProperties {
RedirectUri = $"{config["SiteSettings:ApiUrl"]}/auth/google-callback",
Items = {
{"returnUrl", config["SiteSettings:WebUrl"]}
}
};
return Challenge(properties, GoogleDefaults.AuthenticationScheme);
}

[HttpGet("google-callback")]
[HttpGet("/signin-google")]
public async Task<IActionResult> GoogleCallback() {
var authenticateResult = await HttpContext.AuthenticateAsync(GoogleDefaults.AuthenticationScheme);

if (!authenticateResult.Succeeded)
return Unauthorized();

var claims = authenticateResult.Principal.Claims;
foreach (var claim in claims) {
Console.WriteLine($"Claim Type: {claim.Type}, Claim Value: {claim.Value}");
}

var email = authenticateResult.Principal.FindFirstValue(ClaimTypes.Email);
var imageUrl = authenticateResult.Principal.FindFirstValue("picture") ??
authenticateResult.Principal.FindFirstValue(ClaimTypes.Uri);

var user = await userManager.FindByEmailAsync(email);

if (user == null) {
// Create the user if they don't exist
user = new MixyBoosUser {
UserName = email,
Email = email,
EmailConfirmed = true, // Google has already verified the email
ProfileImage = imageUrl
};
var result = await userManager.CreateAsync(user);
if (!result.Succeeded)
return BadRequest(result.Errors);
}

// Sign in the user with Identity cookie
await signInManager.SignInAsync(user, isPersistent: true);

// Redirect back to the React app
var frontendUrl = config["SiteSettings:WebUrl"];
return Redirect(frontendUrl ?? "/");
}
}
6 changes: 6 additions & 0 deletions mixyboos-api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,11 @@
});
builder.Services.LoadScheduler();

builder.Services.Configure<CookiePolicyOptions>(options => {
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

var app = builder.Build();

using (var scope = app.Services.CreateScope()) {
Expand All @@ -101,6 +106,7 @@
.AllowAnyMethod()
);


app.UseSignalRHubs();
app.UseSerilogRequestLogging();

Expand Down
28 changes: 27 additions & 1 deletion mixyboos-api/Services/Startup/AuthenticationStartup.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.BearerToken;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
Expand All @@ -12,6 +15,29 @@ namespace MixyBoos.Api.Services.Startup;

public static class AuthenticationStartup {
public static IServiceCollection AddMixyboosAuthentication(this IServiceCollection services, IConfiguration config) {
var googleClientId = config["Auth:Google:ClientId"];
var googleClientSecret = config["Auth:Google:ClientSecret"];
if (!string.IsNullOrEmpty(googleClientId) && !string.IsNullOrEmpty(googleClientSecret)) {
services.AddAuthentication(options => {
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie(options => {
options.Cookie.Name = ".MixyBoos.Cookies";
options.Cookie.SameSite = SameSiteMode.None;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
})
.AddGoogle(options => {
options.ClientId = googleClientId;
options.ClientSecret = googleClientSecret;
options.SignInScheme = IdentityConstants.ExternalScheme;
options.CorrelationCookie.SameSite = SameSiteMode.None;
options.CorrelationCookie.SecurePolicy = CookieSecurePolicy.Always;
options.Scope.Add("profile");
options.ClaimActions.MapJsonKey("picture", "picture", "url"); // Map the picture claim
});
}

services.AddAuthorization();
services.ConfigureApplicationCookie(options => {
options.Cookie.Name = config["Auth:CookieName"];
Expand Down
5 changes: 0 additions & 5 deletions mixyboos-api/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,5 @@
"Application": "Sample"
}
},
"Servers": {
"LiveShowServer": "rtmp://localhost:1935",
"AudioStreamServer": "rtmp://localhost:1935",
"ImageServer": "https://mixyboos.dev.fergl.ie:5001"
},
"AllowedHosts": "*"
}
1 change: 1 addition & 0 deletions mixyboos-api/mixyboos-api.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
<PackageReference Include="FlexLabs.EntityFrameworkCore.Upsert" Version="8.1.2" />
<PackageReference Include="Flurl" Version="4.0.0"/>
<PackageReference Include="Mapster" Version="7.4.1-pre01"/>
<PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="9.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.0"/>
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="9.0.0"/>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.0">
Expand Down

0 comments on commit c8217b0

Please sign in to comment.