I use the onedrive SDK in a Cross Plattform app. On Windows the Authentication works via the OneDriveClientExtensions.GetClientUsingWebAuthenticationBroker.
Now I'm trying to login on Android. I tried it with this:
oneDriveClient = OneDriveClient.GetMicrosoftAccountClient(
appId: MSA_CLIENT_ID,
returnUrl: RETURN_URL,
scopes: scopes,
clientSecret: MSA_CLIENT_SECRET);
await oneDriveClient.AuthenticateAsync();
But get an error that no valid token could be received. Do I have to implement a own AuthenticationProvider inhereting from WebAuthenticationBrokerAuthenticationProvider who shows a browser for the oauth? Or what would be the way to go here?
I solved this using the Xamarin Auth Component. Heres the code who calls the webview with the login:
private const string RETURN_URL = #"https://login.live.com/oauth20_desktop.srf";
private void ShowWebView()
{
var auth = new OAuth2Authenticator(
clientId: MSA_CLIENT_ID,
scope: string.Join(",", scopes),
authorizeUrl: new Uri(GetAuthorizeUrl()),
redirectUrl: new Uri(RETURN_URL));
auth.Completed += (sender, eventArgs) =>
{
if (eventArgs.IsAuthenticated)
{
//Do Something
}
};
var intent = auth.GetUI(Application.Context);
intent.SetFlags(ActivityFlags.NewTask);
Application.Context.StartActivity(intent);
}
private string GetAuthorizeUrl()
{
var requestUriStringBuilder = new StringBuilder();
requestUriStringBuilder.Append("https://login.live.com/oauth20_authorize.srf");
requestUriStringBuilder.AppendFormat("?{0}={1}", Constants.Authentication.RedirectUriKeyName, RETURN_URL);
requestUriStringBuilder.AppendFormat("&{0}={1}", Constants.Authentication.ClientIdKeyName, MSA_CLIENT_ID);
requestUriStringBuilder.AppendFormat("&{0}={1}", Constants.Authentication.ScopeKeyName,
string.Join("%20", scopes));
requestUriStringBuilder.AppendFormat("&{0}={1}", Constants.Authentication.ResponseTypeKeyName,
Constants.Authentication.TokenResponseTypeValueName);
return requestUriStringBuilder.ToString();
}
Related
I hope you are doing well.
I have a problem when I connect with google on the emulator with android.
If I go through Expo Go on either Android or Ios, it works fine. But when I build my apk, and I install it on the emulator it sends me back to the same login page without redirecting me to the application.
Do you have an idea of the origin of the problem?
My google login function :
try {
const result = await promptAsync();
if (result.type === "success") {
/* `accessToken` is now valid and can be used to get data from the Google API with HTTP requests */
const { id_token } = result.params;
const provider = new firebase.auth.GoogleAuthProvider();
const credential =
firebase.auth.GoogleAuthProvider.credential(id_token);
auth.signInWithCredential(credential)
.then((res) => {
const user = res.additionalUserInfo.profile;
let action = addUserOnFirestore(
res.user?.uid,
user.email,
user.given_name,
user.family_name,
user.picture,
res
);
setIsLoading(true);
try {
dispatch(action);
} catch (err) {
setError(err.message);
}
setIsLoading(false);
})
.catch((error) => {
console.log("firebase cred err:", error);
});
} else {
console.log("cancelled");
}
} catch (e) {
console.log("general error : ", e);
return { error: true };
}
}
And the properties define :
const [request, response, promptAsync] = Google.useIdTokenAuthRequest({
clientId: "XXXX",
iosClientId: "XXX",
androidClientId: "XXX",
androidStandaloneAppClientId: "XXX",
redirectUri: Platform.select({
// iOS handles redirectUri perfectly fine on it's own
ios: undefined,
// Due to Expo's bug, we need to manually encode the redirectUri
// https://github.com/expo/expo/issues/12044
android: makeRedirectUri({
// intent filter set up in app.config.js
// must be the same as "package name" in Google Cloud Console
native: 'packagename://oauthredirect',
}),
})
});
Thanks in advance for your responses.
I have implemented phone number authentication in a flutter app using firebase phone auth. It is working fine in Android. But it is not working properly in iOS as many users are facing error after they submit sms verification code, though a lot others are using the app just fine. What can be the possible reasons for this scenario? I have submitted my code below.
Number Submission
void _verifyPhoneNumber() async {
final PhoneVerificationCompleted verificationCompleted =
(AuthCredential phoneAuthCredential) async {
final FirebaseUser user =
await _auth.signInWithCredential(phoneAuthCredential);
if (user != null) {
phone = user.phoneNumber;
fid = user.uid;
saveLogin(context);
} else {
_showErrorDialog("User Verification Error!");
}
};
final PhoneVerificationFailed verificationFailed =
(AuthException authException) {
_showErrorDialog("Phone Verification Failed");
};
final PhoneCodeSent codeSent =
(String verificationId, [int forceResendingToken]) async {
_verificationId = verificationId;
setState(() {
_title = "Verify SMS Code";
phoneInput = false;
phoneSubmit = false;
codeInput = true;
codeSubmit = true;
});
};
final PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout =
(String verificationId) async {
_verificationId = verificationId;
setState(() {
_title = "Verify SMS Code";
phoneInput = false;
phoneSubmit = false;
codeInput = true;
codeSubmit = true;
});
};
await _auth.verifyPhoneNumber(
phoneNumber: "+880" + _mobileNumber,
timeout: const Duration(seconds: 5),
verificationCompleted: verificationCompleted,
verificationFailed: verificationFailed,
codeSent: codeSent,
codeAutoRetrievalTimeout: codeAutoRetrievalTimeout);
}
Code Submission
void _signInWithPhoneNumber(String _code) async {
final AuthCredential credential = PhoneAuthProvider.getCredential(
verificationId: _verificationId,
smsCode: _code,
);
final FirebaseUser user = await _auth.signInWithCredential(credential);
if (user != null) {
phone = user.phoneNumber;
fid = user.uid;
saveLogin(context);
} else {
_showErrorDialog("User Verification Error!");
}
}
Plugins Used
google_sign_in: ^4.0.1+3
firebase_auth: ^0.11.0
Try adding the REVERSE_CLIENT_ID custom URL schemes to your Xcode project.
According to the firebase documentation:
iOS setup note: App verification may use APNs, if using a simulator (where APNs does not work) or APNs is not setup on the device you are using you must set the URL Schemes to the REVERSE_CLIENT_ID from the GoogleServices-Info.plist file.
How to add custom URL schemes to your Xcode project:
Open your project configuration: double-click the project name in the left tree view. Select your app from the TARGETS section, then select the Info tab, and expand the URL Types section.
Click the + button, and add a URL scheme for your reversed client ID. To find this value, open the GoogleService-Info.plist configuration file, and look for the REVERSED_CLIENT_ID key. Copy the value of that key, and paste it into the URL Schemes box on the configuration page. Leave the other fields blank.
References from here:
https://pub.dev/packages/firebase_auth
https://firebase.google.com/docs/auth/ios/phone-auth
In my android app when user enters wrong PASSWORD more times then i want send email to user using firebase functions with download link of picture captured so i created function below.
So i push email and download link to firebase and when data gets added following function gets triggered but whenever im trying to deploy this function cli giving me error that mailtransport is unexpected..
exports.sendMails = functions.database.ref('/failedAttemps/{email2}/{attemptsid}')
.onWrite((data, context) =>
{
const email2 = context.params.email2;
const attemptsid = context.params.attemptsid;
//const sender_id = context.params.sender_id;
//const mees = context.params.message_not;
// contentss = mees;
const gmailEmail = functions.config().gmail.email;
const gmailPassword = functions.config().gmail.password;
const mailTransport = nodemailer.createTransport({
service: 'gmail',
auth: {
user: "******#gmail.com",
pass: "****#****",
},
});
const email = admin.database().ref(`/Notification/${email2}/${attemptsid}/email`);
email.once("value", function(snapshot){
emails = snapshot.val();
});
const naam = admin.database().ref(`/Notification/${email2}/${attemptsid}/dlink`);
naam.once("value", function(snapshot){
dlinks = snapshot.val();
});
// console.log('message :' , contentss);
const mailOptions = {
from: '"LetsTalk" <noreply#firebase.com>',
to: emails,
};
// Building Email message.
mailOptions.subject = 'Someone tried to login to you account';
mailOptions.text = `${dlink}Thanks you for subscribing to our newsletter. You will receive our next weekly newsletter.`;
try {
await mailTransport.sendMail(mailOptions);
// console.log(`New ${subscribed ? '' : 'un'}subscription confirmation email sent to:`, val.email);
} catch(error) {
console.error('There was an error while sending the email:', error);
}
return null;
});
Every time i try to deploy function on firebase.This error pops upenter image description here
The problem seems to be you are using await without first indicating it is an async function.
Try replacing your first lines with:
exports.sendMails = functions.database.ref('/failedAttemps/{email2}/{attemptsid}')
.onWrite(async (data, context) =>
{
I am faced with problem when trying to authenticate my app via facebook. After entering a username and password in the facebook form, I caught a NullReferenceException.
I've noticed that it happens only when I compile with Android 6.0.
[assembly: ExportRenderer(typeof(FirstPage), typeof(FirstPageRenderer))]
namespace Dating.Droid.Renderers
{
public class FirstPageRenderer : PageRenderer
{
public FirstPageRenderer()
{
var activity = this.Context as Activity;
if (activity != null)
{
var auth = new OAuth2Authenticator(
clientId: "MyFacebookId", // your OAuth2 client id
scope: "", // the scopes for the particular API you're accessing, delimited by "+" symbols
authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/"),
redirectUrl: new Uri("http://www.facebook.com/connect/login_success.html"));
auth.Completed += (sender, eventArgs) =>
{
if (eventArgs.IsAuthenticated)
{
// Authenticated
}
else
{
// The user cancelled
}
};
activity.StartActivity(auth.GetUI(activity));
}
}
}
}
Exception appears on auth.Completed event
Stack Trace: at Dating.Droid.Renderers.FirstPageRenderer+<>c.<.ctor>b__0_0 (System.Object sender, Xamarin.Auth.AuthenticatorCompletedEventArgs eventArgs) [0x00002] in D:\Dev\Real\Xamarin\Dating\Dating.Droid\Renderers\FirstPageRenderer.cs:31
As per the Pusher docs, for a client to subscribe to a private channel he needs to undergo some authorization process. Could someone guide me on how to achieve this using Parse? I already have integrated Facebook login with Parse for my android application. Im not too familiar with web development code so had difficulty in understand this
HttpAuthorizer authorizer = new HttpAuthorizer(http://example.com/some_auth_endpoint);
PusherOptions options = new PusherOptions().setAuthorizer(authorizer);
Pusher pusher = new Pusher( YOUR_APP_KEY, options );
Somebody has written a Parse module that offers authentication functionality: https://github.com/kashif/pusher-parse
The auth example from the README is:
app.post('/authorise', function(req, res) {
var socketId = req.body.socket_id;
var channel = req.body.channel_name;
var user_id = channel.split("-")[1];
var user = Parse.Object.extend("User");
var query = new Parse.Query(user);
query.get(user_id, {
success: function(userAgain) {
var presenceData = {
user_id: userAgain.id,
user_info: {
username: userAgain.get("username"),
email: userAgain.get("email")
}
};
var auth = pusher.authenticate( socketId, channel, presenceData );
res.send(auth);
},
error: function(model, error) {
res.status(403);
res.send('Forbidden');
}
});
});