Skip to content

Commit

Permalink
Initial sample commit (dotnet#110)
Browse files Browse the repository at this point in the history
  • Loading branch information
JeremyLikness authored Oct 27, 2023
1 parent fb95ec6 commit 37f9eda
Show file tree
Hide file tree
Showing 37 changed files with 1,404 additions and 0 deletions.
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

0 comments on commit 37f9eda

Please sign in to comment.