Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sendgrid API: The provided authorization grant is invalid, expired, or revoked

Tags:

c#

sendgrid

I've just created a sendgrid account. Then I went to settings=>API Keys and clicked on "Create API Key" and gave any possible permission.

Then I've created a c# project, added nuget packages and put my write the hello world code from here

 public async Task HelloEmail()
 {
            dynamic sg = new SendGrid.SendGridAPIClient("XXX-XXXXXXXXXXXXXXXXXX", "https://api.sendgrid.com");

        Email from = new Email("[email protected]");

        String subject = "Hello World from the SendGrid CSharp Library";
        Email to = new Email("[email protected]");
        Content content = new Content("text/plain", "Textual content");
        Mail mail = new Mail(from, subject, to, content);
        Email email = new Email("[email protected]");
        mail.Personalization[0].AddTo(email);

        dynamic response = await sg.client.mail.send.post(requestBody: mail.Get());

        var x=response.StatusCode;
        var y = response.Body.ReadAsStringAsync().Result;
        var z = response.Headers.ToString();
 }

But I get

Unauthorized =>

"{\"errors\":[{\"message\":\"The provided authorization grant is invalid, expired, or revoked\",\"field\":null,\"help\":null}]}"


In the example, they got the API key from the EnvironmentVariableTarget.User is it related to that?

string apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY", EnvironmentVariableTarget.User);
dynamic sg = new SendGridAPIClient(apiKey);

*The problem is that no one reads messages when creating a key, also Microsoft chooses to show us "API Key ID" which is worst name ever

It is not a duplicate because although the reason was the same, no one would guess it since in c# we use a nuget library, not the api.

like image 209
Ashkan S Avatar asked Oct 30 '22 17:10

Ashkan S


1 Answers

Something is wrong with your API key. Check this answer, generate a new key, and double check your permissions.

You also don't need to specify the URL in your SendGrid.SendGridAPIClient. I'd remove that line to reduce hardcoded values.

like image 187
bwest Avatar answered Nov 15 '22 04:11

bwest