Xamarin Forms Cross Platform App Authentication with Firebase - firebase

I want to take the users email and send them a reset password request.
I haven't had any luck with the solution.
private async void ForgetPassword_Clicked(object sende, EventArgs e)
{
var authReset = new FirebaseAuthProvider(new FirebaseConfig(WebAPIkey));
try
{
var email = UserLoginEmail.Text;
var auth = await authReset.SendPasswordResetEmailAsync(UserLoginEmail.Text);
var content = await auth.GetFreshAuthAsync();
var serializedcontent = JsonConvert.SerializeObject(content);
Preferences.Set("MyFirebaseRefreshToken", serializedcontent);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
await App.Current.MainPage.DisplayAlert("Alert", "Invalid email or password", "OK");
}
}

I figured it out. But if there is a better way, please let me know
private async void ForgetPassword_Clicked(object sende, EventArgs e)
{
var authReset = new FirebaseAuthProvider(new FirebaseConfig(WebAPIkey));
try
{
var email = UserLoginEmail.Text;
var auth = authReset.SendPasswordResetEmailAsync(UserLoginEmail.Text);
await App.Current.MainPage.DisplayAlert("Alert", "Email Sent", "OK");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
await App.Current.MainPage.DisplayAlert("Alert", "Invalid email or password", "OK");
}
}

Related

Retrieving claim value for current logged in user

I have an ASP.Net web form application that users can register to. In the registration process, some user details are stored as claims, the MemberApproved variable is used to check the approval status of a user, it is set to "No" when the user is created, and can be changed later by admin:
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
var user = new ApplicationUser() { UserName = Email.Text, Email = Email.Text, FirstName = FirstName.Text, LastName = LastName.Text,MemberApproved="No" };
THis is working fine and I can see the user details above added correctly in the AspNetUsers
Then I am trying to check if the user has been approved by an admin when they login, in this process, I am trying to retrieve MemberApproved value using the following code:
protected void Page_Load(object sender, EventArgs e)
{
RegisterHyperLink.NavigateUrl = "Register";
OpenAuthLogin.ReturnUrl = Request.QueryString["ReturnUrl"];
var returnUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
if (!String.IsNullOrEmpty(returnUrl))
{
RegisterHyperLink.NavigateUrl += "?ReturnUrl=" + returnUrl;
}
}
protected void LogIn(object sender, EventArgs e)
{
if (IsValid)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();
var result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
var claims = ClaimsPrincipal.Current.Identities.First().Claims.ToList();
string MemberApproved = claims?.FirstOrDefault(x => x.Type.Equals("MemberApproved", StringComparison.OrdinalIgnoreCase))?.Value;
if (MemberApproved == "No")
{
FailureText.Text = "User not approved yet";
ErrorMessage.Visible = true;
break;
}
else
{ IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
break;
}
case SignInStatus.LockedOut:
Response.Redirect("/Account/Lockout");
break;
case SignInStatus.RequiresVerification:
Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",
Request.QueryString["ReturnUrl"],
RememberMe.Checked),
true);
break;
case SignInStatus.Failure:
default:
FailureText.Text = "Invalid login attempt";
ErrorMessage.Visible = true;
break;
}
}
}
}
I am however running into problems and the code above does not seem to be able to retrieve the value of "MemberApproved"
Any suggestions would be very much appreciated.

User not authenticating on successful login ASP.net

I created a application using ASP.NET with EF. I did the login function and when the user logged redirect to WelcomePage. The login was succeeded and redirect to the page but in the page I have the user authenticated.
I put this to see and its false
<p>#User.Identity.IsAuthenticated</p>
I'm just having trouble understanding how to authenticate them. I try to clean cache but thats not the problem.
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
string Con = ConUri();
services.AddDbContext<SysContext>(options =>
{
options.UseNpgsql(Con);
});
services.AddIdentity<User, IdentityRole<Guid>>()
.AddEntityFrameworkStores<SysContext>()
.AddDefaultTokenProviders();
services.AddControllersWithViews().AddRazorRuntimeCompilation();
services.AddControllersWithViews().AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromDays(30);
options.Cookie.HttpOnly = true;
});
services.ConfigureApplicationCookie(options =>
{
options.AccessDeniedPath = new PathString("/Login");
options.LoginPath = new PathString("/Login");
});
}
HomeController.cs
public object Login(String Username, String Password)
{
try
{
if (ModelState.IsValid)
{
var user = _userManager.FindByEmailAsync(Username).Result;
if (user == null)
throw new Exception("Error 1");
var result = _signInManager.CheckPasswordSignInAsync(user,
Password, lockoutOnFailure: false).Result;
if (result.IsLockedOut)
throw new Exception("Error 2");
if (!result.Succeeded)
throw new Exception("Error 3");
var response = _signInManager.PasswordSignInAsync(Username, Password, true, lockoutOnFailure: false).Result;
if (result.Succeeded)
{
var location = new Uri($"{Request.Scheme}://{Request.Host}/WelcomePage");
Response.Cookies.Append("_UserId", user.Id.ToString());
HttpContext.Session.SetString("_User" + user.Id, string.Empty);
return new
{
Sucesso = true,
Url = location
};
}
else
{
throw new Exception("Error ex");
}
}
throw new Exception("Error 4");
}
catch (Exception ex)
{
return new
{
Sucesso = false,
Mensagem = ex.Message
};
}
}
}
You could check the EmailConfirmed Colum if it has a value in your database,if you did not set to send you a confirmed e-mail when you sign up,try to set as below to avoid varify the e-mail:
services.Configure<IdentityOptions>(options =>
{
.......
options.SignIn.RequireConfirmedAccount=false ;
......
})
Why you passed the username as an e-mail address?
var user = _userManager.FindByEmailAsync(Username).Result;

CancellationToken Source does not return taskcancelled when token.cancel is called

Below is the Service method that i call....
after i have called the service... my net goes off and i cancel the token
Which means after i have hit the service i cancel the token... is there a way to cancel the service i have called...
below is my code
public async Task<List<MeritData>> GetSyncupData(string Id, string BusinessDate, CancellationToken cancellationToken)
{
List<MeritData> PendingData = new List<MeritData>();
HttpResponseMessage responseMessage = null;
try
{
cancellationToken.ThrowIfCancellationRequested();
var api = RestService.For<IInventoryMeritStatusApi>(_httpClient);
responseMessage = await api.GetMeritData(Id, BusinessDate, cancellationToken).ConfigureAwait(false);
if (cancellationToken.IsCancellationRequested)
cancellationToken.ThrowIfCancellationRequested();
if (responseMessage.StatusCode == System.Net.HttpStatusCode.OK)
{
// my code on success
}
}
catch (SocketException SocketEx)
{
ServiceException serviceException = new ServiceException("SocketException", SocketEx);
throw serviceException;
}
catch (HttpRequestException httpReqEx)
{
ServiceException serviceException = new ServiceException("NoInternet", httpReqEx);
throw serviceException;
}
catch (ServiceException serviceEx)
{
ServiceException serviceException = new ServiceException("NoInternet", serviceEx);
throw serviceException;
}
catch (OperationCanceledException ex)
{
Console.WriteLine("TaskCanceledException GetProduct");
throw ex;
}
catch (Exception ex)
{
throw ex;
}
return PendingData;
}
after the line
responseMessage = await api.GetMeritData(Id, BusinessDate, cancellationToken).ConfigureAwait(false);
is executed i switch off the net and call cancellationTokenSource.Cancel();
it takes a long time and finally get a "httprequestexception" not a token cancelled exception
how do i solve this ? i want to cancel the call to the webservice when token.Cancel is called

How to get access token identity in asp.net webforms external login page?

I'm using the new Microsoft identity to manage my website login and register.
I've configured the website to start using external login (Facebook).
How i can get the Access Token in the (RegisterExternalLogin) page?
``
protected void Page_Load(){
// Process the result from an auth provider in the request
ProviderName = IdentityHelper.GetProviderNameFromRequest(Request);
if (String.IsNullOrEmpty(ProviderName))
{
RedirectOnFail();
return;
}
if (!IsPostBack)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
if (loginInfo == null)
{
RedirectOnFail();
return;
}
var user = manager.Find(loginInfo.Login);
if (user != null)
{
IdentityHelper.SignIn(manager, user, isPersistent: false);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else if (User.Identity.IsAuthenticated)
{
Response.Write("ok.2");
// Apply Xsrf check when linking
var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId());
if (verifiedloginInfo == null)
{
RedirectOnFail();
return;
}
var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login);
if (result.Succeeded)
{
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else
{
AddErrors(result);
return;
}
}
else
{
try
{
var accessToken = "What can i get the access token";
Response.Write(accessToken + "<br>");
var client = new FacebookClient(accessToken);
//var client = new FacebookClient();
dynamic me = client.Get("me");
string firstName = me.first_name;
string lastName = me.last_name;
Response.Write(firstName + " " + lastName);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
email.Text = loginInfo.Email;
}
}
}
Regards,
Moayyad

Tracking Bounced Emails Through ASP.Net

Is there any way I can track (through the code) the bounced emails.
Consider the email id like 'skdfisdcnsodioifs#gmail.com'. This is valid email id but does not exists so certainly it will be bounced backed.
I am using ASP.Net's SmtpClient with "message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure". However it still shows the message sent successfully and after ~20-25 minutes I get the fail delivery notification email.
Below is my code
class Program
{
static void Main(string[] args)
{
SmtpClient client = new SmtpClient("xxxx.xxxxxx.xxx", 25);
client.Credentials = new NetworkCredential("xxxxxx#xxxxxx.com", "xxxxxx");
MailAddress to = new MailAddress("abcdsfasdfasdfasdfasdf2342342defgh#gmail12333.com");
MailAddress from = new MailAddress("xxxxxx#xxxxxx.com");
MailMessage message = new MailMessage(from, to);
message.Headers.Add("Return-Path", "xxxxxx#gmail.com");
message.ReplyToList.Add(new MailAddress("xxxxxx#gmail.com"));
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.OnSuccess;
message.Subject = "Test POC";
message.Body = "This is a test e-mail message sent by an application. ";
client.SendCompleted += client_SendCompleted;
string UserState = "test";
client.Timeout = 3;
try
{
Console.WriteLine("start to send email ...");
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.SendAsync(message,UserState);
Console.WriteLine("email was sent successfully!");
}
catch (SmtpFailedRecipientsException ep)
{
Console.WriteLine("failed to send email with the following error:");
Console.WriteLine(ep.Message);
}
catch (Exception ep)
{
Console.WriteLine("failed to send email with the following error:");
Console.WriteLine(ep.Message);
}
Console.WriteLine("test.");
Console.ReadKey();
}
static void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
// Get the unique identifier for this asynchronous operation.
//String token = (string)e.UserState;
if (e.Cancelled)
{
Console.WriteLine("Send canceled.");
}
if (e.Error != null)
{
Console.WriteLine("[{0}] ", e.Error.ToString());
}
else
{
Console.WriteLine("Message sent.");
}
}
}
Thanks in advance.
Abhishek

Resources