简体   繁体   English

Dart中的Google Firebase和API:生成访问令牌和自定义访问令牌

[英]Google Firebase and APIs in Dart: Generating an Access Token and Custom Access Token

Using Google Firebase and Google APIs in Dart: Is there an equivalent to the following two .js programs in .dart: 在Dart中使用Google Firebase和Google API:.dart中是否有以下两个.js程序的等效项:

  1. Generate an Access Token on the server: 在服务器上生成访问令牌:

; ;

var google = require("googleapis");

// Load the service account key JSON file.
var serviceAccount = require("./xxxxxxxx.json");

// Define the required scopes.
var scopes = [
  "https://www.googleapis.com/auth/userinfo.email",
  "https://www.googleapis.com/auth/firebase.database"
];

// Authenticate a JWT client with the service account.
var jwtClient = new google.auth.JWT(
  serviceAccount.client_email,
  null,
  serviceAccount.private_key,
  scopes
);

// Use the JWT client to generate an access token.
jwtClient.authorize(function(error, tokens) {
  if (error) {
    console.log("Error making request to generate access token:", error);
  } else if (tokens.access_token === null) {
    console.log("Provided service account does not have permission to generate access tokens");
  } else {
    var accessToken = tokens.access_token;
     console.log(accessToken);
    // See the "Using the access token" section below for information
    // on how to use the access token to send authenticated requests to
    // the Realtime Database REST API.
  }
});

and 2.: 和2 .:

Generate a Custom Access Token on the server and the client side (mixed into one here for testing): 在服务器和客户端上生成自定义访问令牌(在此处混合在一起进行测试):

var google = require("googleapis");

var serviceAccount = require("xxxxxxxx.json");

var admin = require("firebase-admin");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "xxxx"
});

var firebase = require("firebase");


  var config = {
    apiKey: "xxxx",
    authDomain: "xxxxxx",
    databaseURL: "xxxx",
    projectId: "xxxx",
    storageBucket: "xxx",
    messagingSenderId: "xxxxx"
  };

firebase.initializeApp(config);


var uid = "some-uid";


var additionalClaims = {
  premiumAccount: true
};



admin.auth().createCustomToken(uid/*, additionalClaims*/)
  .then(function(customToken) {




    // begin client use, actually in browser. Here for testing.

      firebase.auth().signInWithCustomToken(customToken).then(
        function(d){

            var  fbref = firebase.database().ref('/users/'+uid  );

              fbref.set({
                username: "name",
                email: "email",
                profile_picture : "imageUrl"
              }).catch(function(error) {
              console.log("Kann nicht setzen: " + error);
            });

          var userId = firebase.auth().currentUser.uid;

          return firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) {

            console.log(snapshot.val());
          });
        }    
      ).catch(function(error) {
      var errorCode = error.code;
      var errorMessage = error.message;

    });

    // end client use

  })
  .catch(function(error) {
    console.log("Error creating custom token:", error);
  });

I'd like to know what package I need, and where I can obtain documentation for it. 我想知道我需要什么软件包,以及在哪里可以获取其文档。

At least a sketchy translation into a dart program would be helpful. 至少将草图粗略地翻译为飞镖程序会有所帮助。

The sulution is to find a jwt library that uses RSA for signing the token, RSA seems to be the less popular alternative among existing libraries. 解决的办法是找到一个使用RSA对令牌进行签名的jwt库,RSA在现有库中似乎不太受欢迎。

pubspec.yaml: pubspec.yaml:

dependencies:
  firebase: "4.2.0+1"
  just_jwt: "1.3.1"

createCustomToken.dart: createCustomToken.dart:

import 'dart:async';
import 'dart:convert' as convert;
import 'package:just_jwt/just_jwt.dart' as jj;

Future main() async {

  String client_email = "xxxxxxx";

  final DateTime issuedAt = new DateTime.now();
  final DateTime expiresAt = issuedAt.add(const Duration(minutes: 30));

  String uid = "some-uid";
  jj.EncodedJwt encodedJwt;
  Map<String, Object> payload = {
    "iss": client_email,
    "sub": client_email,
    "aud":        "xxxxxx",
    "iat": (issuedAt.millisecondsSinceEpoch / 1000).floor(),
    "exp": (issuedAt.millisecondsSinceEpoch / 1000).floor() + (60 * 30),
    "uid": uid,
    "claims": {}
  };
  var sign = jj.toTokenSigner(jj.createRS256Signer("xxxxxxxxxx"));
  Map<String, jj.TokenSigner> signer = {'RS256': sign};
  jj.Encoder encoder = new jj.Encoder(jj.composeTokenSigners(signer));
  jj.Jwt jwt = new jj.Jwt.RS256(payload);
  encodedJwt = await encoder.convert(jwt);
  print(encodedJwt.toString());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM