0

Using a Blazor WebAssembly hosted with a server BFF, I get access from a API which is secured by tokens. I do however have two bff endpoints. One secured by user login and token request, and one that is not authenticated.

endpoints.MapRemoteBffApiEndpoint("/myapi", "https://localhost:7268");

They both point to the same API, but the unsecured is used by the application for a non-user (not signed in) where he can access some of the data from the API.

How may I change this code to secure the unsecure endpoint with a machine to machine?

using Duende.Bff.Yarp;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.ResponseCompression;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();

builder.Services.AddBff(options => options.ManagementBasePath = "/account")
    .AddRemoteApis()
    .AddServerSideSessions();

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
    options.DefaultSignOutScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
    .AddCookie(options =>
    {
        options.Cookie.Name = "__Host-blazor";
        options.Cookie.SameSite = SameSiteMode.Strict;
    })
    .AddOpenIdConnect(options =>
    {
        options.Authority = "https://localhost:5001";
        options.ClientId = "my.blazor.wasm";
        options.Scope.Clear();
        options.Scope.Add("openid");
        options.Scope.Add("profile");        
        options.Scope.Add("roles");
        options.Scope.Add("myapi");
        options.SaveTokens = true;
        options.ResponseType = "code";
        options.GetClaimsFromUserInfoEndpoint = true;
    });

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseWebAssemblyDebugging();
}
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.UseAuthentication();

app.UseRouting();

app.UseBff();
app.UseAuthorization();


app.MapRazorPages();
app.MapControllers();

app.UseEndpoints(endpoints =>
{
    endpoints.MapBffManagementEndpoints();
    endpoints.MapRemoteBffApiEndpoint("/myapi", "https://localhost:7268");
    endpoints.MapRemoteBffApiEndpoint("/myapisecure", "https://localhost:7268").RequireAccessToken();
});

app.MapFallbackToFile("index.html");

app.Run();
Kman
  • 4,809
  • 7
  • 38
  • 62

0 Answers0