forked from microsoftgraph/aspnet-snippets-sample
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOAuth2CodeRedeemerMiddleware.cs
219 lines (195 loc) · 9.04 KB
/
OAuth2CodeRedeemerMiddleware.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
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
/*
* Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license.
* See LICENSE in the source repository root for complete license information.
*/
using Microsoft.Identity.Client;
using Microsoft.Owin;
using Owin;
using System;
using System.Collections.Generic;
using System.IdentityModel.Claims;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft_Graph_ASPNET_Snippets.TokenStorage;
namespace Microsoft_Graph_ASPNET_Snippets.Utils
{
public sealed class OAuth2CodeRedeemerMiddleware : OwinMiddleware
{
private readonly OAuth2CodeRedeemerOptions options;
public OAuth2CodeRedeemerMiddleware(OwinMiddleware next, OAuth2CodeRedeemerOptions options)
: base(next)
{
if (options == null)
{
throw new ArgumentNullException("options");
}
this.options = options;
}
public async override Task Invoke(IOwinContext context)
{
string code = context.Request.Query["code"];
if (code != null)
{
//extract state
string state = context.Request.Query["state"];
string session_state = context.Request.Query["session_state"];
string signedInUserID = context.Authentication.User.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;
HttpContextBase hcb = context.Environment["System.Web.HttpContextBase"] as HttpContextBase;
TokenCache theCache = new SessionTokenCache(signedInUserID, hcb).GetMsalCacheInstance();
ConfidentialClientApplication cca = new ConfidentialClientApplication(options.ClientId, options.RedirectUri,
new ClientCredential(options.ClientSecret), theCache, null);
//validate state
CodeRedemptionData crd = OAuth2RequestManager.ValidateState(state, hcb);
if (crd != null)
{//if valid
//redeem code
try
{
AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, crd.Scopes);
HttpContext.Current.Session.Add("IsAdmin", true);
}
catch (Exception ee)
{
}
//redirect to original requestor
context.Response.StatusCode = 302;
context.Response.Headers.Set("Location", crd.RequestOriginatorUrl);
}
else
{
context.Response.StatusCode = 302;
context.Response.Headers.Set("Location", "/Error?message=" + "code_redeem_failed");
}
}
else
await this.Next.Invoke(context);
}
}
public sealed class OAuth2CodeRedeemerOptions
{
public string ClientId { get; set; }
public string RedirectUri { get; set; }
public string ClientSecret { get; set; }
// public TokenCache TokenCache { get; set; }
}
internal static class OAuth2CodeRedeemerHandler
{
public static IAppBuilder UseOAuth2CodeRedeemer(this IAppBuilder app, OAuth2CodeRedeemerOptions options)
{
app.Use<OAuth2CodeRedeemerMiddleware>(options);
return app;
}
}
#region Utils
public class OAuth2RequestManager
{
private static ReaderWriterLockSlim SessionLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
/// Generate a state value using a random Guid value, the origin of the request and the scopes being requested.
/// The state value will be consumed by the OAuth controller for validation, for specifying the corresc scopes during code redemption, and redirection after code redemption.
/// Here we store the random Guid in the session for validation by the OAuth controller.
private static string GenerateState(string requestUrl, HttpContextBase httpcontext, UrlHelper url, string[] scopes)
{
try
{
string stateGuid = Guid.NewGuid().ToString();
SaveUserStateValue(stateGuid, httpcontext);
List<String> stateList = new List<String>();
stateList.Add(stateGuid);
stateList.Add(requestUrl);
// turn the scopes array into a comma separated list string
string scopeslist = scopes[0];
if (scopes.Count() > 1)
for (int i = 1; i < scopes.Count(); i++)
{
scopeslist += "," + scopes[i];
}
stateList.Add(scopeslist);
var formatter = new BinaryFormatter();
var stream = new MemoryStream();
formatter.Serialize(stream, stateList);
var stateBits = stream.ToArray();
return url.Encode(Convert.ToBase64String(stateBits));
}
catch
{
return null;
}
}
// save the state in the session for the current user
private static void SaveUserStateValue(string stateGuid, HttpContextBase httpcontext)
{
string signedInUserID = ClaimsPrincipal.Current.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;
SessionLock.EnterWriteLock();
httpcontext.Session[signedInUserID + "_state"] = stateGuid;
SessionLock.ExitWriteLock();
}
private static string ReadUserStateValue(HttpContextBase httpcontext)
{
string signedInUserID = ClaimsPrincipal.Current.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;
string stateGuid = string.Empty;
SessionLock.EnterReadLock();
stateGuid = (string)httpcontext.Session[signedInUserID + "_state"];
SessionLock.ExitReadLock();
return stateGuid;
}
// Verify that the state identifier in the state string corresponds to the GUID saved in the session for the current user
// If the check succeeds, return the scopes to request when redeeming the code and the URL to which the app will be redirected after redemption
public static CodeRedemptionData ValidateState(string state, HttpContextBase httpcontext)
{
try
{
var stateBits = Convert.FromBase64String(HttpUtility.UrlDecode(state));
var formatter = new BinaryFormatter();
var stream = new MemoryStream(stateBits);
List<String> stateList = (List<String>)formatter.Deserialize(stream);
var stateGuid = stateList[0];
//TODO - cleaning up should not be necessary, I have just one entry per user
// but at least I should do it for making the state single use
if (stateGuid == ReadUserStateValue(httpcontext))
{
string returnURL = stateList[1];
string[] scopes = stateList[2].Split(',');
return new CodeRedemptionData()
{
RequestOriginatorUrl = returnURL,
Scopes = scopes
};
}
else
return null;
}
catch
{
return null;
}
}
public static async Task<string> GenerateAuthorizationRequestUrl(string[] scopes, ConfidentialClientApplication cca, HttpContextBase httpcontext, UrlHelper url)
{
string signedInUserID = ClaimsPrincipal.Current.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;
string preferredUsername = ClaimsPrincipal.Current.FindFirst("preferred_username").Value;
Uri oauthCodeProcessingPath = new Uri(httpcontext.Request.Url.GetLeftPart(UriPartial.Authority).ToString());
string state = GenerateState(httpcontext.Request.Url.ToString(), httpcontext, url, scopes);
string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string domain_hint = (tenantID == "9188040d-6c67-4c5b-b112-36a304b66dad") ? "consumers" : "organizations";
Uri authzMessageUri = await cca.GetAuthorizationRequestUrlAsync(scopes,
oauthCodeProcessingPath.ToString(),
preferredUsername,
state == null ? null : "&state=" + state + "&domain_hint=" + domain_hint,
null,
cca.Authority);
return authzMessageUri.ToString();
}
}
public class CodeRedemptionData
{
public string RequestOriginatorUrl { get; set; }
public string[] Scopes { get; set; }
}
#endregion
}