Search code examples
asp.netasp.net-mvcgoogle-apigoogle-api-clientgoogle-api-dotnet-client

redirect_uri_mismatch in Google APIs in ASP.NET


I am trying to upload video on my YouTube channel using ASP.NET Web Form. I created developer account and tested it working using JavaScript based solution which requires login every-time to upload a video.

I want users of my website to upload video directly on my channel and every auth should be in code behind, user should not be prompted to login. For this I wrote following class:

public class UploadVideo
{
    public async Task Run(string filePath)
    {
        string CLIENT_ID = "1111111111111111111111.apps.googleusercontent.com";
        string CLIENT_SECRET = "234JEjkwkdfh1111";
        var youtubeService = AuthenticateOauth(CLIENT_ID, CLIENT_SECRET, "SingleUser");

        var video = new Video();
        video.Snippet = new VideoSnippet();
        video.Snippet.Title = "Default Video Title";
        video.Snippet.Description = "Default Video Description";
        video.Snippet.Tags = new string[] { "tag1", "tag2" };
        video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
        video.Status = new VideoStatus();
        video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"

        using (var fileStream = new FileStream(filePath, FileMode.Open))
        {
            var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
            videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
            videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

            await videosInsertRequest.UploadAsync();
        }
    }

    void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
    {
        switch (progress.Status)
        {
            case UploadStatus.Uploading:
                //Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                break;

            case UploadStatus.Failed:
                //Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                break;
        }
    }

    void videosInsertRequest_ResponseReceived(Video video)
    {
        Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
    }

    public static YouTubeService AuthenticateOauth(string clientId, string clientSecret, string userName)
    {

        string[] scopes = new string[] { YouTubeService.Scope.Youtube,  // view and manage your YouTube account
                                         YouTubeService.Scope.YoutubeForceSsl,
                                         YouTubeService.Scope.Youtubepartner,
                                         YouTubeService.Scope.YoutubepartnerChannelAudit,
                                         YouTubeService.Scope.YoutubeReadonly,
                                         YouTubeService.Scope.YoutubeUpload};

        try
        {
            // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
            UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                         , scopes
                                                                                         , userName
                                                                                         , CancellationToken.None
                                                                                         , new FileDataStore("Daimto.YouTube.Auth.Store")).Result;

            YouTubeService service = new YouTubeService(new YouTubeService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "YouTube Data API Sample",
            });
            return service;
        }
        catch (Exception ex)
        {
            //Console.WriteLine(ex.InnerException);
            return null;
        }
    }
}

Now using this class into Page_Load() of default.aspx, as given below:

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        string path = "C:/Users/abhi/Desktop/TestClip.mp4";
        new UploadVideo().Run(path).Wait();
    }
    catch (AggregateException ex)
    {
        //catch exceptions
    }
}

When I run this (default.aspx) page, i see http://localhost:29540/default.aspx spins, so I used them on Google Developer Console as given below:

enter image description here

Upon running http://localhost:29540/default.aspx opens a new tab which displays "redirect_uri_mismatch" error as given below:

enter image description here

At this point if I look in browser address, I see redirect_uri is set to http://localhost:37294/authorize and I just manually change this to http://localhost:29540/default.aspx which generates a token.

So, can you suggest where to make changes in above code so that request uri fills up correctly from my app side.


Solution

  • A day waste then I came to know below redirect URL is working for all localhost web applications. So you need to use below URL on google developer console web application's "Authorized redirect URIs".

    http://localhost/authorize/