Skip to content

Initial sample commit #110

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

Merged
merged 1 commit into from
Oct 27, 2023
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
18 changes: 18 additions & 0 deletions 8.0/BlazorWasmStandaloneWithIdentity/Backend/Backend.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.0-rc.2.23480.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.0-rc.2.23480.1" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0-rc.2.23480.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>

</Project>
6 changes: 6 additions & 0 deletions 8.0/BlazorWasmStandaloneWithIdentity/Backend/Backend.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@Backend_HostAddress = http://localhost:5266

GET {{Backend_HostAddress}}/weatherforecast/
Accept: application/json

###
70 changes: 70 additions & 0 deletions 8.0/BlazorWasmStandaloneWithIdentity/Backend/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;

var builder = WebApplication.CreateBuilder(args);

// cookie authentication
builder.Services.AddAuthentication(IdentityConstants.ApplicationScheme).AddIdentityCookies();

// configure authorization
builder.Services.AddAuthorizationBuilder();

// add the database (in memory for the sample)
builder.Services.AddDbContext<AppDbContext>(options => options.UseInMemoryDatabase("AppDb"));

// add identity and opt-in to endpoints
builder.Services.AddIdentityCore<MyUser>()
.AddEntityFrameworkStores<AppDbContext>()
.AddApiEndpoints();

// add CORS policy for Wasm client
builder.Services.AddCors(
options => options.AddPolicy(
"wasm",
policy => policy.WithOrigins([builder.Configuration["BackendUrl"], builder.Configuration["FrontendUrl"]])
.AllowAnyMethod()
.SetIsOriginAllowed(pol => true)
.AllowAnyHeader()
.AllowCredentials()));

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// create routes for the identity endpoints
app.MapIdentityApi<MyUser>();

// provide an end point to clear the cookie for logout
app.MapPost("/Logout", async (
ClaimsPrincipal user,
SignInManager<MyUser> signInManager) =>
{
await signInManager.SignOutAsync();
return TypedResults.Ok();
});

// activate the CORS policy
app.UseCors("wasm");

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.Run();

// identity user
class MyUser : IdentityUser { }

// identity database
class AppDbContext(DbContextOptions<AppDbContext> options) : IdentityDbContext<MyUser>(options)
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:27123",
"sslPort": 44394
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5266",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7211;http://localhost:5266",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
11 changes: 11 additions & 0 deletions 8.0/BlazorWasmStandaloneWithIdentity/Backend/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"BackendUrl": "https://localhost:7211",
"FrontendUrl": "https://localhost:7171"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Authentication" Version="8.0.0-rtm.23502.22" />
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0-rc.2.23479.6" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="8.0.0-rtm.23502.22" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="8.0.0-rtm.23502.22" PrivateAssets="all" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<CascadingAuthenticationState>
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
</CascadingAuthenticationState>
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
@page "/login"
@using BlazorWasmAuth.Identity
@inject IAccountManagement Acct

<AuthorizeView>
<Authorized>
<div class="alert alert-success">You are logged in as @context.User.Identity?.Name.</div>
</Authorized>
<NotAuthorized>
<h1>Login</h1>
@if (errors)
{
@foreach (var error in errorList)
{
<div class="alert alert-danger">@error</div>
}
}
<div class="flex-outer">
<div>
<label for="email">
Email:
</label>
<input required id="email" name="emailInput" placeholder="Enter your email address" type="email" @bind-value="email" />
</div>

<div>
<label for="password">
Password:
</label>
<input required id="password" name="passwordInput" placeholder="Enter your password" type="password" @bind-value="password" />
</div>
<div>
<button @onclick="DoLoginAsync">Login</button>
</div>
</div>
</NotAuthorized>
</AuthorizeView>

@code {
private bool success, errors;
private string email = string.Empty;
private string password = string.Empty;
private string[] errorList = [];

public async Task DoLoginAsync()
{
success = errors = false;
errorList = [];

if (string.IsNullOrWhiteSpace(email))
{
errors = true;
errorList = ["Email is required."];
return;
}

if (string.IsNullOrWhiteSpace(password))
{
errors = true;
errorList = ["Password is required."];
return;
}

var result = await Acct.LoginAsync(email!, password!);

if (result.Succeeded)
{
success = true;
email = password = string.Empty;
}
else
{
errors = true;
errorList = result.ErrorList;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
@page "/logout"
@using BlazorWasmAuth.Identity
@inject IAccountManagement AcctMgmt

<AuthorizeView @ref="authView">
<Authorized>
<div class="alert alert-info">Logging you out...</div>
</Authorized>
<NotAuthorized><div class="alert alert-success">You are logged out. <a href="/login">Log in.</a></div></NotAuthorized>
</AuthorizeView>

@code {
private AuthorizeView? authView;

protected override async Task OnInitializedAsync()
{
if (await AcctMgmt.CheckAuthenticatedAsync())
{
await AcctMgmt.LogoutAsync();
}
await base.OnInitializedAsync();
}
}
Loading