This repository was archived by the owner on Jun 17, 2024. It is now read-only.
forked from matvelloso/AuthBot
-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathOAuthCallbackController.cs
197 lines (172 loc) · 9.18 KB
/
OAuthCallbackController.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
// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file.
namespace AuthBot.Controllers
{
using System;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Autofac;
using Helpers;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.Dialogs.Internals;
using Microsoft.Bot.Connector;
using Microsoft.Rest;
using Models;
public class OAuthCallbackController : ApiController
{
private static RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
private static readonly uint MaxWriteAttempts = 5;
[HttpGet]
[Route("api/OAuthCallback")]
public async Task<HttpResponseMessage> OAuthCallback()
{
try
{
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent($"<html><body>You have been signed out. You can now close this window.</body></html>", System.Text.Encoding.UTF8, @"text/html");
return resp;
}
catch (Exception ex)
{
// Callback is called with no pending message as a result the login flow cannot be resumed.
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
[HttpGet]
[Route("api/OAuthCallback")]
public async Task<HttpResponseMessage> OAuthCallback(
[FromUri] string state,
[FromUri] string code,
CancellationToken cancellationToken)
{
try
{
var queryParams = state;
object tokenCache = null;
if (string.Equals(AuthSettings.Mode, "v1", StringComparison.OrdinalIgnoreCase))
{
tokenCache = new Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache();
}
else if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase))
{
tokenCache = new Microsoft.Identity.Client.TokenCache();
}
else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase))
{
tokenCache = new Microsoft.Identity.Client.TokenCache();
}
var resumptionCookie = UrlToken.Decode<ResumptionCookie>(queryParams);
// Create the message that is send to conversation to resume the login flow
var message = resumptionCookie.GetMessage();
using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message))
{
var client = scope.Resolve<IConnectorClient>();
AuthResult authResult = null;
if (string.Equals(AuthSettings.Mode, "v1", StringComparison.OrdinalIgnoreCase))
{
// Exchange the Auth code with Access token
var token = await AzureActiveDirectoryHelper.GetTokenByAuthCodeAsync(code, (Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache)tokenCache);
authResult = token;
}
else if (string.Equals(AuthSettings.Mode, "v2", StringComparison.OrdinalIgnoreCase))
{
// Exchange the Auth code with Access token
var token = await AzureActiveDirectoryHelper.GetTokenByAuthCodeAsync(code, (Microsoft.Identity.Client.TokenCache)tokenCache,Models.AuthSettings.Scopes);
authResult = token;
}
else if (string.Equals(AuthSettings.Mode, "b2c", StringComparison.OrdinalIgnoreCase))
{
var token = await AzureActiveDirectoryHelper.GetB2cTokenByAuthCodeAsync(code, (Microsoft.Identity.Client.TokenCache)tokenCache, Models.AuthSettings.Scopes);
authResult = token;
}
IStateClient sc = scope.Resolve<IStateClient>();
//IMPORTANT: DO NOT REMOVE THE MAGIC NUMBER CHECK THAT WE DO HERE. THIS IS AN ABSOLUTE SECURITY REQUIREMENT
//REMOVING THIS WILL REMOVE YOUR BOT AND YOUR USERS TO SECURITY VULNERABILITIES.
//MAKE SURE YOU UNDERSTAND THE ATTACK VECTORS AND WHY THIS IS IN PLACE.
int magicNumber = GenerateRandomNumber();
bool writeSuccessful = false;
uint writeAttempts = 0;
while (!writeSuccessful && writeAttempts++ < MaxWriteAttempts)
{
try
{
BotData userData = sc.BotState.GetUserData(message.ChannelId, message.From.Id);
userData.SetProperty(ContextConstants.AuthResultKey, authResult);
userData.SetProperty(ContextConstants.MagicNumberKey, magicNumber);
userData.SetProperty(ContextConstants.MagicNumberValidated, "false");
sc.BotState.SetUserData(message.ChannelId, message.From.Id, userData);
writeSuccessful = true;
}
catch (HttpOperationException)
{
writeSuccessful = false;
}
}
var resp = new HttpResponseMessage(HttpStatusCode.OK);
if (!writeSuccessful)
{
message.Text = String.Empty; // fail the login process if we can't write UserData
await Conversation.ResumeAsync(resumptionCookie, message);
resp.Content = new StringContent("<html><body>Could not log you in at this time, please try again later</body></html>", System.Text.Encoding.UTF8, @"text/html");
}
else
{
await Conversation.ResumeAsync(resumptionCookie, message);
if (message.ChannelId == "skypeforbusiness")
resp.Content = new StringContent($"<html><body>Almost done! Please copy this number and paste it back to your chat so your authentication can complete:<br/> {magicNumber} </body></html>", System.Text.Encoding.UTF8, @"text/html");
else
resp.Content = new StringContent($"<html><body>Almost done! Please copy this number and paste it back to your chat so your authentication can complete:<br/> <h1>{magicNumber}</h1>.</body></html>", System.Text.Encoding.UTF8, @"text/html");
}
return resp;
}
}
catch (Exception ex)
{
// Callback is called with no pending message as a result the login flow cannot be resumed.
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
private int GenerateRandomNumber()
{
int number = 0;
byte[] randomNumber = new byte[1];
do
{
rngCsp.GetBytes(randomNumber);
var digit = randomNumber[0] % 10;
number = number * 10 + digit;
} while (number.ToString().Length < 6);
return number;
}
}
}
//*********************************************************
//
//AuthBot, https://github.com/microsoftdx/AuthBot
//
//Copyright (c) Microsoft Corporation
//All rights reserved.
//
// MIT License:
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// ""Software""), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//*********************************************************