I am using a blazor server side application to get an access token to have that page call an API. it uses oauth for authorization code flow
so when /Ninja loads I have this code:
protected override async void OnInitialized()
{
if (DeviceService.Token != null)
{
var authorizationUrl = Service.GetAuthorizationUrl();
Navigation.NavigateTo(authorizationUrl);
}
else {
Console.WriteLine($"Token {Service.Token}"); //do stuff here in future with API calls
}
}
the authorizationUrl is a URL from the oauth provider that returns a code for me to use as a query param
on my callback page (/Callback)
[Parameter]
[SupplyParameterFromQuery(Name = "code")]
public string? code { get; set; }
protected override async Task OnInitializedAsync()
{
if (string.IsNullOrEmpty(code))
{
Console.WriteLine("The authorization code is required.");
throw new ArgumentException("The authorization code is required.");
}
try
{
var accessToken = await _ninjaService.GetAccessTokenAsync(code);
if (accessToken != null)
{
Navigation.NavigateTo("/Ninja");
}
}
catch (Exception ex)
{
Console.WriteLine($"Failed to retrieve access token: {ex.Message}");
//errors here all the time with :
///Failed to retrieve access token: Exception of type 'Microsoft.AspNetCore.Components.NavigationException' was thrown.
}
}
}
The access token is not null – so its present and valid but the router never changes so I am stuck on /Callback with the exception of Failed to retrieve access token: Exception of type ‘Microsoft.AspNetCore.Components.NavigationException’ was thrown.
Can someone help me? Ideally the app would route back to /Ninja and avoid a routing loop so with this new token I can call some APIs that require it
I reproduced your problem:
Solution:
You can put the NavigateTo method into OnAfterRender
as shown in the following example:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
try
{
var accessToken = await _ninjaService.GetAccessTokenAsync(code);
if (accessToken != null)
{
Navigation.NavigateTo("/weather");
}
}
catch (Exception ex)
{
Console.WriteLine($"Failed to retrieve access token: {ex.Message}");
}
}
}
After getting the token, I can navigate to the relevant page:
2