Youtube Login Api OAuth 2.0 flutter

Viewed 1341

I've been trying for a bit to implement login of youtube channels on my app. but all I could do was google accounts with google_sign_in 4.5.1

has any of you implemented this feature and can give me an hint? youtube docs are terrible

edit: here's the code

class AuthService {
String oAuthClientId = '**hidden**'; // not used?

  static List<String> scopes = [
    'email',
    'https://www.googleapis.com/auth/youtube', // Youtube scope
  ];

     final FirebaseAuth auth = FirebaseAuth.instance;
  GoogleSignIn googleSignIn = GoogleSignIn(
    scopes: scopes,
  );



Future<FirebaseUser> login() async {
    final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
    final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication;

final AuthCredential credential = GoogleAuthProvider.getCredential(
  accessToken: googleSignInAuthentication.accessToken,
  idToken: googleSignInAuthentication.idToken,
);

final token = googleSignInAuthentication.accessToken;

final AuthResult authResult = await auth.signInWithCredential(credential);
final FirebaseUser user = authResult.user;
assert(!user.isAnonymous);
assert(await user.getIdToken() != null);

final FirebaseUser currentUser = await auth.currentUser();
assert(user.uid == currentUser.uid);

var client = new http.Client();

return currentUser;


 }

  void signOut() {
    auth.signOut();
    googleSignIn.disconnect();
  }

  Future<FirebaseUser> getUser() async{
    final FirebaseUser user = await auth.currentUser();
    return user;
  }
}
1 Answers

To display your youtube channels, you'll need to add the youtube scope https://www.googleapis.com/auth/youtube to your google login.

Prior to this, you must've setup enabled the Youtube api from your developer console. Read the Youtube API documentation for more information

Example login code:

login() async {
    GoogleSignIn googleSignIn = GoogleSignIn(
      scopes: [
        'email',
        'https://www.googleapis.com/auth/youtube', // Youtube scope
      ],
    );
    final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
    final GoogleSignInAuthentication googleSignInAuthentication =
    await googleSignInAccount.authentication;

    final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleSignInAuthentication.accessToken,
      idToken: googleSignInAuthentication.idToken,
    );

    // You'll need this token to call the Youtube API. It expires every 30 minutes.
    final token = googleSignInAuthentication.accessToken; 
    
    final AuthResult authResult = await auth.signInWithCredential(credential);
    final FirebaseUser user = authResult.user;
    assert(!user.isAnonymous);
    assert(await user.getIdToken() != null);

    final FirebaseUser currentUser = await auth.currentUser();
    assert(user.uid == currentUser.uid);
  }
Related