YouTube and OAuth 2.0 in .Net

Deadly 提交于 2019-12-03 20:57:47

Do do this you need to have both an account set up on google data apps (https://code.google.com/apis/console) and with the youtube apis (http://code.google.com/apis/youtube/dashboard).

You then have to authenticate the google data api using their oauth mechanisms. Something like the following - this is gutted from some code we have. {code}

//Create Client     
m_Client = new NativeApplicationClient(GoogleAuthenticationServer.Description, m_ClientID, m_ClientSecret);
//Add Youtube scope to requested scopes
m_Scopes.Add("https://gdata.youtube.com");
//Get Authentication URL
authStateInitial = new AuthorizationState(m_Scopes);
authStateInitial.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = m_Client.RequestUserAuthorization(authStateInitial);

//Navigate to URL, authenticate get accessToken
string accessToken = ...;

string[] tokens = accessToken.Split(new char[] { '&' });
if(tokens.Length == 2)
{
  authStateFinal = new AuthorizationState(m_Scopes);
  authStateFinal.AccessToken = tokens[0];
  authStateFinal.RefreshToken = tokens[1];

  if(m_AuthStateInitial == null)
  {
    m_Client.RefreshToken(m_AuthStateFinal);
  }
  OAuth2Authenticator<NativeApplicationClient> authenticator = new OAuth2Authenticator<NativeApplicationClient>(m_Client, GetState); //GetState returns authStateInitial
  authenticator.LoadAccessToken();
}

Then you have to authenticate the youtube apis by using both the access token you got from above and the youtube Developer Key. {code}

    GAuthSubRequestFactory m_Authenticator = new GAuthSubRequestFactory(ServiceNames.YouTube, "Product Name");
    m_Authenticator.Token = AccessToken;

    YouTubeService m_YouTubeService = new YouTubeService(m_Authenticator.ApplicationName, m_DeveloperKey);
    m_YouTubeService.RequestFactory = m_Authenticator;

Hope this helps someone.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!