Search code examples
c#asp.net-core-mvc.net-8.0

Overriding signin-google endpoint in a .Net 8 web app


I have an app that uses an external login to Google along the lines defined here. When logging in, it calls back to my app to the "/signin-google" endpoint which is built-in. My intention is to intercept the Google callback so I can grab the access token and use it to interact with Google APIs. I've built an endpoint to override the default endpoint like so:

public async Task<IActionResult> GoogleCallback(string code, string state)
{
    await _loginService.RegisterTokenAsync(User.Identity.Name, code);

    return RedirectToAction("Index", "Home");
}

I tried adding a route like

[Route("signin-google")]

But for some reason that doesn't work. When I call "https://localhost:7064/signin-google?code=test1&state=test2", it points to the default signin-google endpoint (the one I'm trying to override) instead of my custom endpoint.

I've been able to override this behaviour with the following:

app.UseEndpoints(endpoints =>
{
    endpoints.MapGet("/signin-google", async context =>
    {
        var queryString = context.Request.Query;
        var code = queryString["code"];
        var state = queryString["state"];

        context.Response.Redirect($"/Account/GoogleCallback?code={code}&state={state}");
    });
});

But this stops regular username-and-password logins from working, and it's something of a brute-force approach that I don't really like. I'll be happy enough if I can get the endpoints method to work, but ideally I'd find some way to get the signin-google endpoint overridden.


Solution

  • While I don't have a direct answer to this question, I have found a workaround that serves my purposes, although it's limited.

    Instead of using the access token, I created a service account and used the JSON Google gave me to provide credentials, like so:

    var credential = GoogleCredential.FromStream(new FileStream("mycredentials.json", FileMode.Open));
    

    Then I was able to make modifications to sheets that the service account has access to. This works for me because they're public sheets, but the limitation is that I would need to give that service account permissions to any sheets I want to edit programmatically. Not the end of the world, but not ideal either.

    I would still prefer to get the access token, so if anyone has a solution to that, I'll accept that answer over this one.