GVKun编程网logo

Firebase Auth JS / PHP

23

如果您想了解FirebaseAuthJS/PHP的知识,那么本篇文章将是您的不二之选。同时我们将深入剖析android–FirebaseUIAuth库:Google登录失败:W/AuthMethodP

如果您想了解Firebase Auth JS / PHP的知识,那么本篇文章将是您的不二之选。同时我们将深入剖析android – FirebaseUI Auth库:Google登录失败:W / AuthMethodPicker:Firebase登录失败、angularjs – Firebase $authWithOAuthRedirect在没有页面刷新的情况下不会调用$onAuth、angularjs – 来自Facebook的$authWithOAuthRedirect之后,Firebase $onAuth的authData错误、com.google.firebase.auth.AuthCredential的实例源码的各个方面,并给出实际的案例分析,希望能帮助到您!

本文目录一览:

Firebase Auth JS / PHP

Firebase Auth JS / PHP

我受命为基于Firebase的Android应用程序构建Web界面。我有一些与数据库交互的端点(云函数)。要访问这些端点,我需要使用电子邮件和密码[1]对用户进行身份验证,检索accessToken
[2]并授权使用Authorization: Bearer {accessToken}标头对端点的每个请求进行授权。

我使用php并竭尽全力想如何在我的应用程序中管理经过身份验证的用户。

我通过php会话中的ajax传输accessToken,以将cURL请求签名到端点。显然,除了使用firebase JS
auth之外,别无其他方法(据我所知[4])。

我的问题是: 是否足以将其保存accessToken在php会话中,并通过ajax
POST请求将其与每个页面加载进行比较(请参见下面的代码)?在php中,有什么更健壮的策略来解决这个问题?

编辑:一位用户指出,使用带有JWT令牌的经典php会话没有多大意义,我读了有关该主题的文章。那么关于Firebase-
这是要考虑的事情吗? https://firebase.google.com/docs/auth/admin/manage-
cookies

Firebase
Auth为依赖会话cookie的传统网站提供服务器端会话cookie管理。与客户端短暂的ID令牌相比,此解决方案具有多个优点,客户端短暂的ID令牌可能每次需要使用重定向机制来在到期时更新会话cookie:

这是我得到的:

1.登录页面

如Firebase示例中所述[3]

function initApp() {  firebase.auth().onAuthStateChanged(function (user) {    if (user) {      // User is signed in.      // obtain token, getIdToken(false) = no forced refresh      firebase.auth().currentUser.getIdToken(false).then(function (idToken) {        // Send token to your backend via HTTPS        $.ajax({          type: ''POST'',          url: ''/auth/check'',          data: {''token'': idToken},          complete: function(data){            // data = {''target'' => ''/redirect/to/route''}            if(getProperty(data, ''responseJSON.target'', false)){              window.location.replace(getProperty(data, ''responseJSON.target''));            }          }        });        // ...      }).catch(function (error) {        console.log(error);      });    } else {      // User Signed out      $.ajax({        type: ''POST'',        url: ''/auth/logout'',        complete: function(data){          // data = {''target'' => ''/redirect/to/route''}          if(getProperty(data, ''responseJSON.target'', false)){            // don''t redirect to itself            // logout => /            if(window.location.pathname != getProperty(data, ''responseJSON.target'', false)){              window.location.replace(getProperty(data, ''responseJSON.target''));            }          }        }      });      // User is signed out.    }  });}window.onload = function () {  initApp();};

2.一个PHP控制器来处理身份验证请求

public function auth($action){  switch($action) {    // auth/logout    case ''logout'':      unset($_SESSION);      // some http status header and mime type header      echo json_encode([''target'' => ''/'']); // / => index page    break;    case ''check'':      // login.      if(! empty($_POST[''token'']) && empty($_SESSION[''token''])){        // What if I send some bogus data here? The call to the Endpoint later would fail anyway        // But should it get so far?        $_SESSION[''token''] = $_POST[''token''];        // send a redirect target back to the JS        echo json_encode([''target'' => ''/dashboard'']);        break;      }      if($_POST[''token''] == $_SESSION[''token'']){        // do nothing;        break;      }    break;  }}

3.主控制器

// pseudo codeclass App{  public function __construct()  {    if($_SESSION[''token'']){      $client = new \GuzzleHttp\Client();      // $user now holds all custom access rights within the app.      $this->user = $client->request(        ''GET'',         ''https://us-centralx-xyz.cloudfunctions.net/user_endpoint'',        [''headers'' =>                 [                    ''Authorization'' => "Bearer {$_SESSION[''token'']}"                ]            ]        )->getBody()->getContents();    }else{      $this->user = null;    }  }  public function dashboard(){    if($this->user){      var_dump($this->user);    }else{      unset($_SESSION);      // redirect to ''/''     }  }}

注意:我知道这个sdk https://github.com/kreait/firebase-
php,我在那里读了很多文章,在SO上的文章里也读到很多,但是我很困惑,因为这里有关于完全管理员的讨论。权限等。我实际上仅与基于Firebase的端点进行交互(加上firebase
auth和firestore)。而且我仍然在php 5.6上:-/

谢谢你的时间!

  • [1]:https://firebase.google.com/docs/auth/web/password-auth
  • [2]:https : //firebase.google.com/docs/reference/js/firebase.User#getIdToken
  • [3]:https://github.com/firebase/quickstart-js/blob/master/auth/email-password.html
  • [4]:https://github.com/kreait/firebase-php/issues/159#issuecomment-360225655

答案1

小编典典

我不得不承认,firebase文档和示例的复杂性以及不同的服务使我非常困惑,以至于我认为只能通过JavaScript进行Web身份验证。错了
至少对于我来说,我只是 使用电子邮件和密码登录检索Json Web令牌(JWT)
,以对Firebase云功能的所有调用进行签名。无需处理奇怪的Ajax请求或通过JavaScript设置令牌cookie,我只需要调用FirebaseAuth REST API

这是使用Fatfreeframework的最小情况:

登录表单

<form action="/auth" method="post">    <input name="email">    <input name="password">    <input type="submit"></form>

路线

$f3->route(''POST /auth'', ''App->auth'');

控制者

class App{    function auth()    {        $email = $this->f3->get(''POST.email'');        $password = $this->f3->get(''POST.password'');        $apiKey = ''API_KEY''; // see https://firebase.google.com/docs/web/setup        $auth = new Auth($apiKey);        $result = $auth->login($email,$password);        if($result[''success'']){            $this->f3->set(''COOKIE.token'',$result[''idToken'']);            $this->f3->reroute(''/dashboard'');        }else{            $this->f3->clear(''COOKIE.token'');            $this->f3->reroute(''/'');        }    }}

<?phpuse GuzzleHttp\Client;class Auth{    protected $apiKey;    public function __construct($apiKey){        $this->apiKey = $apiKey;    }    public function login($email,$password)    {        $client = new Client();        // Create a POST request using google api        $key = $this->apiKey;        $responsee = $client->request(            ''POST'',            ''https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key='' . $key,            [                ''headers'' => [                    ''content-type'' => ''application/json'',                    ''Accept'' => ''application/json''                ],                ''body'' => json_encode([                    ''email'' => $email,                    ''password'' => $password,                    ''returnSecureToken'' => true                ]),                ''exceptions'' => false            ]        );        $body = $responsee->getBody();        $js = json_decode($body);        if (isset($js->error)) {            return [                ''success'' => false,                ''message'' => $js->error->message            ];        } else {            return [                ''success'' => true,                ''localId'' => $js->localId,                ''idToken'' => $js->idToken,                ''email'' => $js->email,                ''refreshToken'' => $js->refreshToken,                ''expiresIn'' => $js->expiresIn,            ];        }    }}

学分

android – FirebaseUI Auth库:Google登录失败:W / AuthMethodPicker:Firebase登录失败

android – FirebaseUI Auth库:Google登录失败:W / AuthMethodPicker:Firebase登录失败

使用可用的在线文档和此视频:https://www.youtube.com/watch?v=0ucjYG_JrEE,我正在尝试开始应用新的UI Auth库.邮件登录效果很好,Google不会登录:它会发出警告,用户界面会一直显示“正在加载…”对话框.

final FirebaseAuth auth = FirebaseAuth.getInstance();
        auth.addAuthStateListener(new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser usr = firebaseAuth.getCurrentUser();

                if (usr != null){
                    Log.d( TAG, "User signed in correctly: " + usr );
                    auth.removeAuthStateListener( this );
                } else {
                    //signed out
                    Log.d( TAG, "User is not signed in" );
                    auth.removeAuthStateListener( this );

                    startActivityForResult( AuthUI.getInstance().createSignInIntentBuilder()
                            .setTheme( R.style.AppBaseTheme )
                            .setProviders(
                                    AuthUI.EMAIL_PROVIDER,
                                    AuthUI.GOOGLE_PROVIDER
                            ).build(), RC_SIGN_IN );


                }
            }
        });

输出:

05-21 13:49:33.595 25005-25005/com.xxx.xxx W/AuthMethodPicker: Firebase login unsuccessful

更多日志输出会有所帮助.请注意,这只发生在导入的Firebase项目上,而不是新创建的Firebase项目上.

更新:刚刚在控制台中发现了这个:

05-22 14:29:58.178 10075-10310/? V/BaseAuthAsyncoperation: access token request successful
05-22 14:29:58.179 10075-10310/? V/AuthAccountOperation: id token is requested.
05-22 14:29:58.758 10075-10310/? E/TokenRequestor: You have wrong OAuth2 related configurations, please check. Detailed error: INVALID_AUDIENCE
05-22 14:29:58.758 10075-10310/? D/AuthAccountOperation: id token request Failed.

解决方法:

刚刚找到了这个问题的原因:我的应用程序使用了一个意外的(错误的)debug.keystore来签署调试APK …在我的构建中指向正确的debug.keystore后,一切都按预期工作!

(回答发现感谢这个主题:Android Studio – debug keystore)

附:感谢Google / Firebase团队提供的UI Auth解决方案:这是一项伟大的改进!

angularjs – Firebase $authWithOAuthRedirect在没有页面刷新的情况下不会调用$onAuth

angularjs – Firebase $authWithOAuthRedirect在没有页面刷新的情况下不会调用$onAuth

我有一个简单的Firebase Facebook OAuth登录设置,如下面的 official tutorial for Ionic Firebase Facebook登录.

问题是,一旦我点击登录与Facebook按钮,我被重定向到Facebook,我登录,然后我被重定向回我的应用程序.但问题是我留在登录页面.奇怪的是,如果我通过按F5来物理刷新我的浏览器(使用离子服务测试)onAuth触发器,我将被重定向到Items页面.如果我不刷新浏览器,则不会调用onAuth.

有人有这个问题吗?你是怎么解决的?

请注意,是的,我做了我的研究(并且稍微开始失去它),但无法让它发挥作用.我搜索了SO,尝试使用google群组的$timeout,试图调用$scope.$apply(),但都无济于事 – 所以请帮我弄清楚我做错了什么?

.controller('AppCtrl',function($scope,Items,Auth,$state,$ionicHistory) {
    $scope.login = function(provider) {
        Auth.$authWithOAuthRedirect(provider).then(function(authData) {

        }).catch(function(error) {
            if (error.code === "TRANSPORT_UNAVAILABLE") {
                Auth.$authWithOAuthPopup(provider).then(function(authData) {
                    
                });
            } else {
                console.log(error);
            }
        });
    };

    $scope.logout = function() {
        Auth.$unauth();
        $scope.authData = null;

        $window.location.reload(true);
    };

    Auth.$onAuth(function(authData) {
        if (authData === null) {
            console.log("Not logged in yet");
            $state.go('app.login');
        } else {
            console.log("Logged in as",authData.uid);
            
            $ionicHistory.nextViewOptions({
                disableBack: true
              });
            $state.go('app.items');
        }
        $scope.authData = authData; // This will display the user's name in our view
    });
})
<ion-view view-title="Members area">
    <ion-content padding="true">
        <div ng-if="!authData">
            <buttonng-click="login('facebook')">Log In with Facebook</button>  
        </div>       
        
        <div ng-if="authData.facebook">
            <div>
                <div>Hello {{authData.facebook.displayName}}!</div>                
            </div>

            <buttonng-click="logout()">Log out</button>
        </div>        

    </ion-content>
</ion-view>

编辑:我通过使用$timeout来解决它:

$timeout(function(){
    Auth.$onAuth(function(authData) {
        if (authData === null) {
            console.log("Not logged in yet");
            $state.go('app.login');
        } else {
            console.log("Logged in as",authData.uid);

            $ionicHistory.nextViewOptions({
                disableBack: true
              });
            $state.go('app.items');
        }
        $scope.authData = authData; // This will display the user's name in our view
    });
},3000);

然而,这只是感觉不对(温和地放),并且必须有更好的方法,所以请建议一个.此外,我注意到高达3秒的延迟几乎不够(我发现建议500ms的资源很少就足够了,但在我的情况下,情况并非如此).

解决方法

发表在github上的问题,但也会在这里回复.

这只发生在使用$authWithOAuthRedirect的浏览器中.该示例适用于cordova应用程序,因此这不应该是一个问题.

但如果你真的需要它,你可以跳过重定向并使用弹出窗口.

Auth.$authWithOAuthPopup(authMethod).then(function(authData) {
      console.dir(authData);
    });

angularjs – 来自Facebook的$authWithOAuthRedirect之后,Firebase $onAuth的authData错误

angularjs – 来自Facebook的$authWithOAuthRedirect之后,Firebase $onAuth的authData错误

我正在尝试使用Facebook登录验证我的Firebase(Angularfire)应用程序的用户.

当我使用弹出窗口进行身份验证时,一切都按预期工作,但支持尽可能多的浏览器(iOS上的Chrome不支持弹出窗口,例如)我想要使用重定向进行身份验证($authWithOAuthRedirect) .

我已经确认我在Facebook中的设置是正确的(我的应用程序ID和秘密,例如)但是当我在使用重定向进行Facebook身份验证后重定向回我的应用程序时,$onAuth会触发,但我没有我的Facebook authData.

相反,我有匿名authData.有点背景;如果没有以其他方式验证所有用户,则匿名进行身份验证(例如,使用Facebook).

我无法找到为什么会这样 – 用户现在应该通过Facebook验证,并拥有Facebook authData.

在某些情况下,我的代码的例外情况如下:

用户单击登录按钮时触发

function logIn () {
    firebaseAuth
        .$authWithOAuthRedirect('facebook',function (error) {
            if (error) {
                console.log(error);
            }
        });
}

$onAuth(在我的Angular应用程序运行中)

function run ($rootScope,firebaseAuth,sessionStore) {
    $rootScope
        .$on('$routeChangeError',function (event,next,prev,error) {
            if (error === 'AUTH_required') {
                console.log(error);
            }
        });

    $rootScope
        .$on('$routeChangeSuccess',current,prev) {
            $rootScope.title = current.$$route.title;
        });

    firebaseAuth
        .$onAuth(onAuth);

    function onAuth (authData) {
        console.log(authData);
    }
}

路由解析器以匿名方式对用户进行身份验证

function sessionState ($q,firebaseAuth) {
    var deferred = $q.defer();

    firebaseAuth
        .$requireAuth()
        .then(deferred.resolve,guest);

    return deferred.promise;

    function guest () {
        firebaseAuth
            .$authAnonymously()
            .then(deferred.resolve,rejected);
    }

    function rejected () {
        deferred.reject('AUTH_required');
    }
}

路由解析器(sessionState)检查用户是否已经过身份验证,如果没有,则尝试匿名验证用户.

在Facebook身份验证重定向之后,用户将已经过身份验证,因此无需进行匿名身份验证.

但是,它们似乎是?由于$onAuth将authData记录到控制台,因此它是匿名的.

任何帮助都将非常感谢!我确信它与我的路由解析器有关,因为弹出式身份验证工作正常(路由已经解决).

编辑:我试图完全删除我的路由解析器,以防它导致问题,但它没有任何区别.用户只是“未经身份验证”,而不是通过Facebook($authWithOAuthRedirect)或匿名进行身份验证.

更新:我尝试使用Twitter和重定向传输进行身份验证,我遇到了完全相同的问题.我也尝试使用端口80,而不是端口3000,我的应用程序在本地提供,但没有快乐.

更新:当我在我的应用程序中关闭html5Mode模式 – 现在路由以#s开头 – $authWithOAuthRedirect完美运行.由此我只能假设$authWithOAuthRedirect不支持AngularJS的html5Mode.任何人都可以确认这是一个问题,还是我需要更改我的代码以支持html5Mode和authWithOAuthRedirect?

示例REPO以下是演示此问题的示例repo:https://github.com/jonathonoates/myapp

查看dist目录 – 您应该能够下载并运行应用程序以重现问题.在scripts / main.js中是应用程序的JS;我添加了几条评论,但这是非常自我解释的.

要重现问题:点击“Facebook登录”按钮,您将被重定向到Facebook进行身份验证. FB会将你重定向回应用程序,但这里存在问题 – 你将不会被验证,并且返回的authData将为null – 你会在控制台中看到这一点

更新:当我在html5Mode中添加hashPrefix时,例如

$locationProvider
    .html5Mode(true)
    .hashPrefix('!');

该应用程序正如我所期望的那样 – 通过Facebook验证和重定向传输工作.

几个小小的但是:

>网址有#?附加到它,并在浏览器的历史记录中可用/可见.
>这会用#重写URL!在不支持History.pushState(html5Mode)的浏览器中,由于’hashbang’,一些不太高级的搜索引擎可能会寻找HTML片段.

我将研究从Facebook重定向而不是使用hashPrefix来劫持URL.在URL中有一个__firebase_request_key,它可能很重要,例如

http://localhost:3000/#%3F&__firebase_request_key=

解决方法

看起来这确实是你怀疑Firebase和AngularJS的html5mode之间的不兼容.在重定向流程结束时,Firebase将URL保留为“ http://…/#?”,而Angular显然不喜欢这样,所以它重定向到“ http://…/”这个重定向会中断Firebase(当我们尝试重新加载页面时对后端进行身份验证)因此无法完成身份验证过程.

我已经做了一个实验性修复,确保我们在重定向流结束时将URL恢复为“http://…/#”,Angular很满意,从而防止了有问题的重定向.如果你愿意,你可以在这里抓住它:https://mike-shared.firebaseapp.com/firebase.js

我将确保此修复程序进入下一版本的JS客户端.您可以留意我们的changelog以查看它何时发布.

com.google.firebase.auth.AuthCredential的实例源码

com.google.firebase.auth.AuthCredential的实例源码

项目:BuddiesGo    文件:SignInActivity.java   
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG,"firebaseAuthWithGooogle:" + acct.getId());
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);
    mFirebaseAuth.signInWithCredential(credential)
            .addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d(TAG,"signInWithCredential:onComplete:" + task.isSuccessful());

                    // If sign in fails,display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        Log.w(TAG,"signInWithCredential",task.getException());
                        Toast.makeText(SignInActivity.this,"Authentication Failed.",Toast.LENGTH_SHORT).show();
                    } else {
                        startActivity(new Intent(SignInActivity.this,MainActivity.class));
                        finish();
                    }
                }
            });
}
项目:friendlychat-android    文件:SignInActivity.java   
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG,"firebaseAuthWithGoogle:" + acct.getId());
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),MainActivity.class));
                        finish();
                    }
                }
            });
}
项目:School1-Android    文件:SigninActivity.java   
@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data) {
    super.onActivityResult(requestCode,resultCode,data);

    if (requestCode == RC_SIGNIN_GOOGLE) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        if (result.isSuccess()) {
            GoogleSignInAccount account = result.getSignInAccount();
            AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(),null);
            auth.signInWithCredential(credential)
                    .addOnCompleteListener(this,this);
        } else
            onFailure(result.getStatus().toString());
    } else
        callbackManager.onActivityResult(requestCode,data);
}
项目:Quadro    文件:AuthActivity.java   
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
    Log.d(TAG,"firebaseAuthWithGoogle:" + account.getId());
    showProgressDialog();
    AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(),null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this,"signInWithCredential:onComplete:" + task.isSuccessful());
                    hideProgressDialog();
                    // If sign in fails,task.getException());
                        Toast.makeText(AuthActivity.this,R.string.auth_Failed,Toast.LENGTH_SHORT).show();
                    }
                    // ...
                }
            });
}
项目:GodotFireBase    文件:FacebookSignIn.java   
public void handleAccesstoken(Accesstoken token) {
    Utils.d("FB:Handle:Accesstoken: " + token.getToken());
    // showProgressDialog();

    AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());

    mAuth.signInWithCredential(credential)
    .addOnCompleteListener(activity,new OnCompleteListener<AuthResult>() {

        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            Utils.d("FB:signInWithCredential:onComplete:" + task.isSuccessful());

            // If sign in fails,display a message to the user. If sign in succeeds
            // the auth state listener will be notified and logic to handle the
            // signed in user can be handled in the listener.

            if (!task.isSuccessful()) {
                Utils.w("FB:signInWithCredential" + 
                    task.getException().toString());
            }

            // hideProgressDialog();
        }
    });
}
项目:GodotFireBase    文件:GoogleSignIn.java   
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {

        Utils.d("Google:FirebaseAuthWithGoogle:" + acct.getId());

        // FireBase.showProgressDialog();

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);
        mAuth.signInWithCredential(credential)
        .addOnCompleteListener(activity,new OnCompleteListener<AuthResult>() {

            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                Utils.d(
                "Google:SignInWithCredential:onComplete:" + task.isSuccessful());

                // If sign in fails,display a message to the user. If sign in succeeds
                // the auth state listener will be notified and logic to handle the
                // signed in user can be handled in the listener.
                if (!task.isSuccessful()) {
                    Utils.w("Google:SignInWithCredential:" + task.getException());
                }

                // FireBase.hideProgressDialog();
            }
        });
    }
项目:GodotFireBase    文件:TwitterSignIn.java   
private void handleTwitterSession(TwitterSession session) {
    Utils.d("Twitter:HandleSession:" + session);

    AuthCredential credential = TwitterauthProvider.getCredential(
    session.getAuthToken().token,session.getAuthToken().secret);

    mAuth.signInWithCredential(credential)
    .addOnCompleteListener(activity,new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
                // Sign in success,update UI with the signed-in user's information
                Utils.d("signInWithCredential:success");
            } else {
                // If sign in fails,display a message to the user.
                Utils.w("signInWithCredential:failure: " + task.getException());
            }

            // ...
        }
    });
}
项目:VR-One    文件:SignInActivity.java   
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG,"firebaseAuthWithGoogle:" + acct.getId());

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),Toast.LENGTH_SHORT).show();
                    }
                }
            });
}
项目:Viajes    文件:LoginPresenter.java   
@Override
public void firebaseAuthWithGoogle(final GoogleSignInAccount account) {
    final AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(),null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(mContext,new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    mLoginView.dismissprogress();
                    if (!task.isSuccessful()) {
                        mLoginView.showErrorMessage("Error In Create User");
                    } else {
                        FirebaseAuth.getInstance().getCurrentUser().linkWithCredential(credential);
                        String uid = task.getResult().getUser().getUid();
                        String name = account.getdisplayName();
                        String email = account.getEmail();
                        String imageProfileUrl = getHighQualityImage(account.getPhotoUrl());
                        createuserInFirebaseHelper(uid,new User(name,email,imageProfileUrl));
                        mLoginView.showMain();
                    }
                }
            });
}
项目:cda-app    文件:LoginActivity.java   
private void accessgithubLoginData(String accesstoken,User githubUser){
    String provider = "github";
        AuthCredential credential = GithubAuthProvider.getCredential(accesstoken);
        credential = provider.equalsIgnoreCase("github") ? GithubAuthProvider.getCredential( accesstoken ) : credential;
        //user.saveProviderSP( LoginActivity.this,provider );
        mFirebaseAuth.signInWithCredential(credential)
                .addOnCompleteListener(this,task -> {
                    Log.d(TAG,"signInWithCredential:onComplete:" + task.isSuccessful());
                    saveUserGithubData("name",githubUser.name);
                    saveUserGithubData("email",githubUser.email);
                    saveUserGithubData("company",githubUser.company);
                    saveUserGithubData("createdAt",String.valueOf(githubUser.created_at));
                    saveUserGithubData("bio",githubUser.bio);
                    saveUserGithubData("location",githubUser.location);
                    saveUserGithubData("numOfRepos",String.valueOf(githubUser.public_repos));
                    saveUserGithubData("followers",String.valueOf(githubUser.followers));
                    callMainActivity();
                    if (!task.isSuccessful()) {
                        Log.w(TAG,task.getException());
                        Toast.makeText(LoginActivity.this,Toast.LENGTH_SHORT).show();
                    }
                });
}
项目:BookED    文件:Authentication.java   
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG,task.getException());
                        Toast.makeText(Authentication.this,Toast.LENGTH_SHORT).show();
                    }
                    // ...
                }
            });
}
项目:friendlypix-android    文件:ProfileActivity.java   
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG,null);
    showProgressDialog(getString(R.string.profile_progress_message));
    mAuth.signInWithCredential(credential)
            .addOnSuccessListener(this,new OnSuccessListener<AuthResult>() {
                @Override
                public void onSuccess(AuthResult result) {
                    handleFirebaseAuthResult(result);
                }
            })
            .addOnFailureListener(this,new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    FirebaseCrash.logcat(Log.ERROR,TAG,"auth:onFailure:" + e.getMessage());
                    handleFirebaseAuthResult(null);
                }
            });
}
项目:cordova-plugin-firebase-sdk    文件:AuthCredentials.java   
public static AuthCredential getCredential(final JSONObject credential) throws Exception {
    final String providerId = credential.getString("provider");
    AuthCredential authCredential;

    if (providerId.equals(EmailAuthProvider.PROVIDER_ID)) {
        authCredential = getEmailAuthCredential(credential);
    } else if (providerId.equals(FacebookAuthProvider.PROVIDER_ID)) {
        authCredential = getFacebookAuthCredential(credential);
    } else if (providerId.equals(GithubAuthProvider.PROVIDER_ID)) {
        authCredential = getGithubAuthCredential(credential);
    } else if (providerId.equals(GoogleAuthProvider.PROVIDER_ID)) {
        authCredential = getGoogleAuthCredential(credential);
    } else if (providerId.equals(TwitterauthProvider.PROVIDER_ID)) {
        authCredential = getTwitterauthCredential(credential);
    } else {
        throw new Exception("UnkNown provider ID: " + providerId);
    }

    return authCredential;
}
项目:PimPam    文件:LoginInteractorImpl.java   
@Override
public void firebaseAuthWithGoogle(GoogleSignInAccount acct,final OnLoginFinishedListener listener) {

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {

                    // If sign in fails,display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        listener.onLoginGoogleFail();
                    }

                }
            });
}
项目:FastReading    文件:AllBooks.java   
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),task -> {
                if (!task.isSuccessful()) {
                    Toast.makeText(AllBooks.this,R.string.auth_error,Toast.LENGTH_SHORT).show();
                    signInSuccess = null;
                } else {
                    Toast.makeText(AllBooks.this,R.string.sign_in_ok,Toast.LENGTH_SHORT).show();

                    if (signInSignOut != null) {
                        if (mFirebaseAuth.getCurrentUser() != null) {
                            signInSignOut.setTitle(R.string.sign_out);
                        } else {
                            signInSignOut.setTitle(R.string.sign_in);
                        }
                    }

                    if (signInSuccess != null) {
                        signInSuccess.run();
                    }
                }
            });
}
项目:android-paypal-example    文件:LoginActivity.java   
private void handleFacebookAccesstoken(Accesstoken token) {

        Log.d(TAG,"handleFacebookAccesstoken:" + token);

        AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success,update UI with the signed-in user's information
                            Log.d(TAG,"signInWithCredential:success");
                            updateUI(mAuth.getCurrentUser());
                        } else {
                            // If sign in fails,display a message to the user.
                            Log.w(TAG,"signInWithCredential:failure",task.getException());
                            Toast.makeText(LoginActivity.this,Toast.LENGTH_SHORT).show();
                        }

                    }
                });
    }
