Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 98 additions & 2 deletions src/BookStore.Presentation/MVC/Controllers/AuthController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Microsoft.JSInterop;
using MVC.Models;
using MVC.Models.Auth;
using System.Security.Claims;

namespace MVC.Controllers
{
Expand Down Expand Up @@ -37,9 +38,15 @@ public IActionResult Index()
return View();
}

public async Task<IActionResult> Login()
public async Task<IActionResult> Login(string? ReturnUrl = null)
{
return View();
var model = new LoginDTO
{
ReturnUrl = ReturnUrl,
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
};

return View(model);
}

public async Task<IActionResult> Register()
Expand Down Expand Up @@ -188,6 +195,95 @@ public async Task<IActionResult> Update(User user)
else
throw new Exception("Something went wrong");
}

[HttpPost]
public IActionResult ExternalLogin(string provider, string returnUrl)
{
//This call will generate a URL that directs to the ExternalLoginCallback action method in the Account controller
//with a route parameter of ReturnUrl set to the value of returnUrl.
var redirectUrl = Url.Action(action: "ExternalLoginCallback", controller: "Auth", values: new { ReturnUrl = returnUrl });
// Configure the redirect URL, provider and other properties
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
//This will redirect the user to the external provider's login page
return new ChallengeResult(provider, properties);
}

public async Task<IActionResult> ExternalLoginCallback(string? returnUrl, string? remoteError)
{
returnUrl = returnUrl ?? Url.Content("~/");

LoginDTO loginViewModel = new LoginDTO
{
ReturnUrl = returnUrl,
ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList()
};

if (remoteError != null)
{
ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");

return View("Login", loginViewModel);
}

// Get the login information about the user from the external login provider
var info = await _signInManager.GetExternalLoginInfoAsync();
if (info == null)
{
ModelState.AddModelError(string.Empty, "Error loading external login information.");

return View("Login", loginViewModel);
}

// If the user already has a login (i.e., if there is a record in AspNetUserLogins table)
// then sign-in the user with this external login provider
var signInResult = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider,
info.ProviderKey, isPersistent: false, bypassTwoFactor: true);

if (signInResult.Succeeded)
{
return LocalRedirect(returnUrl);
}

// If there is no record in AspNetUserLogins table, the user may not have a local account
else
{
// Get the email claim value
var email = info.Principal.FindFirstValue(ClaimTypes.Email);

if (email != null)
{
// Create a new user without password if we do not have a user already
var user = await _userManager.FindByEmailAsync(email);

if (user == null)
{
user = new User
{
UserName = info.Principal.FindFirstValue(ClaimTypes.Email),
Email = info.Principal.FindFirstValue(ClaimTypes.Email),
FullName = info.Principal.FindFirstValue(ClaimTypes.GivenName) + info.Principal.FindFirstValue(ClaimTypes.Surname),
};

//This will create a new user into the AspNetUsers table without password
await _userManager.CreateAsync(user);
}

// Add a login (i.e., insert a row for the user in AspNetUserLogins table)
await _userManager.AddLoginAsync(user, info);

//Then Signin the User
await _signInManager.SignInAsync(user, isPersistent: false);

return LocalRedirect(returnUrl);
}

// If we cannot find the user email we cannot continue
ViewBag.ErrorTitle = $"Email claim not received from: {info.LoginProvider}";
ViewBag.ErrorMessage = "Please contact support on info@dotnettutorials.net";

return View("Error");
}
}
}
}

Expand Down
1 change: 1 addition & 0 deletions src/BookStore.Presentation/MVC/MVC.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

<ItemGroup>
<PackageReference Include="MediatR" Version="11.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="8.0.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
Expand Down
7 changes: 6 additions & 1 deletion src/BookStore.Presentation/MVC/Models/Auth/LoginDTO.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
namespace MVC.Models.Auth
using Microsoft.AspNetCore.Authentication;

namespace MVC.Models.Auth
{
public class LoginDTO
{
public string Password { get; set; }
public string Email { get; set; }

public string? ReturnUrl { get; set; }
public IList<AuthenticationScheme>? ExternalLogins { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace MVC.Models.ConfigurationModels
{
public class AuthGoogleConfiguration
{
public string ClientId { get; set; }
public string ClientSecret { get; set; }
}
}
10 changes: 9 additions & 1 deletion src/BookStore.Presentation/MVC/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using BookStore.Domain.Entities.Auth;
using BookStore.Infrastructure;
using MVC.Middlewares;
using MVC.Models.ConfigurationModels;
using Serilog;
using System.Text.Json.Serialization;

Expand All @@ -21,7 +22,14 @@
builder.Services.AddIdentity<User, Role>()
.AddEntityFrameworkStores<AppDBContext>();

builder.Services.AddAuthentication();
var googleAuth = builder.Configuration.GetSection("Auth-Google").Get<AuthGoogleConfiguration>();

builder.Services.AddAuthentication()
.AddGoogle(options =>
{
options.ClientId = googleAuth.ClientId;
options.ClientSecret = googleAuth.ClientSecret;
});

// Logger
var logger = new LoggerConfiguration()
Expand Down
26 changes: 24 additions & 2 deletions src/BookStore.Presentation/MVC/Views/Auth/Login.cshtml
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
@using MVC.Models.Auth
@model LoginDTO

<form class="container-form">
<div class="container-form">
<form>
<div class="mb-3">
<label asp-for="Email" class="form-label">Email address</label>
<input asp-for="Email" type="email" class="form-control" aria-describedby="emailHelp">
Expand All @@ -11,9 +12,30 @@
<input asp-for="Password" type="password" class="form-control">
</div>

<button asp-controller="Auth" asp-action="Login" formmethod="post" type="submit" class="btn btn-primary">Login</button>
<button asp-controller="Auth" style="background-color:aliceblue; width:100%;" asp-action="Login" formmethod="post" type="submit" class="btn">Login</button>
</form>

@if (Model.ExternalLogins?.Count == 0)
{
<div>No external logins configured</div>
}
else
{
<form class="login-google" method="post" asp-action="ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl">
<div>
@foreach (var provider in Model.ExternalLogins)
{
<button type="submit" class="btn"
name="provider" value="@provider.Name"
title="Log in using your @provider.DisplayName account">
<i class='bx bxl-google'></i> Login with @provider.DisplayName
</button>
}
</div>
</form>
}
</div>

<style>
.container-form {
width: 50%;
Expand Down
13 changes: 9 additions & 4 deletions src/BookStore.Presentation/MVC/Views/Auth/Login.cshtml.css
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
form{
width:50%;
margin:auto;
background-color:black;
.container-form {
width: 50%;
margin: auto;
}

.btn{
width: 100%;
background-color:aliceblue;
margin-top: 10px;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@
width: 200px;
height: 200px;
border-radius: 50%;
object-fit: cover;
}
4 changes: 4 additions & 0 deletions src/BookStore.Presentation/MVC/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,9 @@
}
}
]
},
"Auth-Google": {
"ClientId": "733255891197-6kjvhbtu55ioc4uansrsuhh7bn4gi4ig.apps.googleusercontent.com",
"ClientSecret": "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"
}
}