I have a .Net 8 blazor solution. On creation I chose an Interactive render mode of "auto", and when visual studio built the solution it created two projects: one server-side, one client-side.
I added a <CascadingAuthenticationState> tag to wrap the entire contents of my Routes.razor file (which Visual Studio put in my server-side application). My Routes.razor looks like this:
<CascadingAuthenticationState><Router AppAssembly="typeof(Program).Assembly" AdditionalAssemblies="new[] { typeof(Client._Imports).Assembly }"><Found Context="routeData"><RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" /><FocusOnNavigate RouteData="routeData" Selector="h1" /></Found></Router></CascadingAuthenticationState>The MainLayout.razor was also created in the server-side project, I added an ErrorBoundary but otherwise it is the default:
<main><article class="content px-4"><ErrorBoundary><ChildContent> @Body</ChildContent><ErrorContent Context="exception"><Error Exception="@exception" /></ErrorContent></ErrorBoundary></article></main>I kept the default NavMenu.Razor (also on the server-side) and wrapped all of the menu options in an AuthorizeView tag, it looks like this. The "Home" and "Claims" pages are in the server-side project, and the "Client Payee Search" page is in the client-side project:<AuthorizeView Policy="AnyPayeeAdminRole"><div class="nav-item px-3"><NavLink class="nav-link" href="" Match="NavLinkMatch.All"><span class="bi bi-house-door-fill-nav-menu" aria-hidden="true"></span> Home</NavLink></div><div class="nav-item px-3"><NavLink class="nav-link" href="claims"><span class="bi bi-plus-square-fill-nav-menu" aria-hidden="true"></span>Claims</NavLink></div><div class="nav-item px-3"><NavLink class="nav-link" href="ClientPayeeSearch"><span class="bi bi-plus-square-fill-nav-menu" aria-hidden="true"></span>Client Payee Search</NavLink></div></AuthorizeView>The link to "ClientPayeeSearch" points to a page in the client-side project. The top of that page has these four statements:
@rendermode InteractiveWebAssembly@inject HttpClient HttpClient@inject IConfiguration Configuration@attribute [Authorize(Policy = "AnyPayeeAdminRole")]In my server-side Program.cs I have OIDC configuration. We happen to use PingOne, so when I start this web application on my local host I'm immediately shunted to PingOne to enter my username and password, and then redirected back. The PingOne OIDC application type is "Web App". The scopes that get passed are "openid", "profile", "email", "address", "phone". All of this works fine:
services.AddAuthentication(delegate (AuthenticationOptions authenticationOptions) { authenticationOptions.DefaultScheme = "Cookies"; authenticationOptions.DefaultChallengeScheme = "OpenIdConnect"; }).AddCookie(delegate (CookieAuthenticationOptions cookieAuthenticationOptions) { cookieAuthenticationOptions.Events.OnRedirectToAccessDenied = async delegate { await Task.CompletedTask; }; }).AddOpenIdConnect(delegate (OpenIdConnectOptions openIdConnectOptions) { openIdConnectOptions.Authority = ssoAppSettings.PingOne.Authority; openIdConnectOptions.CallbackPath = ssoAppSettings.PingOne.CallbackPath; openIdConnectOptions.ClientId = ssoAppSettings.PingOne.ClientId; openIdConnectOptions.ClientSecret = clientSecret; openIdConnectOptions.SignedOutCallbackPath = ssoAppSettings.PingOne.SignedOutCallbackPath; openIdConnectOptions.ResponseType = ssoAppSettings.PingOne.ResponseType; openIdConnectOptions.SaveTokens = true; openIdConnectOptions.Scope.Clear(); string[] scopes = ssoAppSettings.PingOne.Scopes; foreach (string item in scopes) { openIdConnectOptions.Scope.Add(item); } openIdConnectOptions.Events.OnAuthenticationFailed = (AuthenticationFailedContext context) => Task.CompletedTask; openIdConnectOptions.Events.OnAccessDenied = (AccessDeniedContext context) => Task.CompletedTask; openIdConnectOptions.Events.OnRemoteFailure = (RemoteFailureContext context) => Task.CompletedTask; });My problem is, in my client-side page, I cannot fetch a generic list from my server-side web api in the OnInitializedAsync event. The server-side web api is protected with an Authorize attribute and looks like this:
[Authorize(Policy = "AnyPayeeAdminRole")]public class CacheController : ControllerBase{[HttpGet("GetClients")]public async Task<ActionResult<List<PLP.Library.PayeeAdmin.Models.Client>>> GetClients(){ return await _cache.GetClients();}I'm calling it from my client-side Razor component like this:
protected override async Task OnInitializedAsync(){ var clients = await HttpClient.GetFromJsonAsync<List<PLP.Library.PayeeAdmin.Models.Client>>("api/cache/GetClients");The call never reaches the method. Instead, the controller tries to redirect me back to PingOne to get my credentials; it returns a blob of html attempting to do that. Since that is not a generic list my call fails.
What am I missing? In my client-side project, in my program.cs, I am adding the "HttpClient" like so:
builder.Services.AddScoped(o => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });Do I need to add something else to the HttpClient? Or do I need to add some argument to my HttpClient.GetFromJsonAsync call?
In v1, before I tried fetching this generic list in the OnInitializedAsync event, the page loaded fine, and I was able to post it back to a server-side controller POST controller method with an Authorize attribute, and it returned a generic list of search results, which I could render successfully. So Blazor must have been passing credentials when I posted back. The successful POST looked like this from the razor component:
var response = await HttpClient.PostAsJsonAsync("api/payeeAdmin/GetClientPayeeSearchResults", clientPayeeSearch);In v1 I was manually entering the various values I needed for searches. Now I'm attempting to add dropdowns with enums, and I can't get past this HttpClient.GetFromJsonAsync call, which is where I want to collect the enums.
Part of the attraction of Blazor was me assuming it handled all of the authorization using attributes, but that is not working out so well!