Google Auth Page always shown, how to Auth only first time - flutter

I am making a calendar app with flutter using googleApi library.
but, When you turn off the app, need to auth again in web site.
i want auth only first time.
is it possible?
// mycode
get _SCOPES => [CalendarApi.CalendarScope];
await clientViaUserConsent(_clientID, _SCOPES, prompt)
.then((AuthClient client) async {
CalendarClient.calendar = CalendarApi(client);
calendarId = await CalendarClient.calendar.calendarList
.list()
.then((value) => value.items[0].id);
});
void saveData(AccessCredentials credentials) {
GetStorage().write(credetialKey, {
"accessTokenData": credentials.accessToken.data,
"accessTokenExpiry": credentials.accessToken.expiry.toString(),
"refreshToken": credentials.refreshToken,
"scopes": credentials.scopes,
"idToken": credentials.idToken
});
}
AccessCredentials getCredetial() {
try {
var map = GetStorage().read(credetialKey);
return AccessCredentials(
AccessToken("Bearer", map["accessTokenData"] as String,
DateTime.parse(map["accessTokenExpiry"])),
map["refreshToken"],
map["scopes"].cast<String>(),
idToken: map["idToken"] as String);
} catch (e) {
return null;
}
}
Client cli = Client();
var c = await refreshCredentials(_clientID, getCredetial(), cli)
.catchError((e) {
print(e);
});
authenticatedClient(cli, c);
error :
DetailedApiRequestError(status: 401, message: Request is missing required authentication credential. Expected OAuth 2 access tok

You can save user session using for example sharedPreferences. Each time the user launch the app your must first check if the session is saved so you can skip the auth process, otherwise you initiate the authentication

i solved it.
save AccessCredentials,
and use autoRefreshingClient;
Client cli = Client();
var c = await refreshCredentials(_clientID, getCredetial(), cli)
.catchError((e) {
print(e);
});
cli = autoRefreshingClient(_clientID, c, cli);

Related

Flutter - Keycloak integration with openId ( redirecting issue )

I want to authenticate flutter app with Keycloak service via internal webview (without open web browser)
To achieve this objective I used OpenID
When app runs will appear Keycloak login page in internal webview. But when entering the username and password correctly, it redirects to another web page which is as follows.
I guess this case happen due to flutter app cannot handle custom redirections. Does anyone know how to fix this??
My code:
urlLauncher(String url) async {
if (await canLaunch(url)) {
await launchUrlString(url, mode: LaunchMode.inAppWebView);
} else {
print("TOKEN = error");
throw 'Could not launch $url';
}
}
// create an authenticator
var authenticator = new Authenticator(
client,
redirectUri: Uri.parse(_redirectUrl),
scopes: scopes,
urlLancher: urlLauncher,
);
// starts the authentication
var c = await authenticator.authorize();
print("TOKEN = DONE");
// close the webview when finished
await closeInAppWebView();
var res = await c.getTokenResponse();
print("TOKEN = ${res.accessToken}");
pubspec.yaml:
openid_client: ^0.4.6
url_launcher: ^6.1.6
I tried open id , simple auth , flutter app auth also, unfortunately flutter app auth cannot use with internal webview
Future<TokenResponse> authenticate(Uri uri, String clientId,
List<String> scopes, BuildContext context) async {
try {
var issuer = await Issuer.discover(uri);
var client = Client(issuer, clientId);
urlLauncher(String url) async {
Uri uri = Uri.parse(url);
if (await launchUrl(uri)) {
} else {
throw 'Could not launch $url';
}
}
var authenticator = Authenticator(
client,
scopes: scopes,
urlLancher: urlLauncher,
port: 3000,
);
var c = await authenticator.authorize();
await closeInAppWebView();
var res = await c.getTokenResponse();
UserInfo use = await c.getUserInfo();
authUserId(use.subject.toString());
email(use.email.toString());
token(res.accessToken.toString());
logoutUrl = c.generateLogoutUrl();
return res;
} finally {
context.loaderOverlay.hide();
}
}
You can try this out.
Saved the logout URL into a variable cos it'll be needed to logout.

Why can't I see a cookie I sent from Flask to Flutter in the browser?

I am creating a Flutter Web app that requires login verification. The user makes a post request with authentication information and then my Flask app with send a cookie back to the client.
Here is the code for the Flask App
#app.route('/test', methods=['POST'])
#cross_origin(supports_credentials=True)
def test():
resp = jsonify({'message' : 'Logged in!'})
resp.set_cookie('Set-Cookie', "token", httponly = True, secure = False)
return resp
Here is the Dart/Flutter code where I make the POST request and expect a cookie called 'Set-Cookie'.
class HttpService {
static var dio = Dio();
static testMethod() async {
try {
dio.options.extra['withCredentials'] = true;
var response = await dio.post('http://127.0.0.1:5000/test');
print(response);
} catch (e) {
print(e);
}
}
As you can see, I don't receive this cookie on my browser, but the request is successful and I get the JSON message!
BUT, when I make this same request on Postman, I get the JSON response AND the cookie.
Any help would be greatly appreciated! Let me know if you need any more details/code.
Thanks to Kris, I realized I was making the request from Flutter (Client) to an IP rather than the domain name localhost. Because setting a cookie is domain specific, I couldn't see the cookie set in the developer console.
Here is the updated code
static testMethod() async {
try {
dio.options.extra['withCredentials'] = true;
var response = await dio.post('http://localhost:5000/test');
print(response);
} catch (e) {
print(e);
}
}

Flutter Session API Login

I am trying to log in with the help of API and after login wants to see dashboard.
but I am getting a message {status: error, message: Seller Not Logged In}
I tried creating a session of login but it didn't work.
Login Page
postMethod() async {
var api = Uri.parse("https://www.nearxt.com/index.php?route=api/userlogin");
Map mapeddate ={
'email':_email.text,
'password':_password.text,
};
final response= await post(api,body: mapeddate);
if(response.statusCode==200)
{
await FlutterSession().set('token',_email.text);
print("Session Created");
}
var res = json.decode(response.body);
print(res);
}
it gives the output: Session Created
{cust: Login Success, error_warning: , success: }
after this, on homepage, I am trying to access the products after the login
Future fetchSellerProduct() async {
FlutterSession().get('token');
var url = await http.post(Uri.parse(
"https://www.nearxt.com/index.php?route=api/purpletree_multivendor/api/sellerproduct"));
if(url.statusCode==200)
{
print(url.statusCode);
}
setState(() {
map = json.decode(url.body);
print(map);
});
}
Output: {status: error, message: Seller Not Logged In}

How to get the token from firebase_auth

I'd like to get the auth token from firebase (email and password auth) to authenticate in my firebase cloud function. It seems like the functions getIdToken() and getToken() are both not working for firebase_auth package.
is there an other function or is there even a better idea to make sure only authenticated users can trigger the cloud functions?
var token = await FirebaseAuth.instance.currentUser.getIdToken();
var response = await httpClient.get(url,headers: {'Authorization':"Bearer $token"});
I agree with #Doug on this one - callable wraps this for you and will be easier -, but my use case required me to make HTTPS calls (onRequest in Functions). Also, I think you're just in the correct path - but you're possibly not checking it in your Cloud Functions.
In your app, you'll call:
_httpsCall() async {
// Fetch the currentUser, and then get its id token
final user = await FirebaseAuth.instance.currentUser();
final idToken = await user.getIdToken();
final token = idToken.token;
// Create authorization header
final header = { "authorization": 'Bearer $token' };
get("http://YOUR_PROJECT_BASE_URL/httpsFunction", headers: header)
.then((response) {
final status = response.statusCode;
print('STATUS CODE: $status');
})
.catchError((e) {
print(e);
});
}
In your function, you'll check for the token:
export const httpsFunction = functions.https.onRequest((request, response) => {
const authorization = request.header("authorization")
if (authorization) {
const idToken = authorization.split('Bearer ')[1]
if (!idToken) {
response.status(400).send({ response: "Unauthenticated request!" })
return
}
return admin.auth().verifyIdToken(idToken)
.then(decodedToken => {
// You can check for your custom claims here as well
response.status(200).send({ response: "Authenticated request!" })
})
.catch(err => {
response.status(400).send({ response: "Unauthenticated request!" })
})
}
response.status(400).send({ response: "Unauthenticated request!" })
})
Keep in mind:
If I'm not mistaken, those tokens are valid for 1 hour, if you are going to store them somewhere, just be aware of this. I've tested locally and it takes around 200~500ms - every time - to get only the id token, which in most cases are not that big of overhead - but is significant.
It's going to be easiest for you to use a callable function, since that lets you:
Automatically send the current user's uid in the request.
Know very easily on the function side if a UID was provided in the request, and refuse service if none was provided.
The flutter plugin is here.
You should be able to do the equivalent work yourself, though, since callable functions are just a wrapper around normal HTTP connections. It's possible for you to get the ID token of the logged in user.
import 'package:firebase_messaging/firebase_messaging.dart';
.
.
.
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
#override
Future<void> initState() {
super.initState();
_firebaseMessaging.getToken().then((token) {
assert(token != null);
print("teken is: " + token);
});
}
Get your token from firebaseAuth and put in a string.
Future<Details> getDetails() async {
String bearer = await FirebaseAuth.instance.currentUser!.getIdToken();
print("Bearer: " + bearer.toString());
String token = "Bearer ${bearer}";
var apiUrl = Uri.parse('Your url here');
final response = await http.get(apiUrl, headers: {
'Authorization' : '${token}'
});
final responseJson = jsonDecode(response.body);
return Details.fromJson(responseJson);
}

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.