项目:WaJeun    文件:MainActivity.java   
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG,task.getException());
                        Toast.makeText(MainActivity.this,Toast.LENGTH_SHORT).show();
                    }
                    // ...
                }
            });
}
项目:WaJeun    文件:MainActivity.java   
private void handleFacebookAccesstoken(Accesstoken token) {
    Log.d(TAG,"handleFacebookAccesstoken:" + token);

    AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this,Toast.LENGTH_SHORT).show();
                    }

                    // ...
                }
            });
}
项目:Stalker    文件:AuthenticateFragment.java   
private void handleFacebookAccesstoken(Accesstoken token) {
    Log.d(TAG,"handleFacebookAccesstoken:" + token);
    AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
    fireBaseAuth.signInWithCredential(credential)
            .addOnCompleteListener(getActivity(),"signInWithCredential:onComplete:" + task.isSuccessful());
                    // If sign in fails,task.getException());
                        Toast.makeText(getApplicationContext(),Toast.LENGTH_SHORT).show();
                    }
                }
            });
}
项目:CineReminDay    文件:CRDAuthActivity.java   
private void logInToFirebaseWithGoogleSignIn(GoogleSignInAccount googleSignInAccount) {
    Log.v(CRDAuthActivity.class.getName(),"logInToFirebaseWithGoogleSignIn() called with: " + "googleSignInAccount = [" + googleSignInAccount + "]");

    // Todo VOLKO MAKE USER WAIT

    AuthCredential credential = GoogleAuthProvider.getCredential(googleSignInAccount.getIdToken(),null);

    FirebaseAuth.getInstance()
            .signInWithCredential(credential)
            .addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.v(CRDAuthActivity.class.getName(),"logInToFirebaseWithGoogleSignIn.onComplete() called with: " + "isSuccessful = [" + task.isSuccessful() + "]");

                    // Todo VOLKO MAKE USER DE-WAIT

                    // If sign in succeeds the auth state listener will be notified and logic to handle the signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        onFirebaseConnectionFailed();
                    }
                }
            });
}
项目:trvlr-android    文件:LoginActivity.java   
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG,"firebaseAuthWithGoogle:" + acct.getId());
    showProgressDialog();

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Sign in success,update UI with the signed-in user's information
                        Log.d(TAG,"signInWithCredential:success");
                        startActivity(new Intent(LoginActivity.this,FindConnectionActivity.class));
                        finish();
                    } else {
                        // If sign in fails,display a message to the user.
                        Log.w(TAG,TAG + ": " + "Authentication Failed.",Toast.LENGTH_SHORT).show();
                    }

                    hideProgressDialog();
                }
            });
}
项目:Ae4Team    文件:LoginActivity.java   
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        getUserInfo();
                    } else {
                        Log.w(TAG,Toast.LENGTH_SHORT).show();
                    }
                }
            });
}
项目:Ae4Team    文件:LoginActivity.java   
private void signInWithToken(String token) {
    // credential object from the token
    AuthCredential credential = GithubAuthProvider.getCredential(token);

    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {

                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {

                        writeUserInfo();
                    } else {
                        Log.d("github signInWithToken","@3" + task.getException());
                    }
                }
            });
}
项目:PiPle    文件:LoginActivity.java   
/**
 * Method firebaseAuthWithGoogle
 *
 * Authenticates in Firebase through a Google Account.
 */
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG,Toast.LENGTH_SHORT).show();
                    }
                    else {
                        startActivity(new Intent(LoginActivity.this,HomeActivity.class));
                        finish();
                    }
                }
            });
}
项目:FantaF1    文件:LoginActivity.java   
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG,"firebaseAuthWithGoogle:" + acct.getId());
    progress = ProgressDialog.show(this,"Login...","",true);
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),task -> {
                if (task.isSuccessful()) {
                    currentUser =  mAuth.getCurrentUser();
                    Log.e(TAG,"signInWithCredential:success");
                    loadRooms();
                    updateUI(currentUser);
                } else {
                    Log.e(TAG,task.getException());
                    Toast.makeText(LoginActivity.this,Toast.LENGTH_SHORT).show();
                    updateUI(null);
                }
            });
}
项目:cleanarchitecture-unidirectional    文件:AuthService.java   
@Override
public Completable signInWithGoogle(final String token) {
    return Completable.create(e -> {
        final AuthCredential credential = GoogleAuthProvider.getCredential(token,null);
        auth.signInWithCredential(credential).addOnCompleteListener(task -> {
            if (!e.isdisposed()) {
                if (task.isSuccessful()) {
                    e.onComplete();
                } else {
                    if (task.getException() != null) {
                        e.onError(task.getException());
                    } else {
                        e.onError(new UnkNownError());
                    }
                }
            }
        });
    });
}
项目:IdleCat    文件:SignInActivity.java   
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG,MainActivity.class));
                        finish();
                    }
                }
            });
}
项目:cat-is-a-dog    文件:GoogleAuthenticator.java   
/**
 * Authenticate Google user with Firebase
 * @param acct Google account
 */
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG,"signInWithCredential:success");
                        onSuccess();
                    } else {
                        // If sign in fails,task.getException());
                        onFailed();
                    }
                }
            });
}
项目:Expert-Android-Programming    文件:SignInBaseActivity.java   
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    MyLg.d(TAG,"firebaseAuthWithGoogle:" + acct.getId()+" "+acct.getPhotoUrl());
    showProgressDialog();

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    MyLg.d(TAG,display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        MyLg.w(TAG,"signInWithCredential");
                        Toas.show(context,"Authentication Failed.");
                    }
                    hideProgressDialog();
                }
            });
}
项目:CollegeDoc    文件:MainActivity.java   
private void handleFacebookAccesstoken(Accesstoken token) {
    Log.d(TAG,"handleFacebookAccesstoken:" + token);
    AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this,Toast.LENGTH_SHORT).show();
                    }
                }
            });
}
项目:CollegeDoc    文件:MainActivity.java   
private void handleTwitterSession(TwitterSession session) {
    Log.d(TAG,"handleTwitterSession:" + session);

    AuthCredential credential = TwitterauthProvider.getCredential(
            session.getAuthToken().token,session.getAuthToken().secret);

    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this,Toast.LENGTH_SHORT).show();
                    }

                    // ...
                }
            });
}
项目:Hyke    文件:LoginActivity.java   
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);
        auth.signInWithCredential(credential)
                .addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d("HERE","signInWithCredential:onComplete:" + task.isSuccessful());
                        Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
                        startActivity(intent);
                        finish();

                        // If sign in fails,display a message to the user. If sign in succeeds
                        // the auth state listener will be notified and logic to handle the
                        // signed in user can be handled in the listener.
                        if (!task.isSuccessful()) {
                            Log.w("HERE",Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
项目:Crimson    文件:SaveReports.java   
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {

        Log.d(TAG,"firebaseAuthWithGoogle:" + acct.getId());

        showProgressDialog();

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d(TAG,"signInWithCredential:onComplete:" + task.isSuccessful());

                        if (!task.isSuccessful()) {
                            Log.w(TAG,task.getException());
                            Toast.makeText(SaveReports.this,Toast.LENGTH_SHORT).show();
                        }
                        hideProgressDialog();
                    }
                });
    }
项目:Programmers    文件:UserRemoteDataSource.java   
@Override
public void firebaseAuthWithGoogle(GoogleSignInAccount account,final Callbacks.IResultCallback<Usuario> callback) {
    showLog("firebaseAuthWithGoogle: " + account.getId());
    AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(),null);
    FirebaseAuth.getInstance()
            .signInWithCredential(credential)
            .addOnFailureListener( reportError(callback))
            .addOnSuccessListener(new OnSuccessListener<AuthResult>() {
                @Override
                public void onSuccess(AuthResult authResult) {
                    FirebaseUser user = authResult.getUser();
                    loginFlow( user,callback);
                }
            });
}
项目:MangoBloggerAndroidApp    文件:BaseAuthActivity.java   
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG,"firebaseAuthWithGoogle:" + acct.getId());

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            hideProgressDialog();
                            // Sign in success,"signInWithCredential:success");
//                            FirebaseUser user = mAuth.getCurrentUser();
                            startApp();
                        } else {
                            hideProgressDialog();
                            // If sign in fails,task.getException());
                            Toast.makeText(BaseAuthActivity.this,Toast.LENGTH_SHORT).show();
                        }

                        // ...
                    }
                });
    }
项目:social-app-android    文件:LoginActivity.java   
private void handleFacebookAccesstoken(Accesstoken token) {
    LogUtil.logDebug(TAG,"handleFacebookAccesstoken:" + token);
    showProgress();

    AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    LogUtil.logDebug(TAG,display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        handleAuthError(task);
                    }
                }
            });
}
项目:social-app-android    文件:LoginActivity.java   
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    LogUtil.logDebug(TAG,"firebaseAuthWithGoogle:" + acct.getId());
    showProgress();

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        handleAuthError(task);
                    }
                }
            });
}

关于Firebase Auth JS / PHP的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于android – FirebaseUI Auth库:Google登录失败:W / AuthMethodPicker:Firebase登录失败、angularjs – Firebase $authWithOAuthRedirect在没有页面刷新的情况下不会调用$onAuth、angularjs – 来自Facebook的$authWithOAuthRedirect之后,Firebase $onAuth的authData错误、com.google.firebase.auth.AuthCredential的实例源码的相关知识,请在本站寻找。

本文标签: