如果您对如何从FirebaseAuth获取ID令牌感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解如何从FirebaseAuth获取ID令牌的各种细节,此外还有关于AndroidFirebase
如果您对如何从FirebaseAuth获取ID令牌感兴趣,那么这篇文章一定是您不可错过的。我们将详细讲解如何从FirebaseAuth获取ID令牌的各种细节,此外还有关于Android Firebase Auth – 获取用户照片、android – Firebase Auth获取更多用户信息(年龄,性别)、android – Firebase Auth获取用户所在国家、android – FirebaseUI Auth库:Google登录失败:W / AuthMethodPicker:Firebase登录失败的实用技巧。
本文目录一览:- 如何从FirebaseAuth获取ID令牌
- Android Firebase Auth – 获取用户照片
- android – Firebase Auth获取更多用户信息(年龄,性别)
- android – Firebase Auth获取用户所在国家
- android – FirebaseUI Auth库:Google登录失败:W / AuthMethodPicker:Firebase登录失败
如何从FirebaseAuth获取ID令牌
我正在从我的Firebase数据库中读取一些Json文件,并且尝试获取要在标头中使用的当前用户的ID令牌,如下所示:
var response = await httpClient.get(url,headers: {'Authorization':"Bearer ${FirebaseAuth.instance.currentUser.getToken()}"});
当我执行上一行时,似乎无法获取正确的令牌,因为我无法访问数据库,但是,当我在字符串中手动包含ID令牌时,我的应用程序将按预期工作。我做错了到底是什么?
Android Firebase Auth – 获取用户照片
如何从移动应用程序中检索具有相当分辨率的用户照片?我查看了指南和api文档,推荐的方法似乎是使用FirebaseUser#getPhotoUrl().然而,这给了一张分辨率为50×50像素的照片的网址,这太低了,无法使用.有没有办法让客户要求更高的用户照片?我已经分别测试了Facebook登录和Google登录的sdks,在这两种情况下,照片的分辨率都高于Firebase Auth的回复.为什么Firebase Auth会更改原始分辨率,如何强制它不要这样做?谢谢.
解决方法:
Facebook和Google PhotoURL:
User myUserDetails = new User();
myUserDetails.name = firebaseAuth.getCurrentUser().getdisplayName();
myUserDetails.email = firebaseAuth.getCurrentUser().getEmail();
String photoUrl = firebaseAuth.getCurrentUser().getPhotoUrl().toString();
for (UserInfo profile : firebaseAuth.getCurrentUser().getProviderData()) {
System.out.println(profile.getProviderId());
// check if the provider id matches "facebook.com"
if (profile.getProviderId().equals("facebook.com")) {
String facebookUserId = profile.getUid();
myUserDetails.sigin_provider = profile.getProviderId();
// construct the URL to the profile picture, with a custom height
// alternatively, use '?type=small|medium|large' instead of ?height=
photoUrl = "https://graph.facebook.com/" + facebookUserId + "/picture?height=500";
} else if (profile.getProviderId().equals("google.com")) {
myUserDetails.sigin_provider = profile.getProviderId();
((HomeActivity) getActivity()).loadGoogleUserDetails();
}
}
myUserDetails.profile_picture = photoUrl;
private static final int RC_SIGN_IN = 8888;
public void loadGoogleUserDetails() {
try {
// Configure sign-in to request the user's ID, email address, and basic profile. ID and
// basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInoptions gso = new GoogleSignInoptions.Builder(GoogleSignInoptions.DEFAULT_SIGN_IN)
.requestemail()
.build();
// Build a Googleapiclient with access to GoogleSignIn.API and the options above.
mGoogleapiclient = new Googleapiclient.Builder(this)
.enableAutoManage(this, new Googleapiclient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
System.out.println("onConnectionFailed");
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleapiclient);
startActivityForResult(signInIntent, RC_SIGN_IN);
} catch (Exception e) {
e.printstacktrace();
}
}
@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()) {
GoogleSignInAccount acct = result.getSignInAccount();
// Get account information
String PhotoUrl = acct.getPhotoUrl().toString();
}
}
}
android – Firebase Auth获取更多用户信息(年龄,性别)
我正在为我的Android应用使用Firebase身份验证.用户可以使用多个提供商(Google,Facebook,Twitter)登录.
成功登录后,有没有办法使用Firebase api从这些提供商处获取用户性别/出生日期?
解决方法:
很遗憾,Firebase在成功登录后没有任何内置功能来获取用户的性别/生日.您必须自己从每个提供程序中检索这些数据.
以下是使用Google People API从Google获取用户性别的方法
public class SignInActivity extends AppCompatActivity implements
Googleapiclient.ConnectionCallbacks,
Googleapiclient.OnConnectionFailedListener,
View.OnClickListener {
private static final int RC_SIGN_IN = 9001;
private Googleapiclient mGoogleapiclient;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_sign_in);
// We can only get basic information using FirebaseAuth
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in to Firebase, but we can only get
// basic info like name, email, and profile photo url
String name = user.getdisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
// Even a user's provider-specific profile information
// only reveals basic information
for (UserInfo profile : user.getProviderData()) {
// Id of the provider (ex: google.com)
String providerId = profile.getProviderId();
// UID specific to the provider
String profileUid = profile.getUid();
// Name, email address, and profile photo Url
String profiledisplayName = profile.getdisplayName();
String profileEmail = profile.getEmail();
Uri profilePhotoUrl = profile.getPhotoUrl();
}
} else {
// User is signed out of Firebase
}
}
};
// Google sign-in button listener
findViewById(R.id.google_sign_in_button).setonClickListener(this);
// Configure GoogleSignInoptions
GoogleSignInoptions gso = new GoogleSignInoptions.Builder(GoogleSignInoptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.server_client_id))
.requestServerAuthCode(getString(R.string.server_client_id))
.requestemail()
.requestScopes(new Scope(PeopleScopes.USERINFO_PROFILE))
.build();
// Build a Googleapiclient with access to the Google Sign-In API and the
// options specified by gso.
mGoogleapiclient = new Googleapiclient.Builder(this)
.enableAutoManage(this, this)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.google_sign_in_button:
signIn();
break;
}
}
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()) {
// Signed in successfully
GoogleSignInAccount acct = result.getSignInAccount();
// execute AsyncTask to get gender from Google People API
new GetGendersTask().execute(acct);
// Google Sign In was successful, authenticate with Firebase
firebaseAuthWithGoogle(acct);
}
}
}
class GetGendersTask extends AsyncTask<GoogleSignInAccount, Void, List<Gender>> {
@Override
protected List<Gender> doInBackground(GoogleSignInAccount... googleSignInAccounts) {
List<Gender> genderList = new ArrayList<>();
try {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();
//Redirect URL for web based applications.
// Can be empty too.
String redirectUrl = "urn:ietf:wg:oauth:2.0:oob";
// Exchange auth code for access token
GoogletokenResponse tokenResponse = new GoogleAuthorizationCodetokenRequest(
httpTransport,
jsonFactory,
getApplicationContext().getString(R.string.server_client_id),
getApplicationContext().getString(R.string.server_client_secret),
googleSignInAccounts[0].getServerAuthCode(),
redirectUrl
).execute();
GoogleCredential credential = new GoogleCredential.Builder()
.setClientSecrets(
getApplicationContext().getString(R.string.server_client_id),
getApplicationContext().getString(R.string.server_client_secret)
)
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.build();
credential.setFromTokenResponse(tokenResponse);
People peopleService = new People.Builder(httpTransport, jsonFactory, credential)
.setApplicationName("My Application Name")
.build();
// Get the user's profile
Person profile = peopleService.people().get("people/me").execute();
genderList.addAll(profile.getGenders());
}
catch (IOException e) {
e.printstacktrace();
}
return genderList;
}
@Override
protected void onPostExecute(List<Gender> genders) {
super.onPostExecute(genders);
// iterate through the list of Genders to
// get the gender value (male, female, other)
for (Gender gender : genders) {
String genderValue = gender.getValue();
}
}
}
}
您可以在Accessing Google APIs找到更多信息
android – Firebase Auth获取用户所在国家
我正在使用Firebase身份验证与谷歌登录和Facebook登录
有没有其他方法可以知道用户来自哪个国家/地区?
在应用程序知道用户来自哪个国家/地区之后,应用程序将决定向用户显示哪个服务/未来.
解决方法:
方法1:
试试这个代码.此代码将根据所连接的国家/地区的网络返回国家/地区代码. see here.没有SIM卡就行不通.
TelephonyManager tm = (TelephonyManager)this.getSystemService(this.TELEPHONY_SERVICE);
String countryCodeValue = tm.getNetworkCountryIso();
方法2:
如果您的设备已连接到互联网,则可以使用此链接http://ip-api.com/json.它会根据IP地址自动检测设备返回位置详细信息的IP地址.
方法3:您可以从GPS获取位置.
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locationManager.getBestProvider(criteria,true);
Location curLocation = locationManager.getLastKNownLocation(provider);
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = null;
addresses = geocoder.getFromLocation((double)curLocal.getLatitudeE6(),(double)curLocal.getLongitudeE6(),1);
String countryCode= addresses.get(0).getCountryCode();
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解决方案:这是一项伟大的改进!
今天关于如何从FirebaseAuth获取ID令牌的介绍到此结束,谢谢您的阅读,有关Android Firebase Auth – 获取用户照片、android – Firebase Auth获取更多用户信息(年龄,性别)、android – Firebase Auth获取用户所在国家、android – FirebaseUI Auth库:Google登录失败:W / AuthMethodPicker:Firebase登录失败等更多相关知识的信息可以在本站进行查询。
本文标签: