save InAppWebView Cookies in Shared_Preferences F;utter - flutter

I'm using shared_preferences ^2.0.15. I'm facing webview logout problem. Every time user restart the app, user logout from the webview. I'm trying to save cookies when user login in webview and generate cookies.
So I'm troubling to save in cookies in Shared_Preferences.
final cookies = <dynamic>[].obs;
void saveCookies(dynamic value) async {
final store = await SharedPreferences.getInstance();
store.clear();
cookies.value = value;
await store.setString('cookies', convert.jsonEncode(cookies.toJson())); // Fail to add
}
var cookieList = await _cookieManager.getCookies(url);
saveCookies(cookieList);

Related

How to pass cookie in http request - Flutter

What I'm trying do is access the Instagram private api which requires user to be logged in before sending request to it, so to achieve that, I accessed the cookies or session id with the help of flutter_web_view and webview_cookie_manager (basically making the user logged in through webview and then get the cookie using cookie_manager package)
But how to pass that cookie in http request?
// accessing cookie or session id
WebViewController webViewController = WebViewController()
..loadRequest(Uri.parse('https://www.instagram.com/'))
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(
onPageFinished: (value) async {
final cookieManager = WebviewCookieManager();
List<Cookie> gotCookies = await cookieManager.getCookies('https://www.instagram.com/');
print(gotCookies); // recieved the cookies
}
)
)
;
var response = await http.get(private_api_url}); // how to pass cookies in this request
var response = await http.get(private_api_url, headers: {'cookie': cookie});

A logged out user data is shown to current user until I close the app and reopen

After I click logout button, the app log user out successful. But when the new user logged in it shows data of the previous user of the same device until I close the app (swipe up on iPhone) and opens again then it fetches current user data. The Firebase data are fetched of the current user but rest API data are fetched of the previous user and when I close and open the app it fetches new user data.
I have tried you clear data using shared preferences and I even installed path_provider: ^2.0.12 to clear the cache on log out pressed, but it still shows previous user data until I close the app and reopen
Future<void> _deleteCacheDir() async {
Directory tempDir = await getTemporaryDirectory();
if (tempDir.existsSync()) {
tempDir.deleteSync(recursive: true);
}
}
Future<void> _deleteAppDir() async {
Directory appDocDir = await getApplicationDocumentsDirectory();
if (appDocDir.existsSync()) {
appDocDir.deleteSync(recursive: true);
}
}
and here is my code for clear data using shared preference
Future<void> clearAllData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
await prefs.clear();
}
and Firebase logout function
Future<void> logout() async => await _auth.signOut();
what should I do please, am stuck
I have tried to check some solution on stackoverflow here like
https://stackoverflow.com/questions/74839200/after-new-login-app-show-old-user-data-from-firebase
https://stackoverflow.com/questions/68812231/after-log-out-and-new-login-still-shows-old-user-data

After login with twitter authorize api, returning is black screen

I am going to develop a flutter app, it login/ signup with twitter api. I code it prefectly but when it move to authorize window to back then it show black screen not returning to my app, whats happing?? Thank you My code is
Future<UserCredential> signInWithTwitter() async {
// Create a TwitterLogin instance
final twitterLogin = new TwitterLogin(
apiKey: 'wkeO1wbI1dHfEjK9TMXPdbD4g',
apiSecretKey: 'b60VwlAerBi39M2TBKz1V6bDAbzu2J2vWFupWs2ZSl6Quz6uVf',
redirectURI: 'school-management-system://',
);
// Trigger the sign-in flow
final authResult = await twitterLogin.login();
// Create a credential from the access token
final twitterAuthCredential = TwitterAuthProvider.credential(
accessToken: authResult.authToken!,
secret: authResult.authTokenSecret!,
);
// Once signed in, return the UserCredential
return await FirebaseAuth.instance
.signInWithCredential(twitterAuthCredential);
}
I did this code and its output in video[output here]

Autofill login credentials in flutter inappWebview

I am using flutter_inappwebview plugin for developing an android browser. Now I need to save and autofill login credentials for different websites like facebook, twitter etc.
I come to know about securely storing login data using flutter_secure_storage plugin but I don't have any knowledge about how to implement this.
I want this feature exactly as it has in Google Chrome. Please help if you can...
Thanks in advance!
flutter_secure_login currently does not support Flutter platform web.
Since this is the case I would recommend using shared_preferences found here
Its very similar to secure storage and can be utilized in a very similar way
in the following code i am using it to store my user data
// write to shared preferences
final prefs = await SharedPreferences.getInstance();
if (!_context.isLoggedIn) {
if (prefs.containsKey('userData')) prefs.remove('userData');
return;
}
final userData = Map<String, String>();
userData['refreshToken'] = _refreshToken;
userData['tenantId'] = _tenantId;
userData['userId'] = _userId;
await prefs.setString('userData', json.encode(userData));
That can then be accessed to refresh tokens.
Future init() async {
final prefs = await SharedPreferences.getInstance();
final prefData = prefs.getString('userData');
if (prefData == null) return;
final Map<String, Object> userData = json.decode(prefData);
_authWriter.write({
'refreshToken': userData['refreshToken'],
'userId': userData['userId'],
'tenantId': userData['tenantId']
});
await refreshAccessToken();
}

How to obtain the refreshToken when google sign in with Flutter / Firebase

I've already did the google sign with the firebase flutter toolkit. When sign in is done, I receive the idToken to read/write on the database.
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn();
Future<String> signInWithGoogle() async {
await Firebase.initializeApp();
final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
final UserCredential authResult = await _auth.signInWithCredential(credential);
final User user = authResult.user;
final idToken = await user.getIdToken();
}
The problem is, I need to auto login user when he opens the app again. So, when I sign in with google, I do not receive the refresh token, needed to get the new valid idToken, as the Doc.
How can I get the refreshToken ?
You can use SharedPreferences to set a bool value when a user is logged in from google and check the value when the app restarts. Don't forget to remove this value from shared preferences when user logged out.
I'm pretty sure googl_sign_in keeps the refresh token internally and you always receive a valid idToken. If it's about to expire, you can force renewal.
Answering your direct question about refreshToken:
You can create your own implementation of the google_sign_in class. In the end it's just an OAuth token. Here's a web implementation of a custom google_sign_in service: https://stackoverflow.com/a/69746036/5492496
I'm pretty sure you can do the same for Android & iOS using web view, you will loose the single click functionality on Android though.