sendSignInLinkToEmail with Flutter, Firebase Auth throws error "[firebase_auth/missing-continue-uri] A continue URL must be provided in the request." - flutter

Here's my code. I'm attempting to implement Firebase Passwordless Sign in.
final ActionCodeSettings acs = ActionCodeSettings(
url: 'https://example.com/completeLogin}',
handleCodeInApp: true,
iOSBundleId: config.bundleId,
androidPackageName: config.packageName,
dynamicLinkDomain: config.firebaseDomain,
androidInstallApp: true);
await FirebaseAuth.instance.sendSignInLinkToEmail(
email: 'example#domain.com',
actionCodeSettings: acs);

To solve this,
A valid continue URL must be provided in the request.
Make sure that the URLs you are providing are valid.
Your URL has a } at the end - url: 'https://example.com/completeLogin}', which is probably making it invalid.

Related

Flutter google sign in serverAuthCode

I'm using this flutter plugin google_sign_in 5.2.1
works good I get the response
{displayName: Mario Mc, email: myemail#gmail.com, id: 117816213074325689769, photoUrl: https://lh3.googleusercontent.com/a-/AOh14GgyaPy7ik693hjyIBmtW5IRXUdCXluaeI=s96-c, serverAuthCode: 4/0AX4XfWiqJ1DMfPaDbgf6gOFVMCfgMicyPqGk25bxjKfA4wq7bJCCu-TWRB8c3rAz_g}
My question is: what is serverAuthCode?
And what's id: 117816213074325689769 used for
And after I send that serverAuthCode to the server, how do I verify that code is legit by calling google servers(as you know any person can send a fake serverAuthCode, so we need to verify it before saving it or do something with it)
I want to use PHP in the server side
thanks
What you can do is use this to get the accessToken then send it to the server
// sign In With Google
_googleSignIn.signIn().then((userData) {
userData.authentication.then((googleKey) {
setState(() {
// Retrieve the email from Google auth
googleEmail = userData.email;
googleId = userData.id;
googlePhotoUrl = userData.photoUrl;
googleServerAuthCode = userData.serverAuthCode;
googleAccessToken = googleKey.accessToken;
googleIdToken = googleKey.idToken;
});
print("googleAccessToken");
print(googleAccessToken);
// call your login function if no errors
checkInternetAndLoginWithGoogle();
}).catchError((err) {
print('inner error');
});
}).catchError((err) {
print('error occurred');
print(err);
});
in the server side, you can verify that access token by calling
https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=<access token>
you will get an answer if that token is valid or expired
Also, you can call this to get user info such as name, email, photo etc.
https://www.googleapis.com/oauth2/v3/userinfo?access_token=<access token>

How to logout with openid_client after authentication via pkce in flutter app with keycloak using openid_client?

I have the following KeyCloak Client config, to use pkce authentication flow:
Realm: REALM
Client ID: pkce-client
Client Protocol: openid-connect
Access Type: public
Standard Flow Enabled: ON
Valid Redirect URIs: http://localhost:4200/
Advanced Settings:
Proof Key for Code Exchange Code Challenge Method: S256
After authenticating with flutter App with iOS Simulator via openid_client
https://pub.dev/packages/openid_client at some point I need to log out.
I can do this to get the logout URL:
String localhost = getLocalhost();
var uri = Uri.parse('http://$localhost:8180/auth/realms/REALM');
var clientId = 'pkce-client';
var issuer = await Issuer.discover(uri);
var client = Client(issuer, clientId);
String idT = token.idToken.toCompactSerialization();
Credential credential = client.createCredential(
tokenType: token.tokenType,
refreshToken: token.refreshToken,
idToken: idT,
);
var url;
try {
url = credential.generateLogoutUrl();
} catch (e) {
print("Error during login (refresh) " + e.toString());
}
urlLauncher(String url) async {
if (await canLaunch(url)) {
await launch(url, forceWebView: true);
} else {
throw 'Could not launch $url';
}
}
String callUrl = url.toString();
urlLauncher.call(callUrl);
This is how the logout url looks like:
http://localhost:8180/auth/realms/vopi/protocol/openid-connect/logout?id_token_hint=eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICIxUVJwMXAtbmk1WmcyZmlyRHFoRS1iS1hwe.......
I'm not logged out after calling the url. Can someone help with this?
Thanks in advance
Redirect browser (web view) to that logout url (logout URL is not an API call, so you can't use XMLHttpRequest). That terminates existing IdP session. Of course you need to destroy also any local tokens (access/id/refresh token), which your app already has.
the IDP should have a front end logout url that you can call to logout of the current session. it is a call directly from the browser to the IDP endpoint.
the IDP front end logout should terminate the session, clear any cookies but the backend tokens (access token , refresh token etc) need to be cleared by your application.

Cannot authenticate via pkce flutter app with keycloak using openid_client

I have the following KeyCloak Client config, to use pkce authentication flow:
Realm: REALM
Client ID: pkce-client
Client Protocol: openid-connect
Access Type: public
Standard Flow Enabled: ON
Valid Redirect URIs: http://localhost:4200/
Advanced Settings:
Proof Key for Code Exchange Code Challenge Method: S256
I try to authenticate in a flutter App with iOS Simulator via openid_client
https://pub.dev/packages/openid_client like this
authenticate() async {
var uri = Uri.parse('http://$localhost:8180/auth/realms/REALM');
var clientId = 'pkce-client';
var scopes = List<String>.of(['profile', 'openid']);
var port = 4200;
var redirectUri = Uri.parse(http://localhost:4200/);
var issuer = await Issuer.discover(uri);
var client = new Client(issuer, clientId);
urlLauncher(String url) async {
if (await canLaunch(url)) {
await launch(url, forceWebView: true);
} else {
throw 'Could not launch $url';
}
}
var authenticator = new Authenticator(
client,
scopes: scopes,
port: port,
urlLancher: urlLauncher,
redirectUri: redirectUri,
);
var auth = await authenticator.authorize();
var token= await auth.getTokenResponse();
return token;
}
But it only gives me this web view:
The Terminal where KeyCloak is running gives me the following lines:
INFO [org.keycloak.protocol.oidc.endpoints.AuthorizationEndpointChecker] (default task-34) PKCE enforced Client without code challenge method.
WARN [org.keycloak.events] (default task-34) type=LOGIN_ERROR, realmId=REALM, clientId=pkce-client, userId=null, ipAddress=127.0.0.1, error=invalid_request, response_type=code, redirect_uri=http://localhost:4200/, response_mode=query
When using Postman it worked and it provided me the Login page:
But I have additional parameters there, which I do not know where to add them in Authenticator(..) when using openid_client, state is automatically added.
state: <state>
code_challenge: <code-challenge>
code_challenge_method: S256
Do I need to add these code_challenge parameters somewhere in the openid_client method?
Or do I need to change the redirect URL when using an App? I tried with the package_name like proposed here (https://githubmemory.com/repo/appsup-dart/openid_client/issues/32), but it did not work either.
See the source code:
: flow = redirectUri == null
? Flow.authorizationCodeWithPKCE(client)
: Flow.authorizationCode(client)
You have specified redirectUri, so authorizationCode flow was used. But you want authorizationCodeWithPKCE flow in this case. So just make sure redirectUri is null and correct PKCE flow (with correct url parameters, e.g. code_challenge) will be used.
You need to send the redirectUri:null and set the port to 3000 ( you can use your port ).
after that you need to add the redirect uri in keycloak like this http://localhost:3000/ .it will do the trick
(what happening is when you send the redirect uri as null value, open_id client use the pkce flow and use the default url)

Apple Sign In with Flutter and Auth0

I have a flutter app and use this package to implement Apple Sign In feature: https://pub.dev/packages/sign_in_with_apple
I get the authorization data from the Apple like below:
userIdentifier = "0XXXX7.6bb65XXXXXXXXXXXXXXXX36.1XXX2"
givenName = "test"
familyName = "signing"
email = "testemail#company.com"
authorizationCode = "c372xxxxxxxa526eexxxxxx1111e.0.rwsex.SwXxxXXXdDj_XxxXXXxxX"
identityToken = "eyJraXxxuxjxxxXxxxXx.eyJXxxxxtXxxxxxxhlYXxxXXxXxXXXXX"
state = null
Then I tries to send the authorizationCode as described here in Step 3: https://auth0.com/docs/connections/nativesocial/apple
And I get the 403 Forbidded {"error":"invalid_grant","error_description":"Invalid authorization code"}
I have configured the settings in the Auth0 dashobard in Social and Applications section.
The login process works well in the web environment but I can not do it in the Flutter.
Could anyone help me with what should I do with the authorizationCode to perform successful login and get Access Token and ID Token from Auth0 in the native app?
Rather a late answer, but I've found following the documentation for the /oauth/token end-point titled "Token Exchange for Native Social" works for me.
Specifically sending that end-point a POST, eg. with this in Dart code:
final appleAuthorizationCode = '???????????????????????';
const url = 'https://$AUTH0_DOMAIN/oauth/token';
final uri = Uri.parse(url);
final result = await http.post(
uri,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: {
"client_id": AUTH0_CLIENT_ID,
"grant_type": 'urn:ietf:params:oauth:grant-type:token-exchange',
"subject_token": appleAuthorizationCode,
"subject_token_type": 'http://auth0.com/oauth/token-type/apple-authz-code',
"scope": 'openid profile offline_access',
},
encoding: Encoding.getByName('utf-8'),
);
print('AUTH0 result: $result');
works for me.

Jhipster + REST client + authentication

I need to understand how to authenticate a REST client (could be Paw, could be an android app, an iOs app using AFNetworking with jHipster and I think, more in general, with spring-boot of which I am no expert).
While I am able to obtain a token when logged in a browser, and subsequently use this token in the following requests, I do not understand how I can authenticate in the first place using RESTful best practices.
For example, in Paw.app, I can pass a Basic authentication, or Oauth2, but I don't understand how to get the session token simply authenticating as I do on a web browser.
Similarly, in AFNetworking I am able to pass basic authentication, e.g.
NSString*auth=[NSString stringWithFormat:#"%#:%#", #"admin", #"admin"];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [auth base64EncodedString]];
[manager.requestSerializer setValue:authValue forHTTPHeaderField:#"Authorization"];
But I struggle to understand how to authenticate with the session security which is bundled in jHipster/spring boot.
First of all, do not use HTTP session authentication for mobile apps.
On the other hand, Oauth2 or JWT works fine with mobile apps. The basic idea behind them is to get a token from Jhipster to mobile the token has an expiry time. In that time you can use the token to access any REST API of Jhipster to access data.
Below I am showing the code snippet of how I was using the Jhipster rest API in my angularjs based ionic app. I hope it gives the idea of what you need to do.
uncomment cors in application.yml inside jhipster
cors: #By default CORS are not enabled. Uncomment to enable.
allowed-origins: "*"
allowed-methods: GET, PUT, POST, DELETE, OPTIONS
allowed-headers: "*"
exposed-headers:
allow-credentials: true
max-age: 1800
To access REST API with Oauth2 authentication in ionic you must first get the token in the ionic app by
$http({
method: "post",
url: "http://192.168.0.4:8085/[Your app name]/oauth/token",
data: "username=admin&password=admin&grant_type=password&scope=read write&client_secret=my-secret-token-to-change-in-production&client_id=auth2Sconnectapp",
withCredentials: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'Authorization': 'Basic ' + 'YXV0aDJTY29ubmVjdGFwcDpteS1zZWNyZXQtdG9rZW4tdG8tY2hhbmdlLWluLXByb2R1Y3Rpb24='
}
})
.success(function(data) {
alert("success: " + data);
})
.error(function(data, status) {
alert("ERROR: " + data);
});
Here "YXV0aDJTY29ubmVjdGFwcDpteS1zZWNyZXQtdG9rZW4tdG8tY2hhbmdlLWluLXByb2R1Y3Rpb24=" is equal to (clientId + ":" + clientSecret)--all base64-encoded
The above $http if successful will give you this JSON which contains token and it's expiry time
{
"access_token": "2ce14f67-e91b-411e-89fa-8169e11a1c04",
"token_type": "bearer",
"refresh_token": "37baee3c-f4fe-4340-8997-8d7849821d00",
"expires_in": 525,
"scope": "read write"
}
Take notice of "access_token" and "token_type" if you want to access any API this is what you have to use. We send the token with API to access data until the token expires then we either refresh it or access for a new one.
For example
$http({
method: "get",
url: "http://192.168.0.4:8085/auth-2-sconnect/api/countries",
withCredentials: true,
headers: {
'Authorization':' [token_type] + [space] + [access_token] '
}
})
.success(function(data) {
alert("success: " + data);
})
.error(function(data, status) {
alert("ERROR: " + data);
});
Here a summarisation of how I implemented the solution. It’s real swift code, but please take it as pseudocode, as it might be incorrect.
make a call to whatever method you need to call, passing in such method a callback (block, or equivalent) for the success and one for the failure
func action(
URLString:String,
method:Method,
encoding:Encoding = .JSON,
parameters:[String : AnyObject]?,
success:(statusCode:Int, responseObject:AnyObject)->Void,
failure:(statusCode:Int, error:NSError)->Void
)
Inside the method es. /events you handle a particular case of failure, which is when the status code is 401.
if(r!.statusCode==ResponseCodes.HTTP_UNAUTHORIZED.rawValue){
loginAndAction(URLString, method: method, encoding: encoding, parameters: parameters, success: success, failure: failure)
}else{
failure(statusCode: response.response!.statusCode, error:response.result.error!)
}
In this particular case, instead of returning back the result and calling the failure callback, you call a login() method which, after the necessary parameters, accept the original success() callback
func loginAndAction(
URLString:String,
method:Method,
encoding: Encoding,
parameters:[String:AnyObject]?,
success:(statusCode:Int, responseObject:AnyObject)->Void,
failure:(statusCode:Int, error:NSError)->Void
)->Void
if the authentication succeeds
var d:[String:AnyObject] = response.result.value as! [String:AnyObject]
self.authToken = d["access_token"] as! String
action(URLString, method: method,encoding:encoding, parameters: parameters, success: success, failure: failure)
at this point the method action could use a proper working token.
This should happen only once a day (based on the token expiration), and it is a mechanism appliable to the oauth2 refresh_token call.