-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
WebAuthenticatorViewModel.cs
88 lines (74 loc) · 2.47 KB
/
WebAuthenticatorViewModel.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
using System.Threading.Tasks;
using System.Windows.Input;
using Microsoft.Maui.Authentication;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Devices;
namespace Samples.ViewModel
{
public class WebAuthenticatorViewModel : BaseViewModel
{
const string authenticationUrl = "https://xamarin-essentials-auth-sample.azurewebsites.net/mobileauth/";
public WebAuthenticatorViewModel()
{
MicrosoftCommand = new Command(async () => await OnAuthenticate("Microsoft"));
GoogleCommand = new Command(async () => await OnAuthenticate("Google"));
FacebookCommand = new Command(async () => await OnAuthenticate("Facebook"));
AppleCommand = new Command(async () => await OnAuthenticate("Apple"));
}
public ICommand MicrosoftCommand { get; }
public ICommand GoogleCommand { get; }
public ICommand FacebookCommand { get; }
public ICommand AppleCommand { get; }
string accessToken = string.Empty;
public string AuthToken
{
get => accessToken;
set => SetProperty(ref accessToken, value);
}
async Task OnAuthenticate(string scheme)
{
try
{
WebAuthenticatorResult r = null;
if (scheme.Equals("Apple", StringComparison.Ordinal)
&& DeviceInfo.Platform == DevicePlatform.iOS
&& DeviceInfo.Version.Major >= 13)
{
// Make sure to enable Apple Sign In in both the
// entitlements and the provisioning profile.
var options = new AppleSignInAuthenticator.Options
{
IncludeEmailScope = true,
IncludeFullNameScope = true,
};
r = await AppleSignInAuthenticator.AuthenticateAsync(options);
}
else
{
var authUrl = new Uri(authenticationUrl + scheme);
var callbackUrl = new Uri("xamarinessentials://");
r = await WebAuthenticator.AuthenticateAsync(authUrl, callbackUrl);
}
AuthToken = string.Empty;
if (r.Properties.TryGetValue("name", out var name) && !string.IsNullOrEmpty(name))
AuthToken += $"Name: {name}{Environment.NewLine}";
if (r.Properties.TryGetValue("email", out var email) && !string.IsNullOrEmpty(email))
AuthToken += $"Email: {email}{Environment.NewLine}";
AuthToken += r?.AccessToken ?? r?.IdToken;
}
catch (OperationCanceledException)
{
Console.WriteLine("Login canceled.");
AuthToken = string.Empty;
await DisplayAlertAsync("Login canceled.");
}
catch (Exception ex)
{
Console.WriteLine($"Failed: {ex.Message}");
AuthToken = string.Empty;
await DisplayAlertAsync($"Failed: {ex.Message}");
}
}
}
}