I have a new Blazor application I'm trying to stitch together and I want to read out all my recent Google drive files. Calling the auth code flow, getting a response (including the code) and so forth is all working fine. I have the correct approve-list of redirect URIs but calling flow.ExchangeCodeForTokenAsync
always fails with a response property saying the call is in a faulted state.
When initially calling my 'signin' page, the code redirects as expected, with the appropriate state and code string included in the URL. However, when my page sees a Google response code and falls into the second part of my if/then conditional, the Task always fails, token.IsFaulted
is always true and WASM shows an exception: "WASM: [System.AggregateException] One or more errors occurred. (Cannot invoke method because it was wiped"
I could really do with a nudge in the right direction here.
@using Google.Apis.Drive.v3
@using Google.Apis.Auth.OAuth2
@using Google.Apis.Auth.OAuth2.Flows
@using Google.Apis.Auth.OAuth2.Responses
@using Google.Apis.Auth.OAuth2.Web
@using Google.Apis.Services
@using Google.Apis.Util.Store
@using System.IO
@using System.Threading
@page "/signin"
@inject HttpClient Http
@inject Microsoft.AspNetCore.Blazor.Services.IUriHelper UriHelper
@functions {
private GoogleAuthorizationCodeFlow flow;
private string[] _scopes = new string[]
{
DriveService.Scope.Drive,
DriveService.Scope.DriveReadonly,
DriveService.Scope.DriveMetadataReadonly,
DriveService.Scope.DriveAppdata,
DriveService.Scope.DriveFile
};
ClientSecrets secrets = new ClientSecrets()
{
ClientId = "a-very-long-string",
ClientSecret = "a-slightly-shorter-string"
};
protected override async Task OnInitAsync()
{
flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer(){
DataStore = new FileDataStore("My.Education.Store", false),
ClientSecrets = secrets,
Scopes = _scopes
});
Uri uri = new Uri(UriHelper.GetAbsoluteUri());
string code = uri.Query.IndexOf("code") > 0 ? uri.QueryParam()["code"] : String.Empty; // QueryParam is just an extension method
if (String.IsNullOrEmpty(code))
{
AuthorizationCodeWebApp.AuthResult result = (new AuthorizationCodeWebApp(flow, $"{uri.Scheme}://{uri.Host}:{uri.Port}/signin", uri.ToString())).AuthorizeAsync("me", CancellationToken.None).Result;
Console.WriteLine($"Redirecting to {result.RedirectUri}");
//UriHelper.NavigateTo(result.RedirectUri);
}
else
{
var token = flow.ExchangeCodeForTokenAsync("me", code, "http://locahost:5000", CancellationToken.None);
Console.WriteLine(token.IsCompleted);
Console.WriteLine($"Faulted: {token.IsFaulted}"); // always true
}
}
}