1+ using System ;
2+ using System . IO ;
3+ using System . Threading . Tasks ;
4+ using Azure . Core ;
5+ using Azure . Identity ;
6+ using Microsoft . Graph . Cli . Utils ;
7+
8+ namespace Microsoft . Graph . Cli . Authentication ;
9+
10+ class AuthenticationServiceFactory {
11+ public async Task < IAuthenticationService > GetAuthenticationServiceAsync ( AuthenticationStrategy strategy , bool persistToken = false ) {
12+ switch ( strategy ) {
13+ case AuthenticationStrategy . DeviceCode :
14+ return await GetDeviceCodeAuthenticationServiceAsync ( persistToken ) ;
15+ default :
16+ throw new InvalidOperationException ( $ "The authentication strategy { strategy } is not supported") ;
17+ }
18+
19+ }
20+
21+ public async Task < TokenCredential > GetTokenCredentialAsync ( AuthenticationStrategy strategy , bool persistToken = false ) {
22+ switch ( strategy ) {
23+ case AuthenticationStrategy . DeviceCode :
24+ return await GetDeviceCodeCredentialAsync ( persistToken ) ;
25+ default :
26+ throw new InvalidOperationException ( $ "The authentication strategy { strategy } is not supported") ;
27+ }
28+ }
29+
30+ private async Task < DeviceCodeAuthenticationService > GetDeviceCodeAuthenticationServiceAsync ( bool persistToken = false ) {
31+ var credential = await GetDeviceCodeCredentialAsync ( persistToken ) ;
32+ return new ( credential ) ;
33+ }
34+
35+ private async Task < DeviceCodeCredential > GetDeviceCodeCredentialAsync ( bool persistToken ) {
36+ DeviceCodeCredentialOptions credOptions = new ( )
37+ {
38+ ClientId = Constants . ClientId ,
39+ TenantId = Constants . TenantId
40+ } ;
41+
42+ if ( persistToken ) {
43+ TokenCachePersistenceOptions tokenCacheOptions = new ( ) { Name = Constants . TokenCacheName } ;
44+ credOptions . TokenCachePersistenceOptions = tokenCacheOptions ;
45+ var recordPath = Constants . AuthRecordPath ;
46+
47+ if ( File . Exists ( recordPath ) )
48+ {
49+ using var authRecordStream = new FileStream ( recordPath , FileMode . Open , FileAccess . Read ) ;
50+ var authRecord = await AuthenticationRecord . DeserializeAsync ( authRecordStream ) ;
51+ credOptions . AuthenticationRecord = authRecord ;
52+ }
53+ }
54+
55+ return new DeviceCodeCredential ( credOptions ) ;
56+ }
57+ }
58+
59+ enum AuthenticationStrategy {
60+ DeviceCode
61+ }
0 commit comments