Skip to content

Net core5 #14

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
35 changes: 23 additions & 12 deletions src/AuthenticationWithClientSideBlazor.Client/App.razor
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@
<Router AppAssembly="@typeof(Program).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
</Found>
<NotFound>
<CascadingAuthenticationState>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</CascadingAuthenticationState>
</NotFound>
</Router>
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(Program).Assembly" PreferExactMatches="@true">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
@if (!context.User.Identity.IsAuthenticated)
{
<RedirectToLogin />
}
else
{
<p>You are not authorized to access this resource.</p>
}
</NotAuthorized>
</AuthorizeRouteView>
</Found>
<NotFound>
<LayoutView Layout="@typeof(MainLayout)">
<p>Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<OutputType>Exe</OutputType>
<LangVersion>7.3</LangVersion>
<RazorLangVersion>3.0</RazorLangVersion>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Blazored.LocalStorage" Version="2.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Blazor" Version="3.1.0-preview3.19555.2" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.Build" Version="3.1.0-preview3.19555.2" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Blazor.HttpClient" Version="3.1.0-preview3.19555.2" />
<PackageReference Include="Microsoft.AspNetCore.Components.Authorization" Version="3.1.0-preview3.19555.2" />
</ItemGroup>

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

</Project>
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Blazored.LocalStorage" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="5.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="5.0.4" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Authentication" Version="5.0.4" />
<PackageReference Include="Microsoft.Extensions.Http" Version="5.0.0" />
<PackageReference Include="System.Net.Http.Json" Version="5.0.0" />
</ItemGroup>

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

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

namespace AuthenticationWithClientSideBlazor.Client
{


public static class HttpClientExtensions
{



public static async Task<T> ReadAsJsonAsync<T>(this HttpContent content)
{
var dataAsString = "";
try
{
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
dataAsString = await content.ReadAsStringAsync();
if (string.IsNullOrEmpty(dataAsString)) return default;
return JsonSerializer.Deserialize<T>(dataAsString, options);
}
catch (Exception e)
{
throw new ArgumentException($"Invalid json: '{dataAsString}'", e.InnerException);
}
}


}
}
32 changes: 16 additions & 16 deletions src/AuthenticationWithClientSideBlazor.Client/Pages/Counter.razor
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
int currentCount = 0;

void IncrementCount()
{
currentCount++;
}
}
@page "/counter"
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
101 changes: 56 additions & 45 deletions src/AuthenticationWithClientSideBlazor.Client/Pages/FetchData.razor
Original file line number Diff line number Diff line change
@@ -1,45 +1,56 @@
@page "/fetchdata"
@using AuthenticationWithClientSideBlazor.Shared
@inject HttpClient Http

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from the server.</p>

@if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}

@code {
WeatherForecast[] forecasts;

protected override async Task OnInitializedAsync()
{
forecasts = await Http.GetJsonAsync<WeatherForecast[]>("api/SampleData/WeatherForecasts");
}
}
@page "/fetchdata"
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using AuthenticationWithClientSideBlazor.Shared
@attribute [Authorize]
@inject HttpClient Http

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from the server.</p>

@if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}

@code {
private WeatherForecast[] forecasts;

protected override async Task OnInitializedAsync()
{
try
{
forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
}
catch (AccessTokenNotAvailableException exception)
{
exception.Redirect();
}
}

}
14 changes: 7 additions & 7 deletions src/AuthenticationWithClientSideBlazor.Client/Pages/Index.razor
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />
@page "/"
<h1>Hello, world!</h1>
Welcome to your new app.
<SurveyPrompt Title="How is Blazor working for you?" />
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
@page "/login"
@using AuthenticationWithClientSideBlazor.Client.Services
@using AuthenticationWithClientSideBlazor.Shared
@inject IAuthService AuthService
@inject NavigationManager NavigationManager

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
@page "/logout"
@using AuthenticationWithClientSideBlazor.Client.Services
@using System.Threading.Tasks
@inject IAuthService AuthService
@inject NavigationManager NavigationManager

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
@page "/register"
@using AuthenticationWithClientSideBlazor.Client.Services
@using AuthenticationWithClientSideBlazor.Shared
@inject IAuthService AuthService
@inject NavigationManager NavigationManager

Expand Down
49 changes: 33 additions & 16 deletions src/AuthenticationWithClientSideBlazor.Client/Program.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,33 @@
using Microsoft.AspNetCore.Blazor.Hosting;

namespace AuthenticationWithClientSideBlazor.Client
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IWebAssemblyHostBuilder CreateHostBuilder(string[] args) =>
BlazorWebAssemblyHost.CreateDefaultBuilder()
.UseBlazorStartup<Startup>();
}
}
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using AuthenticationWithClientSideBlazor.Client.Services;
using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components.Authorization;

namespace AuthenticationWithClientSideBlazor.Client
{
public class Program
{
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");

builder.Services.AddHttpClient("AuthenticationWithClientSideBlazor.ServerAPI",
client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress));

// Supply HttpClient instances that include access tokens when making requests to the server project
builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("AuthenticationWithClientSideBlazor.ServerAPI"));
builder.Services.AddAuthorizationCore();
builder.Services.AddBlazoredLocalStorage();
builder.Services.AddScoped<AuthenticationStateProvider, ApiAuthenticationStateProvider>();

builder.Services.AddScoped<IAuthService, AuthService>();
await builder.Build().RunAsync();
}
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
using AuthenticationWithClientSideBlazor.Shared;
using Blazored.LocalStorage;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Net.Http.Json;

using System.Threading.Tasks;

namespace AuthenticationWithClientSideBlazor.Client.Services
Expand All @@ -28,16 +26,17 @@ public AuthService(HttpClient httpClient,

public async Task<RegisterResult> Register(RegisterModel registerModel)
{
var result = await _httpClient.PostJsonAsync<RegisterResult>("api/accounts", registerModel);
var response = await _httpClient.PostAsJsonAsync("api/accounts", registerModel);
var result = await response.Content.ReadAsJsonAsync<RegisterResult>();

return result;
}

public async Task<LoginResult> Login(LoginModel loginModel)
{
var loginAsJson = JsonSerializer.Serialize(loginModel);
var response = await _httpClient.PostAsync("api/Login", new StringContent(loginAsJson, Encoding.UTF8, "application/json"));
var loginResult = JsonSerializer.Deserialize<LoginResult>(await response.Content.ReadAsStringAsync(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
var response = await _httpClient.PostAsJsonAsync("api/Login", loginModel);

var loginResult = await response.Content.ReadAsJsonAsync<LoginResult>();

if (!response.IsSuccessStatusCode)
{
Expand Down
Loading