-
Notifications
You must be signed in to change notification settings - Fork 6
/
AccountController.cs
209 lines (193 loc) · 10.5 KB
/
AccountController.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
using Sample.Client.AspNetCore.Models;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.AzureADB2C.UI;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
namespace Sample.Client.AspNetCore.Controllers
{
[Route("[controller]/[action]")]
public class AccountController : Controller
{
private readonly IHttpClientFactory httpClientFactory;
private readonly string signingSecret;
private readonly string invitationClientAssertionPolicyId;
private readonly string invitationCodePolicyId;
private readonly string userInvitationApiUrl;
private readonly JsonSerializerOptions jsonSerializerOptions;
public AccountController(IHttpClientFactory httpClientFactory, IConfiguration configuration)
{
this.httpClientFactory = httpClientFactory;
this.signingSecret = configuration["AzureAdB2C:ClientSecret"];
this.invitationClientAssertionPolicyId = configuration["AzureAdB2C:InvitationClientAssertionPolicyId"];
this.invitationCodePolicyId = configuration["AzureAdB2C:InvitationCodePolicyId"];
this.userInvitationApiUrl = configuration["UserInvitationApiUrl"];
this.jsonSerializerOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
}
public async Task<IActionResult> Identity()
{
var relatedApplicationIdentities = new List<IdentityInfo>();
try
{
// Request identity information as seen by the back-end Web API.
var client = this.httpClientFactory.CreateClient(Startup.SampleApiHttpClientName);
// Fetch the access token from the current user's claims to avoid the complexity of an external token cache (see Startup.cs).
var accessTokenClaim = this.User.Claims.SingleOrDefault(c => c.Type == Startup.ClaimTypeAccessToken);
if (accessTokenClaim != null)
{
// Call the back-end Web API using the bearer access token.
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessTokenClaim.Value);
var response = await client.GetAsync("api/identity");
response.EnsureSuccessStatusCode();
// Deserialize the response into an IdentityInfo instance.
var apiIdentityInfoValue = await response.Content.ReadAsStringAsync();
var apiIdentityInfo = JsonSerializer.Deserialize<IdentityInfo>(apiIdentityInfoValue, this.jsonSerializerOptions);
relatedApplicationIdentities.Add(apiIdentityInfo);
}
}
catch (Exception exc)
{
relatedApplicationIdentities.Add(new IdentityInfo
{
Source = "Exception",
Application = "Sample API",
IsAuthenticated = false,
Claims = new[] { new ClaimInfo { Type = "ExceptionMessage", Value = exc.Message }, new ClaimInfo { Type = "ExceptionDetail", Value = exc.ToString() } }
});
}
// Return identity information as seen from this application, including related applications.
var identityInfo = new IdentityInfo
{
Source = "ID Token",
Application = "Sample Client",
IsAuthenticated = this.User.Identity.IsAuthenticated,
Name = this.User.Identity.Name,
AuthenticationType = this.User.Identity.AuthenticationType,
Claims = this.User.Claims.Select(c => new ClaimInfo { Type = c.Type, Value = c.Value }).ToList(),
RelatedApplicationIdentities = relatedApplicationIdentities
};
return View(identityInfo);
}
public IActionResult Invite()
{
var model = new AccountInvitationViewModel
{
CanInviteUsingClientAssertion = !string.IsNullOrWhiteSpace(this.signingSecret),
CanInviteUsingInvitationCode = !string.IsNullOrWhiteSpace(this.userInvitationApiUrl)
};
return View(model);
}
[HttpPost]
public IActionResult InviteUsingClientAssertion(string email, int validDays = 30)
{
if (!string.IsNullOrEmpty(email))
{
// Generate an invitation link for the requested email address by generating a self-issued token and sending that to the "Register" action.
var expiration = TimeSpan.FromDays(validDays); // Defines how long the invitation is valid.
var claims = new[]
{
new Claim("verified_email", email) // This claim maps to the extension attribute registered in AAD B2C which is used in the custom invitation policy.
};
var selfIssuedToken = CreateSelfIssuedToken(expiration, claims, this.signingSecret);
var authenticationRequestUrl = Url.Action("Register", "Account", new { client_assertion = selfIssuedToken }, "https" /* This forces an absolute URL */);
var model = new AccountInvitationViewModel
{
CanInviteUsingClientAssertion = !string.IsNullOrWhiteSpace(this.signingSecret),
CanInviteUsingInvitationCode = !string.IsNullOrWhiteSpace(this.userInvitationApiUrl),
Email = email,
AuthenticationRequestUrl = authenticationRequestUrl
};
return View(nameof(Invite), model);
}
return RedirectToAction(nameof(Invite));
}
[HttpPost]
public async Task<IActionResult> InviteUsingInvitationCode(string companyId)
{
if (!string.IsNullOrEmpty(this.userInvitationApiUrl))
{
var client = this.httpClientFactory.CreateClient();
var invitationCodeRequest = new { CompanyId = companyId };
var invitationCodeRequestContent = new StringContent(JsonSerializer.Serialize(invitationCodeRequest, this.jsonSerializerOptions), Encoding.UTF8, "application/json");
var response = await client.PostAsync(this.userInvitationApiUrl, invitationCodeRequestContent);
response.EnsureSuccessStatusCode();
var invitationCode = default(string);
var invitationCodeResponseValue = await response.Content.ReadAsStringAsync();
if (JsonDocument.Parse(invitationCodeResponseValue).RootElement.TryGetProperty("invitationCode", out var invitationCodeProperty))
{
invitationCode = invitationCodeProperty.GetString();
}
var authenticationRequestUrl = Url.Action("Register", "Account", null, "https" /* This forces an absolute URL */);
var model = new AccountInvitationViewModel
{
CanInviteUsingClientAssertion = !string.IsNullOrWhiteSpace(this.signingSecret),
CanInviteUsingInvitationCode = !string.IsNullOrWhiteSpace(this.userInvitationApiUrl),
CompanyId = companyId,
AuthenticationRequestUrl = authenticationRequestUrl,
InvitationCode = invitationCode
};
return View(nameof(Invite), model);
}
return RedirectToAction(nameof(Invite));
}
public async Task<IActionResult> Register(string client_assertion)
{
// Tell the AAD B2C middleware to invoke a specific policy.
// NOTE: this resets the scope and response type so no authorization code is requested from this flow,
// see https://github.com/aspnet/AspNetCore/blob/release/3.1/src/Azure/AzureAD/Authentication.AzureADB2C.UI/src/AzureAdB2COpenIDConnectEventHandlers.cs#L35-L36.
var authenticationProperties = new AuthenticationProperties();
authenticationProperties.RedirectUri = Url.Action("Registered", "Account");
#pragma warning disable 0618 // AzureADB2CDefaults is obsolete in favor of "Microsoft.Identity.Web"
if (!string.IsNullOrWhiteSpace(client_assertion))
{
// Use the client assertion flow and pass the client_assertion through.
authenticationProperties.Items[AzureADB2CDefaults.PolicyKey] = this.invitationClientAssertionPolicyId;
authenticationProperties.Items[OpenIdConnectParameterNames.ClientAssertion] = client_assertion;
}
else
{
// Use the invitation code flow.
authenticationProperties.Items[AzureADB2CDefaults.PolicyKey] = this.invitationCodePolicyId;
}
await HttpContext.ChallengeAsync(AzureADB2CDefaults.AuthenticationScheme, authenticationProperties);
#pragma warning restore 0618
return new EmptyResult();
}
[Authorize]
public IActionResult Registered()
{
return View();
}
internal static string CreateSelfIssuedToken(TimeSpan expiration, ICollection<Claim> claims, string signingSecret)
{
var tokenHandler = new JwtSecurityTokenHandler();
var nowUtc = DateTime.UtcNow;
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signingSecret));
var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Audience = "my-audience", // Not important as we are self-issuing the token.
Expires = nowUtc.Add(expiration),
IssuedAt = nowUtc,
Issuer = "https://my-issuer", // Not important as we are self-issuing the token.
NotBefore = nowUtc,
SigningCredentials = signingCredentials,
Subject = new ClaimsIdentity(claims)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}
}