Hi, I've developed a WebApi project that uses MS Identitity and serves data to a Html/Jquery client. I'm having my first go at Xamarin forms and followed tutorials. I've got to to a stage where i can successfully post login criteria and receive a bearer token, and store it using Xam Plugins.Settings. I can use this token fine in future requests and receive the data fine.
I'm struggling how to implement the navigation, so when a user clicks the login button and is issued a token, the app will 'redirect' to the view GSMUnitsPage(). Currently the user clicks the button and logs in fine, but it sits on the same login screen.... Ive proved everything works by creating a button to the GSMUnitsPage which works fine.
Login View Mode:
class LoginViewModel
{
public string Email { get; set; }
public string Password { get; set; }
public ICommand LoginCommand
{
get
{
return new Command(async () =>
{
ApiServices apiServices = new ApiServices();
var accesstoken = await apiServices.LoginUserAsync(Email, Password);
Settings.AccessToken = accesstoken;
});
}
}
public LoginViewModel()
{
Email = Settings.Username;
Password = Settings.Password;
}
}
Login Api:
public async Task<string> LoginUserAsync(string email, string password)
{
var client = new HttpClient();
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", email),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("grant_type", "password")
};
var request = new HttpRequestMessage(
HttpMethod.Post, "linktotoken");
request.Content = new FormUrlEncodedContent(keyValues);
var reponse = await client.SendAsync(request);
var jwt = await reponse.Content.ReadAsStringAsync();
JObject jwtDyanmic = JsonConvert.DeserializeObject<dynamic>(jwt);
var accessToken = jwtDyanmic.Value<string>("access_token");
var accessTokenExpiration = jwtDyanmic.Value<DateTime>(".expires");
Settings.AccessTokenExpiration = accessTokenExpiration;
Debug.WriteLine(jwt);
return accessToken;
}
LoginPage.xaml:
<ContentPage.BindingContext>
<vm:LoginViewModel/>
</ContentPage.BindingContext>
<StackLayout VerticalOptions="Center">
<Entry Text="{Binding Email}" />
<Entry Text="{Binding Password}" />
<Button Command="{Binding LoginCommand}" Text="Login/Signin" />
</StackLayout>
App.xaml.cs:
public App ()
{
InitializeComponent();
SetMainPage();
}
private void SetMainPage()
{
if (!string.IsNullOrEmpty(Settings.AccessToken))
{
if (DateTime.UtcNow.AddHours(1) > Settings.AccessTokenExpiration)
{
var vm = new LoginViewModel();
vm.LoginCommand.Execute(null);
}
MainPage = new NavigationPage(new GSMUnitsPage());
}
else if(!string.IsNullOrEmpty(Settings.Username) && !string.IsNullOrEmpty(Settings.Password))
{
MainPage = new NavigationPage(new LoginPage());
}
else
{
MainPage = new NavigationPage(new RegisterPage());
}
}