forked from microsoft/app-innovation-workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthenticationService.cs
More file actions
152 lines (133 loc) · 5.3 KB
/
AuthenticationService.cs
File metadata and controls
152 lines (133 loc) · 5.3 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ContosoFieldService.Helpers;
using Microsoft.Identity.Client;
using Newtonsoft.Json.Linq;
namespace ContosoFieldService.Services
{
public class AuthenticationService
{
public static UIParent UIParent;
public static IUser CurrentUser { get; set; }
public static string CurrentUserEmail { get; set; }
public static bool IsLoggedIn { get; set; }
public static string AccessToken { get; set; }
PublicClientApplication authClient;
string[] scopes;
string signUpAndInPolicy;
string authority;
public Action ShowLoginUi { get; set; }
public AuthenticationService()
{
var authorityBase = $"https://login.microsoftonline.com/tfp/{Constants.Tenant}/";
authority = $"{authorityBase}{Constants.SignUpAndInPolicy}";
scopes = Constants.Scopes;
signUpAndInPolicy = Constants.SignUpAndInPolicy;
try
{
authClient = new PublicClientApplication(Constants.ApplicationId, authority); ;
authClient.ValidateAuthority = false;
authClient.RedirectUri = $"msalcontosomaintenance://auth";
}
catch (ArgumentException)
{
// That usually only happens, when ADB2C is not configured correctly or is not
// configured at all. Should not happen in real-world scenarios but for the
// matter of this workshop we have to catch it
authClient = null;
}
}
/// <summary>
/// Opens a Web Browser to display the Login Website to the user and returns to the app after the process has been
/// completed or cancelled by the user
/// </summary>
/// <returns>The Authentication Result.</returns>
public async Task<AuthenticationResult> LoginAsync()
{
try
{
var user = GetUserByPolicy(authClient.Users, signUpAndInPolicy);
// Open the login web form
var result = await authClient?.AcquireTokenAsync(scopes, user, UIParent);
if (result != null)
{
// Login successful, set properties
CurrentUser = result.User;
AccessToken = result.AccessToken;
IsLoggedIn = true;
// Get claims
var handler = new JwtSecurityTokenHandler();
var token = handler.ReadJwtToken(result.AccessToken);
CurrentUserEmail = token.Claims.FirstOrDefault(x => x.Type == "emails")?.Value;
}
return result;
}
catch (MsalServiceException ex)
{
if (ex.ErrorCode == MsalClientException.AuthenticationCanceledError)
{
// User cancelled authentication
return null;
}
}
return null;
}
/// <summary>
/// Tries to refresh the user's Access Token in the background without any user innteraction
/// </summary>
/// <returns>The Authentication Result.</returns>
public async Task<AuthenticationResult> LoginSilentAsync()
{
var user = GetUserByPolicy(authClient?.Users, signUpAndInPolicy);
if (user == null)
return null;
// Try to refresh the token in the background
var result = await authClient?.AcquireTokenSilentAsync(scopes, user, authority, false);
if (result != null)
{
// Restore successful, set properties
CurrentUser = result.User;
AccessToken = result.AccessToken;
IsLoggedIn = true;
// Get claims
var handler = new JwtSecurityTokenHandler();
var token = handler.ReadJwtToken(result.AccessToken);
CurrentUserEmail = token.Claims.FirstOrDefault(x => x.Type == "emails")?.Value;
}
return result;
}
public void Logout()
{
foreach (var user in authClient?.Users)
{
authClient?.Remove(user);
}
// Reset properties
CurrentUser = null;
AccessToken = null;
IsLoggedIn = false;
CurrentUserEmail = null;
}
IUser GetUserByPolicy(IEnumerable<IUser> users, string policy)
{
foreach (var user in users)
{
string userIdentifier = Base64UrlDecode(user.Identifier.Split('.')[0]);
if (userIdentifier.EndsWith(policy.ToLower(), StringComparison.OrdinalIgnoreCase)) return user;
}
return null;
}
string Base64UrlDecode(string s)
{
s = s.Replace('-', '+').Replace('_', '/');
s = s.PadRight(s.Length + (4 - s.Length % 4) % 4, '=');
var byteArray = Convert.FromBase64String(s);
var decoded = Encoding.UTF8.GetString(byteArray, 0, byteArray.Count());
return decoded;
}
}
}