I am using Firebase email and password authentication in my Angular 6 project, and want to persist the user login credentials for a browser session.
Once a user is logged in and I press F5 the user appears to no longer be logged in.
looking at the firebase documentation (https://firebase.google.com/docs/auth/web/auth-state-persistence#supported_types_of_auth_state_persistence), I should be able to set the persistence for the session by calling the method -
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION))
any idea where this code should go to properly implement this please?
_loggedIn = new BehaviorSubject<boolean>(false);
constructor(
public _fireAuth: AngularFireAuth) {
_fireAuth.auth.onAuthStateChanged(function (user) {
if (user) {
this._loggedIn = true;
console.log("onAuthStateChanged = true ");
} else {
console.log("onAuthStateChanged false ");
this._loggedIn = false;
}
});
}
Related
I'm using firebase anonymous authantication for my unity project.
As i always did when project is started i'm sending request to firebase for authantication,
but on my last project (which uses firebase sdk 6.16.0) my request creates new user everytime.
Here is some code about how i'm sending my request
Firebase.Auth.FirebaseAuth auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
auth.SignInAnonymouslyAsync().ContinueWith((task =>
{
if (task.IsCanceled)
{
Debug.Log("task cancelled");
return;
}
if (task.IsFaulted)
{
Debug.Log("task cancelled");
return;
}
if (task.IsCompleted)
{
Firebase.Auth.FirebaseUser userr = task.Result;
firebaseUserId = userr.UserId;
Debug.Log("firebaseUserId");
Debug.Log(firebaseUserId);
//every opening returns new uniq id here.
}
}));
On firebase authantication panel i only activated anonymous login. any suggestions?
Or is there any way to downgrade unity firebase version? i've tried to import old version which i was using on my last game (sdk 6.15.2) but there is some errors on resolver.
Basically, every time you call SignInAnonymouslyAsync you'll create a new user and the last one will be basically lost (it's more or less a random hash - anonymous as it's name suggests).
I'll typically do something like:
using System;
using Firebase.Auth;
using UnityEngine;
using UnityEngine.Events;
public class Login : MonoBehaviour
{
public UnityEvent OnSignInFailed = new UnityEvent();
public UserSignedInEvent OnUserSignedIn = new UserSignedInEvent();
public async void TriggerLogin()
{
var auth = FirebaseAuth.DefaultInstance;
var user = auth.CurrentUser;
if (user == null)
{
try
{
user = await auth.SignInAnonymouslyAsync();
}
catch (Exception e)
{
Debug.LogException(e);
OnSignInFailed.Invoke();
return;
}
}
// user definitely should not be null!
if (user == null)
{
OnSignInFailed.Invoke();
Debug.LogWarning("User still null!?");
return;
}
var userName = user.UserId;
OnUserSignedIn.Invoke(userName);
Debug.Log($"Logged in as {userName}");
}
[Serializable]
public class UserSignedInEvent : UnityEvent<string>
{
}
}
Note that for this code snippet, TriggerLogin is a public method so I can chain it off of a UnityEvent in the Unity editor.
Try and Put it some kind of check to find if used is already logged in. If yes, then do a silent login, if no then use anonymous login.
Currently you are straightaway logging in user even if they logged in last time they opened the Application.
Try this link: https://github.com/firebase/quickstart-unity/issues/266#issuecomment-447981995
I'm developing a web app and I use Firebase Authentication for the authentication service.
The project seems to store the authentication, since if I refresh the page, or close the browser, the user is still logged in.
However I noticed that if I don't access the app for a long time (more than 1 hour, after the night for example), the authentication gets lost.
I don't know how to debug this and how to solve this.
Following some snippets of code to better understand my implementation:
This is the function I have in my startup view to redirect the user to the right page based on auth status.
bool isUserLoggedIn() {
var user = _firebaseAuth.currentUser;
return user != null;
}
void handleStartupBasedOnAuthStatus() {
Future.delayed(const Duration(milliseconds: 1000), () async {
bool loggedInShared =
await sharedPreferences.getBoolSharedPreferences("loggedIn");
if (isUserLoggedIn() || loggedInShared) {
String ruoloValue =
await sharedPreferences.getSharedPreferences('ruolo');
(ruoloValue == Ruolo.ADMIN)
? navigationService.replaceWith(Routes.admin)
: navigationService.replaceWith(Routes.messages);
} else {
navigationService.replaceWith(Routes.login);
}
});
}
In the following function I call the onAuthStateChange to set sharedpreferences accordingly. I have the check on the timestamp because I noticed that it is triggered more time once the page is refreshed.
void listenToAuthChangesSharedPref() {
FirebaseAuth.instance.authStateChanges().listen((firebaseUser) async {
var datetimeNow = (DateTime.now().millisecondsSinceEpoch);
String oldDatetimeString =
await sharedPreferences.getSharedPreferences('previous_timestamp');
if (oldDatetimeString != null) {
var oldDatetime = (new DateTime.fromMillisecondsSinceEpoch(
int.parse(oldDatetimeString)))
.millisecondsSinceEpoch;
if (datetimeNow - oldDatetime > 1000) {
if (firebaseUser == null) {
await sharedPreferences.setBoolSharedPreferences('loggedIn', false);
} else {
await sharedPreferences.setBoolSharedPreferences('loggedIn', true);
}
await sharedPreferences.setSharedPreferences(
'previous_timestamp', datetimeNow.toString());
}
} else {
if (firebaseUser == null) {
await sharedPreferences.setBoolSharedPreferences('loggedIn', false);
} else {
await sharedPreferences.setBoolSharedPreferences('loggedIn', true);
}
await sharedPreferences.setSharedPreferences(
'previous_timestamp', datetimeNow.toString());
}
});
}
My question is: is possible that after long time currentUser and also the onAuthStateChanges gets called and the user is not logged in?
Persisting authentication state#
The Firebase SDKs for all platforms provide out of the box support for ensuring that your user's authentication state is persisted across app restarts or page reloads.
On native platforms such as Android & iOS, this behaviour is not configurable and the user's authentication state will be persisted on-device between app restarts. The user can clear the apps cached data via the device settings which will wipe any existing state being stored.
On web platforms, the user's authentication state is stored in local storage. If required, you can change this default behaviour to only persist authentication state for the current session, or not at all. To configure these settings, call the setPersistence() method (note; on native platforms an UnimplementedError will be thrown):
// Disable persistence on web platforms
await FirebaseAuth.instance.setPersistence(Persistence.NONE);
for more info:
for more info:
I can add users to keycloak but only in the master realm. Is there a way to add users to other realms beside master?
I tried and received an HTTP 401 Unauthorized Exception.
Sounds like your user doesn't have the manage-users role in other realms.
Just go to the admin realm, look up your user, navigate to Role mappings tab, then in the Client Roles drop down select the correct realm and then add manage-users as a role. Repeat for all realms.
//Here's how I created a user to my realm using Java
#Override
public UserDto registerNewUserAccount(final UserDto accountDto) {
String keycloakPassword = accountDto.getPassword();
accountDto.setPassword(passwordEncoder.encode(accountDto.getPassword()));
accountDto.setEnabled(1);
UserDto user = userRepository.save(accountDto);
AuthorityDto role = new AuthorityDto();
role.setUserName(accountDto.getLogin());
role.setAuthority("ROLE_USER");
authorityRepository.save(role);
Keycloak kc = Keycloak.getInstance(
"https://www.zdslogic.com/keycloak/auth", /your server
"zdslogic", //your realm
"richard.campion", //user
"Changit", //password
"admin-cli"); //client
CredentialRepresentation credential = new CredentialRepresentation();
credential.setType(CredentialRepresentation.PASSWORD);
credential.setValue(keycloakPassword);
UserRepresentation keycloakUser = new UserRepresentation();
keycloakUser.setUsername(accountDto.getLogin());
keycloakUser.setFirstName(accountDto.getFirstName());
keycloakUser.setLastName(accountDto.getLastName());
keycloakUser.setEmail(accountDto.getEmail());
keycloakUser.setCredentials(Arrays.asList(credential));
keycloakUser.setEnabled(true);
keycloakUser.setRealmRoles(Arrays.asList("user"));
// Get realm
RealmResource realmResource = kc.realm("zdslogic");
UsersResource usersRessource = realmResource.users();
// Create Keycloak user
Response result = null;
try {
result = usersRessource.create(keycloakUser);
} catch(Exception e) {
System.out.println(e);
}
if (result==null || result.getStatus() != 201) {
System.err.println("Couldn't create Keycloak user.");
}else{
System.out.println("Keycloak user created.... verify in keycloak!");
}
return user;
}
Here, I am trying to authenticate user via login and after that I want to skip permissions dialog. But I am unable to achieve this, as it always asking for permissions for app to the user. My intention is if user is not logged into the facebook he/she should be prompted for facebook login and then I will fetch public information by using method Get("/me"). Let me know what I am doing wrong here.
public string GetFBAccessToken(string strAppID, string strAppSecret, string strUrl)
{
// Declaring facebook client type
var vFB = new FacebookClient();
string strAccessTok = string.Empty;
try
{
if (!string.IsNullOrEmpty(strAppID) && !string.IsNullOrEmpty(strAppSecret) && !string.IsNullOrEmpty(strUrl))
{
// Getting login url for facebook
var loginUrl = vFB.GetLoginUrl(new
{
client_id = strAppID,
client_secret = strAppSecret,
redirect_uri = strUrl,
response_type = "code",
state = "returnUrl",
//scope = "",
display = "popup"
});
// Redirecting the page to login url
if (HttpContext.Current.Request.QueryString["code"] == null)
{
HttpContext.Current.Response.Redirect(loginUrl.AbsoluteUri);
}
// Fetching the access token from query string
if (HttpContext.Current.Request.QueryString["code"] != null)
{
dynamic result = vFB.Post("oauth/access_token", new
{
client_id = strAppID,
client_secret = strAppSecret,
redirect_uri = strUrl,
code = HttpContext.Current.Request.QueryString["code"]
});
// Getting access token and storing in a variable
strAccessTok = result.access_token;
}
}
return strAccessTok;
}
catch (Exception ex)
{
//if (HttpContext.Current.Request.QueryString["response_type"] == "code")
//{
// var fb = new FacebookClient();
// var details = fb.Get("/me");
//}
return strAccessTok;
}
}
Regardless to the platform/ language you are using; solution can be as follows.
check use's logged in status. https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
based on Response status, forcefully call your action (i.e. Log in, Get Permission or any additional action if user is already connected). For Log in check this reference document from FB. https://developers.facebook.com/docs/facebook-login/login-flow-for-web/
No. You cannot skip the Login Dialog.
In fact, it is really important for an APP owner to build a trust relationship with your users. I would recommend you to follow the Login Best Practices while authenticating the users using your APP.
I was trying to let the users change their password in settings. In the ajax page, I was using
WebSecurity.Logout();
So I thought logging out is because of this code. But then I noticed that the user logs out, even if this line isn't present after Password change success. So I tried to Google it. And on many places I found that this code removes the Cache and Cookies, so the user is logged out.
My Question: Is there any way to prevent User logout? Or can I save the Cookie or cache so that the user is still logged in after password change success.
You should use WebSecurity.ChangePassword, this will renew the current cookie with all new crendentials and then send it back into the response.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Manage(ChangePassward model)
{
bool changePasswordSucceeded = false;
try
{
changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
}
catch (Exception)
{
changePasswordSucceeded = false;
}
if (changePasswordSucceeded)
{
return RedirectToAction("Some Page here", new { Message = "Success" });
}
else
{
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
}
}
This is an old question, so apologies for bringing it back to life, but for anyone else who faces this issue:
You already have their username and password in this method. Log them back in.