Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update BFF project and packages #15

Merged
merged 6 commits into from
Jun 10, 2022
Merged
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
8 changes: 4 additions & 4 deletions AspNetCoreRazor/AspNetCoreRazor.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.2" NoWarn="NU1605" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="6.0.2" NoWarn="NU1605" />
<PackageReference Include="Microsoft.Identity.Web" Version="1.22.3" />
<PackageReference Include="Microsoft.Identity.Web.UI" Version="1.22.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.5" NoWarn="NU1605" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="6.0.5" NoWarn="NU1605" />
<PackageReference Include="Microsoft.Identity.Web" Version="1.25.0" />
<PackageReference Include="Microsoft.Identity.Web.UI" Version="1.25.0" />
<PackageReference Include="NetEscapades.AspNetCore.SecurityHeaders" Version="0.16.1" />
<PackageReference Include="NetEscapades.AspNetCore.SecurityHeaders.TagHelpers" Version="0.16.1" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.2" NoWarn="NU1605" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="6.0.2" NoWarn="NU1605" />
<PackageReference Include="Microsoft.Identity.Web" Version="1.22.3" />
<PackageReference Include="Microsoft.Identity.Web.UI" Version="1.22.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.5" NoWarn="NU1605" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="6.0.5" NoWarn="NU1605" />
<PackageReference Include="Microsoft.Identity.Web" Version="1.25.0" />
<PackageReference Include="Microsoft.Identity.Web.UI" Version="1.25.0" />
<PackageReference Include="NetEscapades.AspNetCore.SecurityHeaders" Version="0.16.1" />
<PackageReference Include="NetEscapades.AspNetCore.SecurityHeaders.TagHelpers" Version="0.16.1" />
</ItemGroup>
Expand Down
15 changes: 6 additions & 9 deletions BlazorBffAzureAD/Client/BlazorHosted.Client.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,19 @@

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<NoDefaultLaunchSettingsFile>true</NoDefaultLaunchSettingsFile>
<NoDefaultLaunchSettingsFile>true</NoDefaultLaunchSettingsFile>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="6.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="6.0.2" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="6.0.5" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="6.0.5" PrivateAssets="all" />
<PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Authentication" Version="6.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Authentication" Version="6.0.5" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Shared\BlazorHosted.Shared.csproj" />
</ItemGroup>

<ItemGroup>
<ServiceWorker Include="wwwroot\service-worker.js" PublishedContent="wwwroot\service-worker.published.js" />
</ItemGroup>

</Project>
11 changes: 4 additions & 7 deletions BlazorBffAzureAD/Client/Pages/DirectApi.razor
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
@page "/directapi"
@inject HttpClient Http
@inject IAntiforgeryHttpClientFactory httpClientFactory
@inject IJSRuntime JSRuntime

<h1>Data from Direct API</h1>
Expand Down Expand Up @@ -28,15 +28,12 @@ else
}

@code {
private string[] apiData;
private string[]? apiData;

protected override async Task OnInitializedAsync()
{
var token = await JSRuntime.InvokeAsync<string>("getAntiForgeryToken").ConfigureAwait(false);
var client = await httpClientFactory.CreateClientAsync();

Http.DefaultRequestHeaders.Add("X-XSRF-TOKEN", token);

apiData = await Http.GetFromJsonAsync<string[]>("api/DirectApi").ConfigureAwait(false);
apiData = await client.GetFromJsonAsync<string[]>("api/DirectApi");
}

}
11 changes: 8 additions & 3 deletions BlazorBffAzureAD/Client/Pages/GraphApiCall.razor
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
@page "/graphapicall"
@inject HttpClient Http
@inject IHttpClientFactory httpClientFactory
@inject IJSRuntime JSRuntime

<h1>Data from Graph API</h1>

Expand Down Expand Up @@ -31,7 +32,11 @@ else

protected override async Task OnInitializedAsync()
{
apiData = await Http.GetFromJsonAsync<string[]>("api/GraphApiCalls").ConfigureAwait(false);
}
var token = await JSRuntime.InvokeAsync<string>("getAntiForgeryToken");

var client = httpClientFactory.CreateClient("authorizedClient");
client.DefaultRequestHeaders.Add("X-XSRF-TOKEN", token);

apiData = await client.GetFromJsonAsync<string[]>("api/GraphApiCalls");
}
}
61 changes: 27 additions & 34 deletions BlazorBffAzureAD/Client/Program.cs
Original file line number Diff line number Diff line change
@@ -1,41 +1,34 @@
using BlazorHosted.Client.Services;
using BlazorHosted.Client;
using BlazorHosted.Client.Services;

