Home > Mobile >  I need to do oauth2 authentication to access gmail in C#
I need to do oauth2 authentication to access gmail in C#

Time:03-24

Currently in the backend, I read the mailbox and send email from gmail using system.net's SMTP in .NET, but google now requires us to do OAuth2 authentication to continue accessing email from GMail. However so far I have managed to get the standard Google html interface to appear to do this authentication, but I need to do this authentication directly in the backend.

My code currently:

[HttpGet]
    [GoogleScopedAuthorize(GmailService.ScopeConstants.GmailCompose)]
    public async Task<ActionResult> userProfile([FromServices] IGoogleAuthProvider auth)
    {
        try
        {
            var cred = await auth.GetCredentialAsync();
            Console.WriteLine("Auntenticado");
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
        return Ok();
}

Default authentication screen: Authentication Screen

I need it to do this authentication directly on the backend.

CodePudding user response:

First off the code you have Show apears to be that you are trying to use the Gmail api. This is not the smtp server.

Also you have included.

[GoogleScopedAuthorize(GmailService.ScopeConstants.GmailCompose)]

Which leads me to believe you are following the asp .net core configure-your-application-to-use-google.apis.auth.aspnetcore3 sample.

As such this is what it is designed to do. It will open the consent window on the users machine and request their permission to access their gmail account.

server side.

If you want to access a users gmail account server side then you will need to authorize them as you are already doing then store the refresh token that is returned. Then you will be able to use that from your server sided application to access the users gmail account with out them being present.

The key here is that you need the users consent before you can access their data.

Application email account

If what you are trying to do is access an account that you control and this is not an account of the users of your system then things will be more difficult for you.

Unless this is a google workspace domain email address you can not user service account authorization. If it is a workspace domain account then I suggest you look into that.

If its a normal standard google gmail account then you will need to authorize the user once. store the refresh token in your system some where and then use that to request an access token as needed. You can use the installed app examples for this. You will need to watch it if your refresh token ever goes down you will loose access. This solution is not optimal but it is the only option available.

Or you can try an apps password with the code you have now. Google has not been clear as to wither or not this will work.

  • Related