简体   繁体   English

Android Firebase Rest API身份验证

[英]Android Firebase Rest API Authentication

I'm currently developing an app using Firebase Realtime database, however I've opted to omit using the SDK to retrieve data from the db. 我目前正在使用Firebase实时数据库开发应用程序,但是我选择省略使用SDK从数据库中检索数据。 The reason being I don't want my code to be so closely tied with FireBase as once the app is built the api itself will be moving to a custom rest based api. 原因是我不希望我的代码与FireBase紧密相关,因为一旦应用程序构建,api本身将转移到基于自定义休息的api。

I've implemented the api calls using REST with Firebase as per the docs without issue - POST, GET, DELETE etc.. 我根据文档使用REST和Firebase实现了api调用,没有问题 - POST,GET,DELETE等。

The issue I have is if I enable any kind of authentication on the database, according to the docs I need to send "access_token" with the request however I don't know where to retrieve this from. 我遇到的问题是,如果我在数据库上启用任何类型的身份验证,根据我需要发送带有请求的“access_token”的文档,但是我不知道从哪里检索它。 firebaseUser.getToken(true) returns what looks to be a JWT token that isn't recognised if I send it as "access_token" . firebaseUser.getToken(true)返回看起来像JWT令牌的内容,如果我将其作为"access_token"发送,则无法识别该令牌。 I get 401 Unauthorized 我得到401 Unauthorized

I also followed the instructions to setup a service account which seems to generate a token that works but then it doesn't uniquely identify the user. 我还按照说明设置了一个服务帐户,该帐户似乎生成了一个有效的令牌,但它并没有唯一地标识用户。

So my question is can anyone point me in the direction of how to get the required access token that identifies which user is accessing that api? 所以我的问题是,任何人都可以指出我如何获得所需的访问令牌,以识别哪个用户正在访问该API? The login options my Firebase project supports are Google, Facebook & Twitter. 我的Firebase项目支持的登录选项是Google,Facebook和Twitter。

If you are looking for the different tokens or IDs from each one of the different authentication modes, you should implement differences APIs for each one of them: 如果要从每种不同的身份验证模式中查找不同的令牌或ID,则应为每个身份验证模式实现差异API:

REST API REST API

To retrieve an access token you need to use a service account. 要检索访问令牌,您需要使用服务帐户。 Please see the guide for using Google Service Accounts. 请参阅使用Google服务帐户的指南。 You can create a service account credential in your Firebase project from the Service Accounts section of the Firebase console. 您可以从Firebase控制台的“服务帐户”部分在Firebase项目中创建服务帐户凭据。

As an example, one way to generate an appropriate oauth2 token is with the Java google-api-client. 例如,生成适当的oauth2令牌的一种方法是使用Java google-api-client。

GoogleCredential googleCred = GoogleCredential.fromStream(new FileInputStream("service_account.json"));
GoogleCredential scoped = googleCred.createScoped(
    Arrays.asList(
      "https://www.googleapis.com/auth/firebase.database",
      "https://www.googleapis.com/auth/userinfo.email"
    )
);
scoped.refreshToken();
String token = scoped.getAccessToken();

A successful request will be indicated by a 200 OK HTTP status code. 成功的请求将由200 OK HTTP状态代码指示。 The response contains the data being retrieved: 响应包含要检索的数据:

{ "first": "Jack", "last": "Sparrow" }

The Database REST API accepts access_token=<TOKEN> on the query string or header Authorization: Bearer <TOKEN> to authenticate a request with a service account. 数据库REST API接受查询字符串上的access_token=<TOKEN>或标题Authorization: Bearer <TOKEN>以使用服务帐户验证请求。

The following example demonstrates how you might use this with a database containing user names. 以下示例演示了如何在包含用户名的数据库中使用它。 You would replace [PROJECT_ID] with the identifier of your Firebase project. 您可以使用Firebase项目的标识符替换[PROJECT_ID]

Facebook Facebook的

You should add the Facebook SDK to your application and implement a LoginButton and LoginManager items asking for some information as public_profile an email. 您应该将Facebook SDK添加到您的应用程序并实现LoginButtonLoginManager项目,要求提供一些信息作为public_profile一封电子邮件。 It's pretty annoying to work with Facebook SDK . 使用Facebook SDK非常烦人。 An Example code about how to add it is this: 有关如何添加它的示例代码如下:

// Initialize Facebook Login button
mCallbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        Log.d(TAG, "facebook:onSuccess:" + loginResult);
        handleFacebookAccessToken(loginResult.getAccessToken());
    }

    @Override
    public void onCancel() {
        Log.d(TAG, "facebook:onCancel");
        // ...
    }

    @Override
    public void onError(FacebookException error) {
        Log.d(TAG, "facebook:onError", error);
        // ...
    }
});

Also, inside the developers console from Facebook you should create an account, configure a new project with your app package name and add the SHA keys for debug and release versions of your app. 此外,在Facebook的开发人员控制台中 ,您应该创建一个帐户,使用您的应用程序包名称配置一个新项目,并为您的应用程序的调试和发布版本添加SHA密钥。 After do all this things, you will successfully retrieve a token from the LoginResult object using the method getAccessToken() 完成所有这些操作后,您将使用getAccessToken()方法从LoginResult对象成功检索令牌

You can read more about this in the official documentation . 您可以在官方文档中阅读更多相关信息。

Google 谷歌

Google is easier because it is already connected to Firebase, you should add to your Gradle google play services and add a google services JSON file already configured to your application. Google更容易,因为它已经连接到Firebase,您应该添加到Gradle google play services并添加已配置到您的应用程序的google services JSON文件。 You can get it from your Firebase console. 您可以从Firebase控制台获取它。

After this, you will need to configure a GoogleSignInOptions item using the id from your JSON file: 在此之后,您需要使用JSON文件中的id配置GoogleSignInOptions项:

// Configure Google Sign In
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();

After this you will just need to make a intent to the GoogleSignInApi in your app and wait for the onActivityResult callback: 在此之后,您只需要在应用中对GoogleSignInApi发出意图并等待onActivityResult回调:

private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = result.getSignInAccount();
                firebaseAuthWithGoogle(account);
            } else {
                // Google Sign In failed, update UI appropriately
                // ...
            }
        }
    }

After this you will be able to retrieve the token from the GoogleSignInAccount item. 在此之后,您将能够从GoogleSignInAccount项目中检索令牌。 Remember to configure different SHA keys for debug or release versions of your app or Google Sign in will stop working in release version. 请记住为应用的调试或发布版本配置不同的SHA密钥,否则Google登录将停止在发布版本中运行。

You can read more about this in the official Firebase documentation 您可以在官方Firebase文档中阅读有关此内容的更多信息

Twitter 推特

About Twitter, I didn't work with Twitter, so I can't really help you at the moment, but I suggest you to check the Twitter developer documentation and the firebase Twitter implementation post . 关于Twitter,我没有使用Twitter,所以我现在无法真正帮助你,但我建议你查看Twitter开发者文档firebase Twitter实现帖子

I will try to edit this when I will make some pocs at home checking how it works. 我会尝试编辑这个,当我在家里做一些pocs检查它是如何工作的。

About Firebase tokens 关于Firebase令牌

Another good point to have knowledge about is the Firebase id tokens, which are unique per user and connection in your app, allowing you to check if the same account is trying to log from different devices at the same time, or send FCM Cloud Messages to use online notification in your app. 了解Firebase id令牌的另一个好处是,每个用户和应用程序中的连接都是唯一的,允许您检查同一帐户是否尝试同时从不同设备登录,或者发送FCM Cloud Messages在您的应用中使用在线通知。

To retrieve it, you should use the FirebaseInstanceId object using the API and the method FirebaseInstanceId.getInstance() . 要检索它,您应该使用API​​和方法FirebaseInstanceId.getInstance()来使用FirebaseInstanceId对象。 This will retrieve you a FirebaseInstance unique ID for your user when he/she login in your app. 当用户登录您的应用时,这将为您的用户检索FirebaseInstance唯一ID。

You can retrieve his token with the idInstance.getToken() and store it whenever you want in your application to check it and manage it in the way that you want. 您可以使用idInstance.getToken()检索其令牌,并在应用程序中随时存储它以检查它并以您希望的方式进行管理。

The Firebase documentation about this is not pretty clear, so I recommend you to use the next link , it helped me a lot to implement it in my app. 关于这个Firebase文档不是很清楚,所以我建议你使用下一个链接 ,它帮助我在我的应用程序中实现它很多。

You can add a table in your server for USER. 您可以在服务器中为USER添加表。 In that table, add fields like firebase_token, google_token, fb_token, etc. As you register in all those services one by one, update the fields in the table for user. 在该表中,添加firebase_token,google_token,fb_token等字段。当您逐个注册所有这些服务时,请更新表中的字段以供用户使用。 In this way you can maintain the users_info as well as all the required tokens. 通过这种方式,您可以维护users_info以及所有必需的令牌。

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

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