Skip to content

Commit 7c7ab8a

Browse files
author
Kalyan Krishna
committed
Ready for review
1 parent fce718f commit 7c7ab8a

File tree

6 files changed

+51
-17
lines changed

6 files changed

+51
-17
lines changed

AppCreationScripts/Configure.ps1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ Function ConfigureApplications
208208
# Update config file for 'client'
209209
$configFile = $pwd.Path + "\..\TodoListClient\App.Config"
210210
Write-Host "Updating the sample code ($configFile)"
211-
ReplaceSetting -configFilePath $configFile -key "ida:Tenant" -newValue $tenantName
211+
ReplaceSetting -configFilePath $configFile -key "ida:TenantId" -newValue $tenantId
212212
ReplaceSetting -configFilePath $configFile -key "ida:ClientId" -newValue $clientAadApplication.AppId
213213
ReplaceSetting -configFilePath $configFile -key "todo:TodoListResourceId" -newValue $serviceIdentifierUri
214214
ReplaceSetting -configFilePath $configFile -key "todo:TodoListBaseAddress" -newValue $serviceAadApplication.HomePage

AppCreationScripts/sample.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,8 @@
6969
"SettingFile": "\\..\\TodoListClient\\App.Config",
7070
"Mappings": [
7171
{
72-
"key": "ida:Tenant",
73-
"value": "$tenantName"
72+
"key": "ida:TenantId",
73+
"value": "$tenantId"
7474
},
7575
{
7676
"key": "ida:ClientId",

TodoListClient/App.config

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,6 @@
99
<add key="todo:TodoListResourceId" value="[Enter App ID URI of TodoListService-ManualJwt, e.g. api://{clientID}]" />
1010
<add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}/v2.0" />
1111
<add key="todo:TodoListBaseAddress" value="https://localhost:44324" />
12+
<add key="todo:TodoListScope" value="user_impersonation" />
1213
</appSettings>
1314
</configuration>

TodoListClient/MainWindow.xaml.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ private async void AddTodoItem(object sender, RoutedEventArgs e)
198198
// There is no access token in the cache, so prompt the user to sign-in.
199199
catch (MsalUiRequiredException)
200200
{
201-
MessageBox.Show("Please re-sign");
201+
MessageBox.Show("Please re-signIn");
202202
SignInButton.Content = signInString;
203203
}
204204
catch (MsalException ex)
@@ -269,7 +269,7 @@ private async void SignIn(object sender = null, RoutedEventArgs args = null)
269269
//
270270
try
271271
{
272-
// Force a sign-in (PromptBehavior.Always), as the ADAL web browser might contain cookies for the current user, and using .Auto
272+
// Force a sign-in (PromptBehavior.Always), as the MSAL web browser might contain cookies for the current user, and using .Auto
273273
// would re-sign-in the same user
274274
var result = await _app.AcquireTokenInteractive(scopes)
275275
.WithAccount(accounts.FirstOrDefault())
@@ -303,6 +303,7 @@ private async void SignIn(object sender = null, RoutedEventArgs args = null)
303303
}
304304

305305
UserName.Content = Properties.Resources.UserNotSignedIn;
306+
//SignInButton.Content = signInString;
306307
}
307308
}
308309

TodoListService-ManualJwt/Global.asax.cs

Lines changed: 42 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2626
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
2727
using Microsoft.IdentityModel.Tokens;
2828
using System;
29+
using System.Collections.Generic;
2930
using System.Configuration;
3031
using System.Globalization;
3132
using System.IdentityModel.Tokens.Jwt;
@@ -71,16 +72,16 @@ internal class TokenValidationHandler : DelegatingHandler
7172
private string _authority;
7273
private string _clientId;
7374
private ConfigurationManager<OpenIdConnectConfiguration> _configManager;
74-
75+
private string _tenant;
7576
private ISecurityTokenValidator _tokenValidator;
7677