using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Net.Http;

using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace BlazorHosted.Client;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddOptions();
builder.Services.AddAuthorizationCore();
builder.Services.TryAddSingleton<AuthenticationStateProvider, HostAuthenticationStateProvider>();
builder.Services.TryAddSingleton(sp => (HostAuthenticationStateProvider)sp.GetRequiredService<AuthenticationStateProvider>());
builder.Services.AddTransient<AuthorizedHandler>();

public class Program
builder.RootComponents.Add<App>("#app");

builder.Services.AddHttpClient("default", client =>
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddOptions();
builder.Services.AddAuthorizationCore();
builder.Services.TryAddSingleton<AuthenticationStateProvider, HostAuthenticationStateProvider>();
builder.Services.TryAddSingleton(sp => (HostAuthenticationStateProvider)sp.GetRequiredService<AuthenticationStateProvider>());
builder.Services.AddTransient<AuthorizedHandler>();

builder.RootComponents.Add<App>("#app");

builder.Services.AddHttpClient("default", client =>
{
client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
});

builder.Services.AddHttpClient("authorizedClient", client =>
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}).AddHttpMessageHandler<AuthorizedHandler>();

builder.Services.AddTransient(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("default"));

await builder.Build().RunAsync().ConfigureAwait(false);
}
}
client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
});

builder.Services.AddHttpClient("authorizedClient", client =>
{
client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}).AddHttpMessageHandler<AuthorizedHandler>();

builder.Services.AddTransient(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("default"));
builder.Services.AddTransient<IAntiforgeryHttpClientFactory, AntiforgeryHttpClientFactory>();

await builder.Build().RunAsync();
25 changes: 25 additions & 0 deletions BlazorBffAzureAD/Client/Services/AntiforgeryHttpClientFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Microsoft.JSInterop;

namespace BlazorHosted.Client.Services;

public class AntiforgeryHttpClientFactory : IAntiforgeryHttpClientFactory
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IJSRuntime _jSRuntime;

public AntiforgeryHttpClientFactory(IHttpClientFactory httpClientFactory, IJSRuntime jSRuntime)
{
_httpClientFactory = httpClientFactory;
_jSRuntime = jSRuntime;
}

public async Task<HttpClient> CreateClientAsync(string clientName = "authorizedClient")
{
var token = await _jSRuntime.InvokeAsync<string>("getAntiForgeryToken");

var client = _httpClientFactory.CreateClient(clientName);
client.DefaultRequestHeaders.Add("X-XSRF-TOKEN", token);

return client;
}
}
22 changes: 14 additions & 8 deletions BlazorBffAzureAD/Client/Services/AuthorizedHandler.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace BlazorHosted.Client.Services;

Expand All @@ -19,24 +16,33 @@ protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var authState = await _authenticationStateProvider.GetAuthenticationStateAsync().ConfigureAwait(false);
var authState = await _authenticationStateProvider.GetAuthenticationStateAsync();
HttpResponseMessage responseMessage;
if (!authState.User.Identity.IsAuthenticated)
if (authState.User.Identity!= null && !authState.User.Identity.IsAuthenticated)
{
// if user is not authenticated, immediately set response status to 401 Unauthorized
responseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
else
{
responseMessage = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
responseMessage = await base.SendAsync(request, cancellationToken);
}

if (responseMessage.StatusCode == HttpStatusCode.Unauthorized)
{
var content = await responseMessage.Content.ReadAsStringAsync();

// if server returned 401 Unauthorized, redirect to login page
_authenticationStateProvider.SignIn();
if (content != null && content.Contains("acr")) // CAE
{
_authenticationStateProvider.CaeStepUp(content);
}
else // standard
{
_authenticationStateProvider.SignIn();
}
}

return responseMessage;
}
}
}
28 changes: 16 additions & 12 deletions BlazorBffAzureAD/Client/Services/HostAuthenticationStateProvider.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
using BlazorHosted.Shared.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Security.Claims;
using System.Threading.Tasks;

namespace BlazorHosted.Client.Services;

Expand All @@ -23,7 +19,7 @@ public class HostAuthenticationStateProvider : AuthenticationStateProvider
private readonly ILogger<HostAuthenticationStateProvider> _logger;

private DateTimeOffset _userLastCheck = DateTimeOffset.FromUnixTimeSeconds(0);
private ClaimsPrincipal _cachedUser = new ClaimsPrincipal(new ClaimsIdentity());
private ClaimsPrincipal _cachedUser = new(new ClaimsIdentity());

