Blazor Web App + API + Individual Account

Laurent Guigon 311 Reputation points
2023-12-13T13:09:05.3166667+00:00

Hello,

My question fellow this one. The question still be the same but with a new architecture.
"I intend to utilize .NET Core 8.x and a Blazor Web App, with the plan to incorporate identification features at a later stage. I copied and pasted the code from a previous version, including ApplicationDBContext and all associated data seed services. However, I aim to handle AspNetUser and other classes through the API. How can I achieve this? I've heard about JWT, but I'm unsure about the implementation process.

Additionally, I've encountered an issue with my 'program.cs'. Below is the code snippet from the Wasm .Server's 'program.cs':

using Alurnet.Oniria.Encyclopedia.v7.Server.Data;
using Alurnet.Oniria.Encyclopedia.v7.Server.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System.Reflection;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = Environment.GetEnvironmentVariable("CONNECTION_STRING_ENV_VARIABLE");
//var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

builder.Services.AddIdentityServer()
    .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

builder.Services.AddAuthentication()
    .AddIdentityServerJwt();

builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
    app.UseWebAssemblyDebugging();
    app.UseSwagger();
    app.UseSwaggerUI();
}
else
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseBlazorFrameworkFiles();
app.UseStaticFiles();

app.UseRouting();

app.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization();


app.MapRazorPages();
app.MapControllers();
app.MapFallbackToFile("index.html");

app.Run();

Here is the new structure (It's a WebApi project with .NET 8):

using Alurnet.Oniria.Encyclopedia.v7.WebApi.Data;
using Alurnet.Oniria.Encyclopedia.v7.WebApi.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System.Reflection;



using Alurnet.Oniria.Encyclopedia.v7.WebApi.Data;
using Alurnet.Oniria.Encyclopedia.v7.WebApi.Models;

using Microsoft.EntityFrameworkCore;

var connectionString = Environment.GetEnvironmentVariable("CONNECTION_STRING_ENV_VARIABLE");

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));

var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

My API will be the sole project that accesses the database, and I plan to utilize Microsoft.AspNetCore.Identity.EFCore. Can you assist me in correcting my program.cs file to set up everything?

Note: I prefer not to use Duende. If an authentication solution is necessary to connect the Blazor web app to my API, I would prefer a free alternative. However, I still want to utilize the Identity mechanism with AspNetUser, etc., and I would prefer to utilize the pre-scaffolding.

Once this is done, I'll be able to apply migrations to my database.

Developer technologies .NET Blazor
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2023-12-14T05:20:31.38+00:00

    Hi,@Laurent Guigon

    I prefer not to use Duende. If an authentication solution is necessary to connect the Blazor web app to my API, I would prefer a free alternative. However, I still want to utilize the Identity mechanism with AspNetUser, etc., and I would prefer to utilize the pre-scaffolding.

    In .Net 8,ASP.NET Core Identity provides APIs that would return accesstoken& refreshtoken after you've login for clients that don't support cookies,so your requirement could be achieved without identity server now

    Register required service in your webapi project:

    builder.Services.AddIdentityApiEndpoints<ApplicationUser>()
        .AddEntityFrameworkStores<ApplicationDbContext>();
    

    call the middleware to map api endpoints:

    app.MapIdentityApi<ApplicationUser>();

    Here's the sample codes on github

    You could check the document related for more details:

    How to use Identity to secure a Web API backend for SPAs

    Secure ASP.NET Core Blazor WebAssembly with ASP.NET Core Identity


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Ruikai Feng


1 additional answer

Sort by: Most helpful
  1. Laurent Guigon 311 Reputation points
    2023-12-15T10:02:10.07+00:00

    Since I'm spending too much time constantly changing app versions and facing new things I'm not familiar with, I'll create a simple Blazor Web App (Auto) project first. Later, I'll consider extracting an API. I should have finished my MVP by the 31st, and I haven't even started due to spending time on these kinds of issues.

    Thank you to everyone who has helped me, and know that it's not wasted time. Your comments and information remain in a corner of my mind (and my space on this forum especially).

    Thanks a lot.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.