Skip to content

Using Cookies instead of access_token in the wasm mode of Blazor WebApp tiered app. #22622

@maliming

Description

@maliming

This change only applies to Blazer WebApp tiered projects.

Old behavior

Previously, we used PersistentComponentState in App.razor to pass the access_token to the WebApp.Client project for API calls.

The BaseUrl of RemoteServices in the WebApp.Client project targets the API website.

[CascadingParameter]
private HttpContext HttpContext { get; set; } = default!;

[Inject]
private PersistentComponentState PersistentComponentState { get; set; }

private string? Token { get; set; } = default!;

protected override async Task OnInitializedAsync()
{
    if (HttpContext.User?.Identity?.IsAuthenticated == true)
    {
        Token = await HttpContext.GetTokenAsync("access_token");
    }

    PersistentComponentState.RegisterOnPersisting(OnPersistingAsync, RenderMode.InteractiveWebAssembly);
}

async Task OnPersistingAsync()
{
    if (!Token.IsNullOrWhiteSpace())
    {
        PersistentComponentState.PersistAsJson(PersistentAccessToken.Key, new PersistentAccessToken
        {
            AccessToken = Token
        });
    }

    await Task.CompletedTask;
}

New behavior

In the new Blazer WebApp tiered template, we will make HTTP requests to the current WebApp website instead of the API website.

Why

This way we will no longer need to pass the access_token to the WebApp.Client, because the WebApp uses cookie authentication.

Mitigations

  1. Change BaseUrl of RemoteServices in the WebApp.Client's appsettings.json file to the current WebApp website's URL.
{
  "RemoteServices": {
    "Default": {
      "BaseUrl": "https://localhost:44334" // Your WebApp project URL.
    },
    "AbpAccountPublic": {
      "BaseUrl": "https://localhost:44377"
    }
  }
}
  1. Change AddBlazorWebAppTieredServices to AddBlazorWebAppServices in ConfigureAuthentication method in WebApp.Client project.
- builder.Services. AddBlazorWebAppTieredServices();
+ builder.Services.AddBlazorWebAppServices();
  1. Update App.razor in WebApp project file as below:
@using Volo.Abp.AspNetCore.Mvc.AntiForgery;

[Inject]
private IAbpAntiForgeryManager AbpAntiForgeryManager { get; set; }

protected override Task OnInitializedAsync()
{
   AbpAntiForgeryManager.SetCookie();
   return Task.CompletedTask;
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions