Skip to content

Commit a3c2c13

Browse files
committed
Add GraphSession object.
1 parent eb9d1c1 commit a3c2c13

File tree

12 files changed

+199
-44
lines changed

12 files changed

+199
-44
lines changed

src/Authentication/Authentication/Cmdlets/ConnectGraph.cs

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets
1616
using System.Threading.Tasks;
1717

1818
[Cmdlet(VerbsCommunications.Connect, "Graph", DefaultParameterSetName = Constants.UserParameterSet)]
19-
public class ConnectGraph : PSCmdlet
19+
public class ConnectGraph : PSCmdlet, IModuleAssemblyInitializer
2020
{
2121

2222
[Parameter(ParameterSetName = Constants.UserParameterSet, Position = 1)]
@@ -53,7 +53,7 @@ protected override void ProcessRecord()
5353
{
5454
base.ProcessRecord();
5555

56-
AuthConfig authConfig = new AuthConfig { TenantId = TenantId };
56+
IAuthContext authConfig = new AuthContext { TenantId = TenantId };
5757
CancellationToken cancellationToken = CancellationToken.None;
5858

5959
if (ParameterSetName == Constants.UserParameterSet)
@@ -117,7 +117,7 @@ protected override void ProcessRecord()
117117
authConfig.Account = jwtPayload?.Upn ?? account?.Username;
118118

119119
// Save auth config to session state.
120-
SessionState.PSVariable.Set(Constants.GraphAuthConfigId, authConfig);
120+
GraphSession.Instance.AuthContext = authConfig;
121121
}
122122
catch (AuthenticationException authEx)
123123
{
@@ -164,5 +164,13 @@ private void ThrowParameterError(string parameterName)
164164
new ArgumentException($"Must specify {parameterName}"), Guid.NewGuid().ToString(), ErrorCategory.InvalidArgument, null)
165165
);
166166
}
167+
168+
/// <summary>
169+
/// Globally initializes GraphSession.
170+
/// </summary>
171+
public void OnImport()
172+
{
173+
GraphSessionInitializer.InitializeSession();
174+
}
167175
}
168176
}

src/Authentication/Authentication/Cmdlets/DisconnectGraph.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets
55
{
66
using Microsoft.Graph.PowerShell.Authentication.Helpers;
7-
using Microsoft.Graph.PowerShell.Authentication.Models;
87
using System;
98
using System.Management.Automation;
109
[Cmdlet(VerbsCommunications.Disconnect, "Graph")]
@@ -24,7 +23,7 @@ protected override void ProcessRecord()
2423
{
2524
base.ProcessRecord();
2625

27-
AuthConfig authConfig = SessionState.PSVariable.GetValue(Constants.GraphAuthConfigId) as AuthConfig;
26+
IAuthContext authConfig = GraphSession.Instance.AuthContext;
2827

2928
if (authConfig == null)
3029
ThrowTerminatingError(

src/Authentication/Authentication/Cmdlets/GetMGContext.cs

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,10 @@
44

55
namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets
66
{
7-
using Microsoft.Graph.Auth;
8-
using Microsoft.Graph.PowerShell.Authentication.Helpers;
9-
using Microsoft.Graph.PowerShell.Authentication.Models;
10-
using System;
11-
using System.Collections.Generic;
127
using System.Management.Automation;
13-
using System.Net.Http;
14-
using System.Threading;
15-
using System.Threading.Tasks;
168

179
[Cmdlet(VerbsCommon.Get, "MgContext", DefaultParameterSetName = Constants.UserParameterSet)]
18-
[OutputType(typeof(AuthConfig))]
10+
[OutputType(typeof(IAuthContext))]
1911
public class GetMGContext: PSCmdlet
2012
{
2113
protected override void BeginProcessing()
@@ -26,11 +18,8 @@ protected override void BeginProcessing()
2618
protected override void ProcessRecord()
2719
{
2820
base.ProcessRecord();
29-
// Get auth config from session state.
30-
PSVariable graphAuthVariable = SessionState.PSVariable.Get(Constants.GraphAuthConfigId);
31-
AuthConfig authConfig = graphAuthVariable?.Value as AuthConfig;
32-
Invoke<AuthConfig>();
33-
WriteObject(authConfig as AuthConfig);
21+
IAuthContext authConfig = GraphSession.Instance.AuthContext;
22+
WriteObject(authConfig as IAuthContext);
3423
}
3524

3625
protected override void EndProcessing()
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
// ------------------------------------------------------------------------------
2+
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3+
// ------------------------------------------------------------------------------
4+
5+
namespace Microsoft.Graph.PowerShell.Authentication
6+
{
7+
using System;
8+
using System.Threading;
9+
public class GraphSession: IGraphSession
10+
{
11+
static GraphSession _instance;
12+
static bool _initialized = false;
13+
static ReaderWriterLockSlim sessionLock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
14+
public IAuthContext AuthContext { get; set; }
15+
public static GraphSession Instance
16+
{
17+
get
18+
{
19+
try
20+
{
21+
sessionLock.EnterReadLock();
22+
try
23+
{
24+
if (null == _instance)
25+
{
26+
throw new InvalidOperationException(ErrorConstants.Codes.SessionNotInitialized);
27+
}
28+
return _instance;
29+
}
30+
finally
31+
{
32+
sessionLock.ExitReadLock();
33+
}
34+
}
35+
catch (LockRecursionException lockException)
36+
{
37+
throw new InvalidOperationException(ErrorConstants.Codes.SessionLockReadRecursion, lockException);
38+
}
39+
catch (ObjectDisposedException disposedException)
40+
{
41+
throw new InvalidOperationException(ErrorConstants.Codes.SessionLockReadDisposed, disposedException);
42+
}
43+
}
44+
}
45+
46+
public static void Initialize(Func<GraphSession> instanceCreator, bool overwrite)
47+
{
48+
try
49+
{
50+
sessionLock.EnterWriteLock();
51+
try
52+
{
53+
if (overwrite || !_initialized)
54+
{
55+
_instance = instanceCreator();
56+
_initialized = true;
57+
}
58+
}
59+
finally
60+
{
61+
sessionLock.ExitWriteLock();
62+
}
63+
}
64+
catch (LockRecursionException lockException)
65+
{
66+
throw new InvalidOperationException(ErrorConstants.Codes.SessionLockWriteRecursion, lockException);
67+
}
68+
catch (ObjectDisposedException disposedException)
69+
{
70+
throw new InvalidOperationException(ErrorConstants.Codes.SessionLockWriteDisposed, disposedException);
71+
}
72+
}
73+
74+
public static void Initialize(Func<GraphSession> instanceCreator)
75+
{
76+
Initialize(instanceCreator, false);
77+
}
78+
79+
public static void Modify(Action<GraphSession> modifier)
80+
{
81+
try
82+
{
83+
sessionLock.EnterWriteLock();
84+
try
85+
{
86+
modifier(_instance);
87+
}
88+
finally
89+
{
90+
sessionLock.ExitWriteLock();
91+
}
92+
}
93+
catch (LockRecursionException lockException)
94+
{
95+
throw new InvalidOperationException(ErrorConstants.Codes.SessionLockWriteRecursion, lockException);
96+
}
97+
catch (ObjectDisposedException disposedException)
98+
{
99+
throw new InvalidOperationException(ErrorConstants.Codes.SessionLockWriteDisposed, disposedException);
100+
}
101+
}
102+
}
103+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// ------------------------------------------------------------------------------
2+
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3+
// ------------------------------------------------------------------------------
4+
5+
namespace Microsoft.Graph.PowerShell.Authentication
6+
{
7+
public static class GraphSessionInitializer
8+
{
9+
/// <summary>
10+
/// Initializes <see cref="GraphSession"/>.
11+
/// </summary>
12+
public static void InitializeSession()
13+
{
14+
GraphSession.Initialize(() => CreateInstance());
15+
}
16+
17+
/// <summary>
18+
/// Creates or gets a instance of a <see cref="GraphSession"/>.
19+
/// </summary>
20+
/// <returns><see cref="GraphSession"/></returns>
21+
internal static GraphSession CreateInstance()
22+
{
23+
// This can be used to initialize GraphSession from a file in the future.
24+
return new GraphSession();
25+
}
26+
}
27+
}

src/Authentication/Authentication/ErrorConstants.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,18 @@ public static class ErrorConstants
77
{
88
internal static class Codes
99
{
10+
internal const string SessionNotInitialized = "sessionNotInitialized";
11+
internal const string SessionLockReadRecursion = "sessionLockReadRecursion";
12+
internal const string SessionLockReadDisposed = "sessionLockReadDisposed";
13+
internal const string SessionLockWriteDisposed = "sessionLockWriteDisposed";
14+
internal const string SessionLockWriteRecursion = "sessionLockWriteRecursion";
1015
internal const string InvalidJWT = "invalidJWT";
1116
}
1217

1318
internal static class Message
1419
{
1520
internal const string InvalidJWT = "Invalid JWT access token.";
21+
internal const string MissingAuthContext = "Authentication needed, call Connect-Graph.";
1622
}
1723
}
1824
}

src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
namespace Microsoft.Graph.PowerShell.Authentication.Helpers
55
{
66
using Microsoft.Graph.Auth;
7-
using Microsoft.Graph.PowerShell.Authentication.Models;
87
using Microsoft.Graph.PowerShell.Authentication.TokenCache;
98
using Microsoft.Identity.Client;
109
using System;
@@ -16,7 +15,7 @@ internal static class AuthenticationHelpers
1615
{
1716
private static readonly object FileLock = new object();
1817

19-
internal static IAuthenticationProvider GetAuthProvider(AuthConfig authConfig)
18+
internal static IAuthenticationProvider GetAuthProvider(IAuthContext authConfig)
2019
{
2120
if (authConfig.AuthType == AuthenticationType.Delegated)
2221
{
@@ -43,7 +42,7 @@ internal static IAuthenticationProvider GetAuthProvider(AuthConfig authConfig)
4342
}
4443
}
4544

46-
internal static void Logout(AuthConfig authConfig)
45+
internal static void Logout(IAuthContext authConfig)
4746
{
4847
lock (FileLock)
4948
{

src/Authentication/Authentication/Helpers/HttpHelpers.cs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@
44
namespace Microsoft.Graph.PowerShell.Authentication.Helpers
55
{
66
using Microsoft.Graph.PowerShell.Authentication.Cmdlets;
7-
using Microsoft.Graph.PowerShell.Authentication.Models;
87
using System.Collections.Generic;
98
using System.Linq;
109
using System.Net.Http;
1110
using System.Reflection;
11+
using System.Security.Authentication;
1212

1313
/// <summary>
1414
/// A HTTP helper class.
@@ -31,8 +31,12 @@ public static class HttpHelpers
3131
/// </summary>
3232
/// <param name="authConfig"></param>
3333
/// <returns></returns>
34-
public static HttpClient GetGraphHttpClient(AuthConfig authConfig)
34+
public static HttpClient GetGraphHttpClient(IAuthContext authConfig = null)
3535
{
36+
authConfig = authConfig ?? GraphSession.Instance.AuthContext;
37+
if (authConfig is null)
38+
throw new AuthenticationException(ErrorConstants.Message.MissingAuthContext);
39+
3640
IAuthenticationProvider authProvider = AuthenticationHelpers.GetAuthProvider(authConfig);
3741
IList<DelegatingHandler> defaultHandlers = GraphClientFactory.CreateDefaultHandlers(authProvider);
3842

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// ------------------------------------------------------------------------------
2+
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3+
// ------------------------------------------------------------------------------
4+
5+
namespace Microsoft.Graph.PowerShell.Authentication
6+
{
7+
public enum AuthenticationType
8+
{
9+
Delegated,
10+
AppOnly
11+
}
12+
public interface IAuthContext
13+
{
14+
string ClientId { get; set; }
15+
string TenantId { get; set; }
16+
string CertificateThumbprint { get; set; }
17+
string[] Scopes { get; set; }
18+
AuthenticationType AuthType { get; set; }
19+
string CertificateName { get; set; }
20+
string Account { get; set; }
21+
string AppName { get; set; }
22+
}
23+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
// ------------------------------------------------------------------------------
2+
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
3+
// ------------------------------------------------------------------------------
4+
5+
namespace Microsoft.Graph.PowerShell.Authentication
6+
{
7+
public interface IGraphSession
8+
{
9+
IAuthContext AuthContext { get; set; }
10+
}
11+
}

0 commit comments

Comments
 (0)