public HostAuthenticationStateProvider(NavigationManager navigation, HttpClient client, ILogger<HostAuthenticationStateProvider> logger)
{
Expand All @@ -34,17 +30,25 @@ public HostAuthenticationStateProvider(NavigationManager navigation, HttpClient

public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
return new AuthenticationState(await GetUser(useCache: true).ConfigureAwait(false));
return new AuthenticationState(await GetUser(useCache: true));
}

public void SignIn(string customReturnUrl = null)
public void SignIn(string? customReturnUrl = null)
{
var returnUrl = customReturnUrl != null ? _navigation.ToAbsoluteUri(customReturnUrl).ToString() : null;
var encodedReturnUrl = Uri.EscapeDataString(returnUrl ?? _navigation.Uri);
var logInUrl = _navigation.ToAbsoluteUri($"{LogInPath}?returnUrl={encodedReturnUrl}");
_navigation.NavigateTo(logInUrl.ToString(), true);
}

public void CaeStepUp(string claimsChallenge, string? customReturnUrl = null)
{
var returnUrl = customReturnUrl != null ? _navigation.ToAbsoluteUri(customReturnUrl).ToString() : null;
var encodedReturnUrl = Uri.EscapeDataString(returnUrl ?? _navigation.Uri);
var logInUrl = _navigation.ToAbsoluteUri($"{LogInPath}?claimsChallenge={claimsChallenge}&returnUrl={encodedReturnUrl}");
_navigation.NavigateTo(logInUrl.ToString(), true);
}

private async ValueTask<ClaimsPrincipal> GetUser(bool useCache = false)
{
var now = DateTimeOffset.Now;
Expand All @@ -55,20 +59,20 @@ private async ValueTask<ClaimsPrincipal> GetUser(bool useCache = false)
}

_logger.LogDebug("Fetching user");
_cachedUser = await FetchUser().ConfigureAwait(false);
_cachedUser = await FetchUser();
_userLastCheck = now;

return _cachedUser;
}

private async Task<ClaimsPrincipal> FetchUser()
{
UserInfo user = null;
UserInfo? user = null;

try
{
_logger.LogInformation(_client.BaseAddress.ToString());
user = await _client.GetFromJsonAsync<UserInfo>("api/User").ConfigureAwait(false);
_logger.LogInformation("{clientBaseAddress}", _client.BaseAddress?.ToString());
user = await _client.GetFromJsonAsync<UserInfo>("api/User");
}
catch (Exception exc)
{
Expand All @@ -95,4 +99,4 @@ private async Task<ClaimsPrincipal> FetchUser()

return new ClaimsPrincipal(identity);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace BlazorHosted.Client.Services;

public interface IAntiforgeryHttpClientFactory
{
Task<HttpClient> CreateClientAsync(string clientName = "authorizedClient");
}
2 changes: 1 addition & 1 deletion BlazorBffAzureAD/Client/Shared/AntiForgeryTokenInput.razor
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

protected override async Task OnInitializedAsync()
{
token = await JSRuntime.InvokeAsync<string>("getAntiForgeryToken").ConfigureAwait(false);
token = await JSRuntime.InvokeAsync<string>("getAntiForgeryToken");
}

public string GetToken()
Expand Down
2 changes: 1 addition & 1 deletion BlazorBffAzureAD/Client/Shared/MainLayout.razor
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<div class="top-row px-4 auth">
<AuthorizeView>
<Authorized>
<strong>Hello, @context.User.Identity.Name!</strong>
<strong>Hello, @context?.User?.Identity?.Name!</strong>
<form method="post" action="api/Account/Logout">
<AntiForgeryTokenInput/>
<button class="btn btn-link" type="submit">Sign out</button>
Expand Down
2 changes: 1 addition & 1 deletion BlazorBffAzureAD/Client/Shared/NavMenu.razor
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
@code {
private bool collapseNavMenu = true;

private string NavMenuCssClass => collapseNavMenu ? "collapse" : null;
private string? NavMenuCssClass => collapseNavMenu ? "collapse" : null;

private void ToggleNavMenu()
{
Expand Down
1 change: 1 addition & 0 deletions BlazorBffAzureAD/Client/_Imports.razor
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@
@using Microsoft.JSInterop
@using BlazorHosted.Client
@using BlazorHosted.Client.Shared
@using BlazorHosted.Client.Services
Loading