Authenticating wordpress from an external app Blazor WASM

222 Views Asked by At

There is a website on wordpress. User registration is performed on the site, accounts are stored in the site database. It is necessary to authenticate users from an external application (Blazor WASM) using the system and the site database, after which, in case of successful authorization, the user will be able to work in an external application.

How can this be done using http requests?

1

There are 1 best solutions below

7
Cory Podojil On

This will depend on a few things -

  1. Are you hosting the WASM app on a separate domain? If so, you will need to configure CORS on the server.
  2. How are you maintaining the authenticated session? Cookies? JSON Web Tokens (JWT)? Custom access token or id?

You will need to include the authorization header with all HTTP requests to ensure the user is still authorized to access you app. Luckily, with Blazor WASM there is a very easy way to add this header to all outgoing HTTP requests using a custom implementation of AuthorizationMessageHandler. Here's an example that I personally use this exact code successfully in my own Blazor WASM app:

public class CorsAuthorizationMessageHandler : AuthorizationMessageHandler
{
    public CorsAuthorizationMessageHandler(IAccessTokenProvider provider, 
       NavigationManager navigation) : base(provider, navigation)
    {
        ConfigureHandler(
            authorizedUrls: new[] { "https://api.myapp.com" }
        );
    }
}

Here's it being added to a HttpClient in Program.cs:

builder.Services.AddHttpClient(
    "Private.ServerAPI", 
    client => client.BaseAddress = new Uri("https://api.myapp.com")
).AddHttpMessageHandler<CorsAuthorizationMessageHandler>();