/
HomeController.cs
201 lines (176 loc) · 7.37 KB
/
HomeController.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
using Microsoft.Identity.Client;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OpenIdConnect;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using WebApp.Utils;
namespace WebApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[Authorize]
public ActionResult About()
{
ViewBag.Name = ClaimsPrincipal.Current.FindFirst("name").Value;
ViewBag.AuthorizationRequest = string.Empty;
// The object ID claim will only be emitted for work or school accounts at this time.
Claim oid = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier");
ViewBag.ObjectId = oid == null ? string.Empty : oid.Value;
// The 'preferred_username' claim can be used for showing the user's primary way of identifying themselves
ViewBag.Username = ClaimsPrincipal.Current.FindFirst("preferred_username").Value;
// The subject or nameidentifier claim can be used to uniquely identify the user
ViewBag.Subject = ClaimsPrincipal.Current.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier").Value;
return View();
}
[Authorize]
[HttpGet]
public async Task<ActionResult> SendMail()
{
// Before we render the send email screen, we use the incremental consent to obtain and cache the access token with the correct scopes
IConfidentialClientApplication app = MsalAppBuilder.BuildConfidentialClientApplication();
AuthenticationResult result = null;
var account = await app.GetAccountAsync(ClaimsPrincipal.Current.GetMsalAccountId());
string[] scopes = { "Mail.Send" };
try
{
// try to get an already cached token
result = await app.AcquireTokenSilent(scopes, account).ExecuteAsync().ConfigureAwait(false);
}
catch (MsalUiRequiredException ex)
{
// A MsalUiRequiredException happened on AcquireTokenSilentAsync.
// This indicates you need to call AcquireTokenAsync to acquire a token
Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");
try
{
// Build the auth code request Uri
string authReqUrl = await OAuth2RequestManager.GenerateAuthorizationRequestUrl(scopes, app, this.HttpContext, Url);
ViewBag.AuthorizationRequest = authReqUrl;
ViewBag.Relogin = "true";
}
catch (MsalException msalex)
{
Response.Write($"Error Acquiring Token:{System.Environment.NewLine}{msalex}");
}
}
catch (Exception ex)
{
Response.Write($"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}");
}
return View();
}
[Authorize]
[HttpPost]
public async Task<ActionResult> SendMail(string recipient, string subject, string body)
{
string messagetemplate = @"{{
""Message"": {{
""Subject"": ""{0}"",
""Body"": {{
""ContentType"": ""Text"",
""Content"": ""{1}""
}},
""ToRecipients"": [
{{
""EmailAddress"": {{
""Address"": ""{2}""
}}
}}
],
""Attachments"": []
}},
""SaveToSentItems"": ""false""
}}
";
string message = String.Format(messagetemplate, subject, body, recipient);
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://graph.microsoft.com/v1.0/me/sendMail")
{
Content = new StringContent(message, Encoding.UTF8, "application/json")
};
IConfidentialClientApplication app = MsalAppBuilder.BuildConfidentialClientApplication();
AuthenticationResult result = null;
var account = await app.GetAccountAsync(ClaimsPrincipal.Current.GetMsalAccountId());
string[] scopes = { "Mail.Send" };
try
{
// try to get an already cached token
result = await app.AcquireTokenSilent(scopes, account).ExecuteAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
/*
* When the user access this page (from the HTTP GET action result) we check if they have the scope "Mail.Send" and
* we handle the additional consent step in case it is needed. Then, we acquire an access token and MSAL cache it for us.
* So in this HTTP POST action result, we can always expect a token to be in cache. If they are not in the cache,
* it means that the user accessed this route via an unsual way.
*/
ViewBag.Error = "An error has occurred acquiring the token from cache. Details: " + ex.Message;
return View();
}
if (result != null)
{
// Use the token to send email
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
ViewBag.AuthorizationRequest = null;
return View("MailSent");
}
}
return View();
}
public async Task<ActionResult> ReadMail()
{
IConfidentialClientApplication app = MsalAppBuilder.BuildConfidentialClientApplication();
AuthenticationResult result = null;
var account = await app.GetAccountAsync(ClaimsPrincipal.Current.GetMsalAccountId());
string[] scopes = { "Mail.Read" };
try
{
// try to get token silently
result = await app.AcquireTokenSilent(scopes, account).ExecuteAsync().ConfigureAwait(false);
}
catch (MsalUiRequiredException)
{
ViewBag.Relogin = "true";
return View();
}
catch (Exception eee)
{
ViewBag.Error = "An error has occurred. Details: " + eee.Message;
return View();
}
if (result != null)
{
// Use the token to read email
HttpClient hc = new HttpClient();
hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken);
HttpResponseMessage hrm = await hc.GetAsync("https://graph.microsoft.com/v1.0/me/messages");
string rez = await hrm.Content.ReadAsStringAsync();
ViewBag.Message = rez;
}
return View();
}
public void RefreshSession()
{
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/Home/ReadMail" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
}