tweetinvi icon indicating copy to clipboard operation
tweetinvi copied to clipboard

Authentication - System.NullReferenceException: 'Object reference not set to an instance of an object.'

Open p1pster opened this issue 6 years ago • 11 comments

Hi there, I have created a class which was made to pass back the authenticate then pass back the credentials so i could use them in the main code, however, im having issues just getting the code to authenticate. I have tried numerous methods and once authenticated i am getting a null responce even when trying to get a authenticated users name or screen name. At present im getting a System.NullReferenceException: 'Object reference not set to an instance of an object.', on the below code line as var authenticateduser = User.GetAuthenticatedUser();:

`using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Diagnostics; using Tweetinvi.Models; using System.Windows.Forms; using Tweetinvi;

public static class TwitterAuthentication
{

public static string Authentication(string ck, string csk)
    {
        IAuthenticationContext _authContext;
        var appCredentials = new TwitterCredentials(ck, csk);
        _authContext = AuthFlow.InitAuthentication(appCredentials);

        using (var client = new WebClient())
        {
                using (var Stream = client.OpenRead("http://www.google.com"))
                {
                    Process.Start(_authContext.AuthorizationURL);

                    //open pin box and enter pin
                    SocialiFace.Twitter_Pin_Auth_Form Pin = new SocialiFace.Twitter_Pin_Auth_Form();
                    Pin.ShowDialog();
                    System.Console.WriteLine(Pin.Pin_Auth);
                    var userCredentials = AuthFlow.CreateCredentialsFromVerifierCode(Pin.Pin_Auth, _authContext);
                    Auth.SetCredentials(userCredentials);

                    try
                    {
                        var authenticateduser = User.GetAuthenticatedUser();
                        string handle = authenticateduser.Name;
                        return handle;
                    }
                    catch (Tweetinvi.Exceptions.TwitterNullCredentialsException)
                    {
                        MessageBox.Show("Error Authenticating");
                        return null;
                    }
                    
                }
        }
       
    }
    
}

`

p1pster avatar Aug 19 '19 15:08 p1pster

I have the same problem please let me know how to solve this.

dybbsteppp avatar Aug 23 '19 04:08 dybbsteppp

I have just tried myself and everything works with the latest version of Tweetinvi. Are you using version 4.0.1?

Thanks

linvi avatar Aug 24 '19 13:08 linvi

@linvi yes i am using 4.0.1, however i notice in nuget manager 4,0,2, ill try to upgrade and see if that solves anything.

p1pster avatar Aug 27 '19 15:08 p1pster

Hello everyone,

I have the same problem i think: I'm try to post in twitter but something is not working, i reed a the documentation and my code is fine but I don't know whats is happening

This is my code:

public string TwitterAuth()
        {
            var i4SystemCreds = _credRepo.GetSystemCredentials(social_medias.Twitter);
            var appCreds = new ConsumerCredentials(i4SystemCreds.AppKey, i4SystemCreds.AppSecret);
            var redirectURL = "http://" + Request.Url.Authority + "/Relations/ValidateTwitterAuth";
            
            _twitterAuthenticationContext = AuthFlow.InitAuthentication(appCreds, redirectURL);
            if (_twitterAuthenticationContext == null)
            {
                throw new Exception("autenticação do Twitter retornou null");
            }
            return _twitterAuthenticationContext.AuthorizationURL;
        }
        public ActionResult ValidateTwitterAuth()
        {
            // Get some information back from the URL
            var verifierCode = Request.Params.Get("oauth_verifier");
            var authorizationId = Request.Params.Get("authorization_id");
            // Create the user credentials
            if (verifierCode != null)
            {
                var userCreds = AuthFlow.CreateCredentialsFromVerifierCode(verifierCode, authorizationId);
                var user = Tweetinvi.User.GetAuthenticatedUser(userCreds);
                StoreTwitterCredentials(userCreds);
                ViewBag.User = user;
            }
            return RedirectToAction("Agenda", "Relations");
        }

Please help me.

Atte: William Blacutt

williamblacutt avatar Jan 22 '20 12:01 williamblacutt

Hello there,

I would need more information in order to help:

  • Where do you get the exception?
  • What information do you have in the exception?
  • Are you using the latest version of Tweetinvi?
  • Are your credentials working?

Cheers, Linvi

linvi avatar Jan 22 '20 13:01 linvi

Where do you get the exception? This is the post window:

image

When I put Ok he do the process, this process need to be the TwitterAuth request to take the Token and TokenSecret from the customer twitter account

What information do you have in the exception?

if (_twitterAuthenticationContext == null) { throw new Exception("autenticação do Twitter retornou null"); } return _twitterAuthenticationContext.AuthorizationURL;

Are you using the latest version of Tweetinvi? Yes Are your credentials working? Yes

williamblacutt avatar Jan 22 '20 13:01 williamblacutt

Please enable exception handling and let me know what you get there.

https://github.com/linvi/tweetinvi/wiki/Exception-Handling

You will likely receive an exception for line _twitterAuthenticationContext = AuthFlow.InitAuthentication(appCreds, redirectURL);

Use a try/catch for TwitterException. There you will be able to do exception.ToString() and send this to me.

linvi avatar Jan 22 '20 14:01 linvi

This is the erro:

image

williamblacutt avatar Jan 24 '20 19:01 williamblacutt

Hello there,

This is the first time I seem something like this. Apparently the error is not returning any information. I am not sure how I can help you further here.

Have you inspected the error and see if you had anything there?

Thanks, Linvi

linvi avatar Jan 26 '20 23:01 linvi

This code directly throws NullReferenceException on me with the latest version (4.0.3) of the library on NuGet:

  public class LoginModel : PageModel {
    private readonly IConfiguration config;

    public LoginModel(IConfiguration configuration) {
      this.config = configuration;
    }
    public void OnGet() {
      string consumerKey = config["Twitter:ConsumerKey"];
      string consumerSecret = config["Twitter:ConsumerSecret"];
      var credentials = new ConsumerCredentials(consumerKey,
        consumerSecret);
      string callbackUrl =
        $"{Request.Scheme}://{Request.Host}/Callback";
      var context = AuthFlow.InitAuthentication(credentials,
        callbackUrl); // this is where the exception is thrown
      Redirect(context.AuthorizationURL);
    }
  }

Exception details:

System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=Tweetinvi.Logic
  StackTrace:
   at Tweetinvi.Logic.Exceptions.WebExceptionInfoExtractor.GetTwitterExceptionInfosFromStream(Stream stream)

The contents of consumerKey and consumerSecret are correct.

This is an ASP.NET Core 3.1 Razor Pages project.

ssg avatar Jun 11 '20 17:06 ssg

Hello there,

Sorry for the delay. For this specific problem, I think the only way I could help you is if you shared a project where you can reproduce the problem and share with me the steps to reproduce it.

Thanks, Linvi

linvi avatar Aug 23 '20 16:08 linvi