Updating Blazor Admin (#442)

* Updating Blazor services

* Adding Settings and Refactoring Services

* WIP - Fighting with DI

* Configuring dependencies in both Web Startup and BlazorAdmin Program.cs has them working again.

* Everything works; need to optimize calls to ListBrands

* LocalStorageBrandService decorator working

* Added cache duration of 1 minute

* Refactoring to reduce token storage
Fixed issue with dropdowns binding to int

* Remove token stuff from login; moved to CustomAuthStateProvider

* Migrated CatalogTypes to separate service
Implemented cache decorator

* Ardalis/blazor refactor (#440)

* 1. Migrate CatalogItemServices -> CatalogItemService.
3. Add caching to CatalogItemService.

* change to $"Loading {key} from local storage" ?

* docker settings added. (#441)

* docker settings added.

* InDocker Removed

* InDocker removed from web startup.

* removed unused using

* no reload list if close without save

* startup patch for localhost

* file name fixed

* removed docker from launchSettings.

* Configure logging via appsettings

Co-authored-by: Shady Nagy <info@shadynagy.com>
This commit is contained in:
Steve Smith
2020-07-30 23:50:51 -04:00
committed by GitHub
parent 98fb0ee8ce
commit e9a9dc06d7
77 changed files with 865 additions and 533 deletions

View File

@@ -22,16 +22,12 @@ namespace Microsoft.eShopWeb.Web.Areas.Identity.Pages.Account
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger<LoginModel> _logger;
private readonly IBasketService _basketService;
private readonly AuthService _authService;
private readonly ITokenClaimsService _tokenClaimsService;
public LoginModel(SignInManager<ApplicationUser> signInManager, ILogger<LoginModel> logger, IBasketService basketService, AuthService authService, ITokenClaimsService tokenClaimsService)
public LoginModel(SignInManager<ApplicationUser> signInManager, ILogger<LoginModel> logger, IBasketService basketService)
{
_signInManager = signInManager;
_logger = logger;
_basketService = basketService;
_authService = authService;
_tokenClaimsService = tokenClaimsService;
}
[BindProperty]
@@ -88,8 +84,6 @@ namespace Microsoft.eShopWeb.Web.Areas.Identity.Pages.Account
if (result.Succeeded)
{
var token = await _tokenClaimsService.GetTokenAsync(Input.Email);
CreateAuthCookie(Input.Email, token, Startup.InDocker);
_logger.LogInformation("User logged in.");
await TransferAnonymousBasketToUserAsync(Input.Email);
return LocalRedirect(returnUrl);
@@ -114,15 +108,6 @@ namespace Microsoft.eShopWeb.Web.Areas.Identity.Pages.Account
return Page();
}
private void CreateAuthCookie(string username, string token, bool inDocker)
{
var cookieOptions = new CookieOptions();
cookieOptions.Expires = DateTime.Today.AddYears(10);
Response.Cookies.Append("token", token, cookieOptions);
Response.Cookies.Append("username", username, cookieOptions);
Response.Cookies.Append("inDocker", inDocker.ToString(), cookieOptions);
}
private async Task TransferAnonymousBasketToUserAsync(string userName)
{
if (Request.Cookies.ContainsKey(Constants.BASKET_COOKIENAME))

View File

@@ -1,8 +1,8 @@
<environment include="Development">
<environment include="Development,Docker">
<script src="~/Identity/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/Identity/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</environment>
<environment exclude="Development">
<environment exclude="Development,Docker">
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.17.0/jquery.validate.min.js"
asp-fallback-src="~/Identity/lib/jquery-validation/dist/jquery.validate.min.js"
asp-fallback-test="window.jQuery && window.jQuery.validator"

View File

@@ -4,6 +4,8 @@ using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using BlazorShared.Authorization;
using Microsoft.eShopWeb.ApplicationCore.Interfaces;
using System.Threading.Tasks;
namespace Microsoft.eShopWeb.Web.Controllers
{
@@ -11,13 +13,20 @@ namespace Microsoft.eShopWeb.Web.Controllers
[ApiController]
public class UserController : ControllerBase
{
private readonly ITokenClaimsService _tokenClaimsService;
public UserController(ITokenClaimsService tokenClaimsService)
{
_tokenClaimsService = tokenClaimsService;
}
[HttpGet]
[Authorize]
[AllowAnonymous]
public IActionResult GetCurrentUser() =>
Ok(User.Identity.IsAuthenticated ? CreateUserInfo(User) : UserInfo.Anonymous);
public async Task<IActionResult> GetCurrentUser() =>
Ok(User.Identity.IsAuthenticated ? await CreateUserInfo(User) : UserInfo.Anonymous);
private UserInfo CreateUserInfo(ClaimsPrincipal claimsPrincipal)
private async Task<UserInfo> CreateUserInfo(ClaimsPrincipal claimsPrincipal)
{
if (!claimsPrincipal.Identity.IsAuthenticated)
{
@@ -57,6 +66,9 @@ namespace Microsoft.eShopWeb.Web.Controllers
userInfo.Claims = claims;
}
var token = await _tokenClaimsService.GetTokenAsync(claimsPrincipal.Identity.Name);
userInfo.Token = token;
return userInfo;
}
}

View File

@@ -16,10 +16,10 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>@ViewData["Title"] - Microsoft.eShopOnWeb</title>
<base href="~/" />
<environment include="Development">
<environment include="Development,Docker">
<link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
</environment>
<environment exclude="Development">
<environment exclude="Development,Docker">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
asp-fallback-href="css/bootstrap/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute"

View File

@@ -7,6 +7,7 @@ using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
namespace Microsoft.eShopWeb.Web
{
@@ -42,6 +43,13 @@ namespace Microsoft.eShopWeb.Web
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((builderContext, config) =>
{
var env = builderContext.HostingEnvironment;
config
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();

View File

@@ -25,13 +25,13 @@ using Blazored.LocalStorage;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.eShopWeb.ApplicationCore.Interfaces;
using BlazorShared;
namespace Microsoft.eShopWeb.Web
{
public class Startup
{
private IServiceCollection _services;
public static bool InDocker => Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") == "true";
public Startup(IConfiguration configuration)
{
@@ -49,6 +49,15 @@ namespace Microsoft.eShopWeb.Web
//ConfigureProductionServices(services);
}
public void ConfigureDockerServices(IServiceCollection services)
{
services.AddDataProtection()
.SetApplicationName("eshopwebmvc")
.PersistKeysToFileSystem(new DirectoryInfo(@"./"));
ConfigureDevelopmentServices(services);
}
private void ConfigureInMemoryDatabases(IServiceCollection services)
{
// use in-memory database
@@ -88,12 +97,6 @@ namespace Microsoft.eShopWeb.Web
{
services.AddCookieSettings();
if (InDocker)
{
services.AddDataProtection()
.SetApplicationName("eshopwebmvc")
.PersistKeysToFileSystem(new DirectoryInfo(@"./"));
}
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
@@ -141,15 +144,22 @@ namespace Microsoft.eShopWeb.Web
config.Path = "/allservices";
});
var baseUrlConfig = new BaseUrlConfiguration();
Configuration.Bind(BaseUrlConfiguration.CONFIG_NAME, baseUrlConfig);
services.AddScoped<BaseUrlConfiguration>(sp => baseUrlConfig);
// Blazor Admin Required Services for Prerendering
services.AddScoped<HttpClient>(s => new HttpClient
{
BaseAddress = new Uri(BlazorShared.Authorization.Constants.GetWebUrl(InDocker))
BaseAddress = new Uri(baseUrlConfig.WebBase)
});
// add blazor services
services.AddBlazoredLocalStorage();
services.AddServerSideBlazor();
services.AddScoped<AuthService>();
services.AddScoped<HttpService>();
services.AddBlazorServices();
_services = services; // used to debug registered services

View File

@@ -4,7 +4,7 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - Microsoft.eShopOnWeb</title>
<environment names="Development">
<environment names="Development,Docker">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="~/css/app.css" />
<link rel="stylesheet" href="~/css/app.component.css" />
@@ -49,7 +49,7 @@
</div>
</footer>
</div>
<environment names="Development">
<environment names="Development,Docker">
<script src="~/lib/jquery/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>

View File

@@ -1,4 +1,4 @@
<environment names="Development">
<environment names="Development,Docker">
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</environment>

View File

@@ -1,4 +1,8 @@
{
"baseUrls": {
"apiBase": "https://localhost:5099/api/",
"webBase": "https://localhost:44315/"
},
"Logging": {
"LogLevel": {
"Default": "Debug",

View File

@@ -0,0 +1,17 @@
{
"ConnectionStrings": {
"CatalogConnection": "Server=(localdb)\\mssqllocaldb;Integrated Security=true;Initial Catalog=Microsoft.eShopOnWeb.CatalogDb;",
"IdentityConnection": "Server=(localdb)\\mssqllocaldb;Integrated Security=true;Initial Catalog=Microsoft.eShopOnWeb.Identity;"
},
"baseUrls": {
"apiBase": "http://localhost:5200/api/",
"webBase": "http://host.docker.internal:5106/"
},
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}

View File

@@ -1,4 +1,8 @@
{
"baseUrls": {
"apiBase": "https://localhost:5099/api/",
"webBase": "https://localhost:44315/"
},
"ConnectionStrings": {
"CatalogConnection": "Server=(localdb)\\mssqllocaldb;Integrated Security=true;Initial Catalog=Microsoft.eShopOnWeb.CatalogDb;",
"IdentityConnection": "Server=(localdb)\\mssqllocaldb;Integrated Security=true;Initial Catalog=Microsoft.eShopOnWeb.Identity;"

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB