Autofill login credentials in flutter inappWebview - flutter

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();
}

Related

save InAppWebView Cookies in Shared_Preferences F;utter

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);

How to get parameter value from link in flutter?

I am using Firebase dynamic links and I save it to a deepLink variable and pass it to the next page. Tell me, how can I get the code and pageName parameters from the link so that I can use them in the future?
url
https://.........app?pageName=emailActivationPage&code=7075
code
await Firebase.initializeApp();
final PendingDynamicLinkData? initialLink =
await FirebaseDynamicLinks.instance.getInitialLink();
if (widget.initialLink != null) {
final Uri deepLink = widget.initialLink!.link;
routeCubit.toForgotPasswordPage(deepLink.path, true);
} else {
routeCubit.toPhoneNumberPage();
}
You can access the data through the queryParameter property. It also should be a good idea to check beforehand if the key is given in the Map
if(deepLink.queryParameters.containsKey('code')){
final code = deepLink.queryParameters['code'];
}

How to connect facebook, firebase and flutter?

I'm following the instructions for incorporating facebook with android projects found here https://developers.facebook.com/apps/318154048893918/fb-login/quickstart/ and there is a step to download the Facebook SDK, but after that, it doesn't tell me where to put the file. The import statement it tells me to add won't work (says target of uri doesn't exist).
I'm trying to add the facebook user to our firebase database when they log in. I'm using flutter in android studio.
There doesn't seem to be anything of use in the console log, except that print statement doesn't print anything. Any ideas?
Here's my code to log in the user.
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
Future<FirebaseUser> initiateFacebookLogin() async {
final FacebookLoginResult result =
await facebookLogin.logInWithReadPermissions(['email', 'public_profile']);
FirebaseUser user =
await _auth.signInWithFacebook(accessToken: result.accessToken.token);
//Token: ${accessToken.token}
ProviderDetails userInfo = new ProviderDetails(
user.providerId, user.uid, user.displayName, user.photoUrl, user.email);
List<ProviderDetails> providerData = new List<ProviderDetails>();
providerData.add(userInfo);
print(user.displayName);
addToDatabase(user.uid, user.displayName, user.displayName, user.email);
return user;
}
In flutter you need use flutter_facebook_login plugin take a look here to see how to get the plugin and setup your flutter app to make use of this plugin. You can also check this article that is step-by-step about how setup you project and contains code example too but the API used is out of date.
Here a snippet with updated API showing how to achieve login in firebase with facebook account.
/// This mehtod makes the real auth
Future<FirebaseUser> firebaseAuthWithFacebook({#required FacebookAccessToken token}) async {
AuthCredential credential= FacebookAuthProvider.getCredential(accessToken: token.token);
FirebaseUser firebaseUser = await _authInstance.signInWithCredential(credential);
return firebaseUser;
}
In your code you're using _auth.signInWithFacebook method that is deprecated and you should replaced by signInWithCredential updating you firebase_auth plugin version.
///This object comes from facebook_login_plugin package
final facebookLogin = new FacebookLogin();
final facebookLoginResult = await facebookLogin
.logInWithReadPermissions(['email', 'public_profile']);
switch (facebookLoginResult.status) {
case FacebookLoginStatus.error:
print("Error");
break;
case FacebookLoginStatus.cancelledByUser:
print("CancelledByUser");
break;
case FacebookLoginStatus.loggedIn:
print("LoggedIn");
/// calling the auth mehtod and getting the logged user
var firebaseUser = await firebaseAuthWithFacebook(
token: facebookLoginResult.accessToken);
}
}

How to do wordpress api authentication in flutter

I am making a flutter application in which in need to fetch data from backened API which is made in wordpress.Now in postman i only need to insert client key and client secret in Oauth 1 authentication and it works fine.But in flutter application it tell that the signature data is invalid.Why ?
I followed official guide from woocommerce Api but i failed.How can i make wordpress api in flutter in dart?I am new to flutter and this is very important for me.So how can i fetch data ?Is there any method to achieve what i want ?
As per my understanding, you are looking for something like this
You want to display the products from wooCommerce using REST API.
And you want that to be done in Flutter Dart.
Auth for users.
The very first thing will do is Auth the user using Username and Password so to do that we have to do something like this
For Auth you should install the JWT plugin name JWT Authentication for
WP-API in WordPress
Then use this URL in the Flutter
Future<http.Response> login(String username, String password) async {
final http.Response response = await http.post('https://domina-name/wp-json/jwt-auth/v1/token?username=abc&password=xyz');
print(response);
return response;
}
This function fetches the data from the wooCommerce REST API endpoints and stores in the List
List<CatService> category;
Future<void> getCategoryData() async {
var res = await http.get(
"https://domain-name/wp-json/wc/v3/products/categories?per_page=100&consumer_key=xxxxxxxxxxxxxxxxxxxxx&consumer_secret=xxxxxxxxxxxxxxx&page=1");
setState(() {
var data = json.decode(res.body);
var list = data as List;
print("List of cat $list");
categoryList =
list.map<CatService>((json) => CatService.fromJson(json)).toList();
category = categoryList
.where((data) => data.count > 0 && data.catName != 'Uncategorized')
.toList();
});
}
Now you should call this future getCategoryData method like this
void initState() {
setState(() {
this.getCategoryData();
});
super.initState();
}
I have created a class for CatService
class CatService {
int catId;
String catName;
int count;
CatService({this.catId, this.catName,this.count});
factory CatService.fromJson(Map<String, dynamic> json) {
return CatService(catId: json['id'], catName: json['name'],count: json['count']);
}
}
Thanks, I hope this will help you

Auth0-How to use with Flutter

I need use Auth0 with Flutter but there is no such SDK in Auth0 site.
Auth0 works to create such SDK for Flutter.
Did anyone use Auth0 with Flutter or what can you advise?
Its very simple to get started with flutter auth0
Have a class for auth0 and call this at the places you need them. But also be sure to set the constants AUTH0_DOMAIN, AUTH0_CLIENT_ID, AUTH0_REDIRECT_URI, AUTH0_ISSUER
class Auth0 {
final FlutterAppAuth appAuth = FlutterAppAuth();
Map<String, Object> parseIdToken(String idToken) {
final List<String> parts = idToken.split('.');
assert(parts.length == 3);
return jsonDecode(
utf8.decode(base64Url.decode(base64Url.normalize(parts[1]))));
}
Future<Map<String, Object>> getUserDetails(String accessToken) async {
const String url = 'https://$AUTH0_DOMAIN/userinfo';
final http.Response response = await http.get(
url,
headers: <String, String>{'Authorization': 'Bearer $accessToken'},
);
if (response.statusCode == 200) {
return jsonDecode(response.body);
} else {
throw Exception('Failed to get user details');
}
}
Future<void> loginAction() async {
isBusy = true;
errorMessage = 'Error! - ';
try {
final AuthorizationTokenResponse result =
await appAuth.authorizeAndExchangeCode(
AuthorizationTokenRequest(
AUTH0_CLIENT_ID,
AUTH0_REDIRECT_URI,
issuer: 'https://$AUTH0_DOMAIN',
scopes: <String>['openid', 'email', 'profile', 'offline_access'],
promptValues: ['login']
),
);
final Map<String, Object> idToken = parseIdToken(result.idToken);
final Map<String, Object> profile =
await getUserDetails(result.accessToken);
isBusy = false;
name = idToken['name'];
email = profile['email'];
picture = profile['picture'];
} on Exception catch (e, s) {
print('login error: $e - stack: $s');
isBusy = false;
errorMessage = e.toString();
}
}
Instead of using a boolean for checking isLoggedIn try saving the token in the localstorage and that will set the state as is.
There's an auth0 package for flutter to use Auth0 API provides login, logout and access APIs for authentication in your App. However, you need to make changes inside android and ios files in your flutter project. You need to configure your callbacks and application settings for that, The author has their example on github that you should check out.
I would advise you to follow the blog post provided by the Auth0 team -
Get Started with Flutter Authentication
For Flutter Web App, I am making a wrapper around Auth0 JS SPA SDK.
GitHub: https://github.com/anthonychwong/auth0-flutter-web
Pub.dev: https://pub.dev/packages/auth0_flutter_web
import 'package:auth0_flutter_web/auth0_flutter_web.dart';
Auth0 auth0 = await createAuth0Client(
Auth0CreateOptions(
domain: '-- domain of the universal login page --',
client_id: '-- id of your app --',
)
);
String token = await auth0.getTokenWithPopup();
It is in very early stage and PRs are welcome.