我正在为我的Android应用使用Firebase身份验证。用户可以使用多个提供商(Google,Facebook,Twitter)登录。
成功登录后,有没有办法使用Firebase API从这些提供商处获取用户性别/出生日期?
答案 0 :(得分:3)
不幸的是,Firebase没有任何内置功能可以在成功登录后获得用户的性别/生日。您必须自己从每个提供程序中检索这些数据。
以下是使用Google People API
从Google获取用户性别的方法rank()
上找到更多信息
答案 1 :(得分:2)
对于Facebook:
从firebase获取facebook accessToken非常简单。我正在使用firebase auth UI。使用Facebook验证后,您将从firebase用户对象获取基本信息,如显示名称,电子邮件,提供商详细信息。但如果你想要更多的信息,如性别,生日facebook图谱API是解决方案。一旦用户通过Facebook进行身份验证,您就可以获得这样的访问令牌。
AccessToken.getCurrentAccessToken() 但有时它会给你NULL值而不是有效的访问令牌。确保在此之前已经初始化了facebook SDK。
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
FacebookSdk.sdkInitialize(this);
}
} 初始化后使用graphAPI
if(AccessToken.getCurrentAccessToken()!=null) {
System.out.println(AccessToken.getCurrentAccessToken().getToken());
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Application code
try {
String email = object.getString("email");
String gender = object.getString("gender");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
}
else
{
System.out.println("Access Token NULL");
}
快乐编码:)
答案 2 :(得分:1)
与使用Google的People API类访问其REST服务相比,我发现直接访问服务要简单得多。
还节省了1.5 MB的APK大小。
public static final String USER_BIRTHDAY_READ = "https://www.googleapis.com/auth/user.birthday.read";
public static final String USER_PHONENUMBERS_READ = "https://www.googleapis.com/auth/user.phonenumbers.read";
public static final String USERINFO_EMAIL = "https://www.googleapis.com/auth/userinfo.email";
public static final String USERINFO_PROFILE = "https://www.googleapis.com/auth/userinfo.profile";
public JSONObject getUserinfo(@NotNull Context context, @NotNull GoogleSignInAccount acct) {
try {
String token = GoogleAuthUtil.getToken(context, acct.getAccount(), "oauth2: " +USERINFO_PROFILE+" "+USER_PHONENUMBERS_READ+" "+USERINFO_EMAIL+" "+USER_BIRTHDAY_READ);
URL url = new URL("https://people.googleapis.com/v1/people/me?"
+"personFields=genders,birthdays,phoneNumbers,emailAddresses"
+"&access_token=" + token);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
int sc = con.getResponseCode();
if (sc == 200) {
InputStream is = con.getInputStream();
JSONObject profile = new JSONObject(readStream(is));
Log.d(TAG, "Got:" + profile.toString(2));
Log.d(TAG, "genders: "+profile.opt("genders"));
Log.d(TAG, "birthdays: "+profile.opt("birthdays"));
Log.d(TAG, "phoneNumbers: "+profile.opt("phoneNumbers"));
return profile;
} else if (sc == 401) {
GoogleAuthUtil.clearToken(context, token);
Log.d("Server auth fejl, prøv igen\n" + readStream(con.getErrorStream()));
} else {
Log.d("Serverfejl: " + sc);
}
} catch (UserRecoverableAuthException recoverableException) {
startActivityForResult(recoverableException.getIntent(), 1234);
} catch (Exception e) {
e.printStackTrace();
}
public static String readStream(InputStream is) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] data = new byte[2048];
int len = 0;
while ((len = is.read(data, 0, data.length)) >= 0) {
bos.write(data, 0, len);
}
is.close();
return new String(bos.toByteArray(), "UTF-8");
}
输出很容易解析为JSON:
genders: [{"metadata":{"primary":true,"source":{"type":"PROFILE","id":"101628018970026223117"}},"value":"male","formattedValue":"Male"}]
birthdays: [{"metadata":{"primary":true,"source":{"type":"PROFILE","id":"101628018970026223117"}},"date":{"year":1985,"month":3,"day":5}},{"metadata":{"source":{"type":"ACCOUNT","id":"101628018970026223117"}},"date":{"year":1985,"month":3,"day":5}}]
答案 3 :(得分:0)
不,您无法直接获取这些数据。但您可以使用用户的ID并从各种提供程序获取这些数据。请检查这些提供商的公共API中可用的数据,例如google刚刚弃用了peopleApi中的一些方法。
无论如何,这是我为facebook做的事情
// Initialize Firebase Auth
FirebaseAuth mAuth = FirebaseAuth.getInstance();
// Create a listener
FirebaseAuth.AuthStateListener mAuthListener = firebaseAuth -> {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
if (user != null) {
Log.d(TAG, "User details : " + user.getDisplayName() + user.getEmail() + "\n" + user.getPhotoUrl() + "\n"
+ user.getUid() + "\n" + user.getToken(true) + "\n" + user.getProviderId());
String userId = user.getUid();
String displayName = user.getDisplayName();
String photoUrl = String.valueOf(user.getPhotoUrl());
String email = user.getEmail();
Intent homeIntent = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(homeIntent);
finish();
}
};
//Initialize the fB callbackManager
mCallbackManager = CallbackManager.Factory.create();
在FB登录按钮的onClick中执行以下操作
LoginManager.getInstance().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);
}
});
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email"));