1
votes

I have a Blazor WebAssembly app. It's self contained and doesn't use any web API calls. I'd like to add authentication using my existing Azure AD B2C tenant so that only registered users can access the app.

Microsoft says that:

In Blazor WebAssembly apps, authorization checks can be bypassed because all client-side code can be modified by users.

So rather than host my Blazor app statically (the standalone model), I'd like to use the ASP.NET Core hosted model (so an ASP.NET Core app serves the Blazor app to clients). That way I can do the authentication/authorization on the server - if the user is registered and is allowed access to the app, the ASP.NET Core app serves them the Blazor app. If they aren't, they can be shown an error page or be redirected.

The issue is that I'm not sure how to implement this.

When I create a new Blazor WebAssembly Hosted app from the template in Visual Studio 2019, it creates three projects. A shared project, the Blazor project, and a Server project. The Server project has a reference to the Blazor project. This line appears at the end of the Configure method of Startup.cs:

endpoints.MapFallbackToFile("index.html");

This seems to be the thing that makes it serve the Blazor app to the client. I'm not sure how I can add authentication/authorization to this. I tried modifying this line to look like this:

endpoints.MapFallbackToFile("index.html").RequireAuthorization();

But the app still loads without redirecting to a login screen first.

There is some Microsoft documentation called "Secure an ASP.NET Core Blazor WebAssembly hosted app with Azure Active Directory B2C" which sounds like it's what I need, but it's actually still doing the authentication in the Client app while also securing API calls to the Server app (which I don't need).

Is there any way to accomplish what I'm trying to do - authenticating the user on the server before serving the Blazor app, rather than doing that authentication in the Blazor app itself?

1

1 Answers

0
votes

The answer was really simple. Actually, the RequireAuthorization() call does work. If you're already logged in to B2C you won't be redirected to the login page first (and, in Edge at least, it doesn't even visibly redirect to B2C first before redirecting back to the app, hence the confusion). But if I load the page in a private browser window I am redirected to the B2C login page - so it must be working as intended.

For future reference, the answer to the title question is:

  1. Add auth to the ASP.NET Core Server app if you haven't already.
  2. In the Server app, add a project reference to the Blazor app.
  3. Add the following line to the UseEndpoints call inside the Configure method in Startup.cs:
endpoints.MapFallbackToFile("index.html").RequireAuthorization();