7778
public TokenValidationHandler()
7879
{
7980
_audience = ConfigurationManager.AppSettings["ida:Audience"];
8081
_clientId = ConfigurationManager.AppSettings["ida:ClientId"];
8182
var aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
82-
var tenant = ConfigurationManager.AppSettings["ida:Tenant"];
83-
_authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
83+
_tenant = ConfigurationManager.AppSettings["ida:TenantId"];
84+
_authority = string.Format(CultureInfo.InvariantCulture, aadInstance, _tenant);
8485
_configManager = new ConfigurationManager<OpenIdConnectConfiguration>($"{_authority}/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
8586
_tokenValidator = new JwtSecurityTokenHandler();
8687
}
@@ -93,6 +94,9 @@ public TokenValidationHandler()
9394
/// <returns>A <see cref="HttpResponseMessage"/>.</returns>
9495
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
9596
{
97+
// For debugging/development purposes, one can enable additional detail in exceptions by setting IdentityModelEventSource.ShowPII to true.
98+
Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
99+
96100
// check if there is a jwt in the authorization header, return 'Unauthorized' error if the token is null.
97101
if (request.Headers.Authorization == null || request.Headers.Authorization.Parameter == null)
98102
return BuildResponseErrorMessage(HttpStatusCode.Unauthorized);
@@ -104,19 +108,35 @@ protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage
104108
{
105109
config = await _configManager.GetConfigurationAsync(cancellationToken).ConfigureAwait(false);
106110
}
107-
catch (Exception)
111+
catch (Exception ex)
108112
{
113+
#if DEBUG
114+
return BuildResponseErrorMessage(HttpStatusCode.InternalServerError, ex.Message);
115+
#else
109116
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
117+
#endif
110118
}
111119

120+
// You can get a list of issuers for the various Azure AD deployments (global & sovereign) from the following endpoint
121+
//https://login.microsoftonline.com/common/discovery/instance?authorization_endpoint=https://login.microsoftonline.com/common/oauth2/v2.0/authorize&api-version=1.1;
122+
123+
IList<string> validissuers = new List<string>()
124+
{
125+
$"https://login.microsoftonline.com/{_tenant}/",
126+
$"https://login.microsoftonline.com/{_tenant}/v2.0",
127+
$"https://login.windows.net/{_tenant}/",
128+
$"https://login.microsoft.com/{_tenant}/",
129+
$"https://sts.windows.net/{_tenant}/"
130+
};
131+
112132
// Initialize the token validation parameters
113133
TokenValidationParameters validationParameters = new TokenValidationParameters
114134
{
115135
// App Id URI and AppId of this service application are both valid audiences.
116136
ValidAudiences = new[] { _audience, _clientId },
117137

118138
// Support Azure AD V1 and V2 endpoints.
119-
ValidIssuers = new[] { config.Issuer, $"{config.Issuer}/v2.0" },
139+
ValidIssuers = validissuers,
120140
IssuerSigningKeys = config.SigningKeys
121141
};
122142

@@ -130,7 +150,11 @@ protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage
130150
if (!claimsPrincipal.Claims.Any(x => x.Type == ClaimConstants.ScopeClaimType)
131151
&& !claimsPrincipal.Claims.Any(y => y.Type == ClaimConstants.RolesClaimType))
132152
{
133-
throw new UnauthorizedAccessException("Neither scope or roles claim was found in the bearer token.");
153+
#if DEBUG
154+
return BuildResponseErrorMessage(HttpStatusCode.Forbidden, "Neither 'scope' or 'roles' claim was found in the bearer token.");
155+
#else
156+
return BuildResponseErrorMessage(HttpStatusCode.Forbidden);
157+
#endif
134158
}
135159
#pragma warning restore 1998
136160

@@ -147,22 +171,30 @@ protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage
147171

148172
return await base.SendAsync(request, cancellationToken);
149173
}
150-
catch (SecurityTokenValidationException)
174+
catch (SecurityTokenValidationException stex)
151175
{
176+
#if DEBUG
177+
return BuildResponseErrorMessage(HttpStatusCode.Unauthorized, stex.Message);
178+
#else
152179
return BuildResponseErrorMessage(HttpStatusCode.Unauthorized);
180+
#endif
153181
}
154-
catch (Exception)
182+
catch (Exception ex)
155183
{
184+
#if DEBUG
185+
return BuildResponseErrorMessage(HttpStatusCode.InternalServerError, ex.Message);
186+
#else
156187
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
188+
#endif
157189
}
158190
}
159191

160-
private HttpResponseMessage BuildResponseErrorMessage(HttpStatusCode statusCode)
192+
private HttpResponseMessage BuildResponseErrorMessage(HttpStatusCode statusCode, string error_description = "")
161193
{
162194
var response = new HttpResponseMessage(statusCode);
163195

164196
// The Scheme should be "Bearer", authorization_uri should point to the tenant url and resource_id should point to the audience.
165-
var authenticateHeader = new AuthenticationHeaderValue("Bearer", "authorization_uri=\"" + _authority + "\"" + "," + "resource_id=" + _audience);
197+
var authenticateHeader = new AuthenticationHeaderValue("Bearer", "authorization_uri=\"" + _authority + "\"" + "," + "resource_id=" + _audience + $",error_description={error_description}");
166198
response.Headers.WwwAuthenticate.Add(authenticateHeader);
167199
return response;
168200
}

TodoListService-ManualJwt/Web.config

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@
99
<add key="webpages:Enabled" value="false" />
1010
<add key="ClientValidationEnabled" value="true" />
1111
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
12-
<add key="ida:ClientId" value="[Enter the Application Id (also named ClientId) for the application]" />
13-
<add key="ida:Tenant" value="[Enter tenant name, e.g. contoso.onmicrosoft.com]" />
12+
<add key="ida:ClientId" value="[Enter the Application Id (also named ClientId) for the application]" />
13+
<add key="ida:TenantId" value="[Enter the tenant/Directory Id name, e.g b898afb8-75af-4d05-ba80-6177b3a6a1e1]" />
1414
<add key="ida:Audience" value="[Enter App ID URI of TodoListService-ManualJwt, e.g. api://{client Id of TodoListService-ManualJwt]}" />
1515
<add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}/v2.0" />
1616
</appSettings>

0 commit comments

Comments
 (0)