Skip to content

Commit 18c066a

Browse files
authored
Merge pull request #70 from wviriya/refresh-functions-v4
Refresh functions v4
2 parents f91b8e4 + 4aeb3ee commit 18c066a

File tree

7 files changed

+65
-43
lines changed

7 files changed

+65
-43
lines changed

dotnet/ServerlessMicroservices.FunctionApp.Passengers/ServerlessMicroservices.FunctionApp.Passengers.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
<PropertyGroup>
33
<TargetFramework>netcoreapp3.1</TargetFramework>
44
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
5+
<_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
56
</PropertyGroup>
67
<ItemGroup>
78
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.13" />

dotnet/ServerlessMicroservices.Shared/ServerlessMicroservices.Shared.csproj

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,13 @@
1212
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
1313
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.23.0" />
1414
<PackageReference Include="Microsoft.Azure.WebJobs" Version="3.0.30" />
15+
<PackageReference Include="Microsoft.Graph" Version="4.11.0" />
16+
<PackageReference Include="Microsoft.Identity.Client" Version="4.39.0" />
1517
<PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="5.2.9" />
18+
<PackageReference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="6.15.0" />
19+
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.15.0" />
1620
<PackageReference Include="System.Data.SqlClient" Version="4.8.3" />
17-
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.14.1" />
21+
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.15.0" />
1822
</ItemGroup>
1923

2024
<ItemGroup>

dotnet/ServerlessMicroservices.Shared/Services/TokenValidationService.cs

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33
using System.Linq;
44
using System.Security.Claims;
55
using System.Threading.Tasks;
6-
using IdentityModel;
76
using IdentityModel.Client;
87
using Microsoft.AspNetCore.Http;
98
using Microsoft.IdentityModel.Tokens;
9+
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
10+
using Microsoft.IdentityModel.Protocols;
1011

1112
namespace ServerlessMicroservices.Shared.Services
1213
{
@@ -30,6 +31,7 @@ public class TokenValidationService : ITokenValidationService
3031
private DiscoveryCache _discoveryCache;
3132
private string _audience;
3233
private string _scope;
34+
private string _authority;
3335

3436
/// <summary>
3537
/// Configured by the function app settings. If false, validation is skipped.
@@ -50,6 +52,7 @@ public TokenValidationService(ISettingService settingService, ILoggerService log
5052

5153
_audience = settingService.GetApiApplicationId();
5254
_scope = settingService.GetApiScopeName();
55+
_authority = settingService.GetAuthorityUrl();
5356
AuthEnabled = settingService.EnableAuth();
5457
}
5558

@@ -88,6 +91,9 @@ async Task<ClaimsPrincipal> ValidateJwt(string token)
8891
var handler = new JwtSecurityTokenHandler();
8992
handler.InboundClaimTypeMap.Clear();
9093

94+
// Debugging purposes only, set this to false for production
95+
Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
96+
9197
try
9298
{
9399
var principal = handler.ValidateToken(token, validationParams, out _);
@@ -114,25 +120,33 @@ async Task<TokenValidationParameters> GetValidationParameters()
114120
return null;
115121
}
116122

117-
var keys = disco.KeySet.Keys
118-
.Where(x => x.Use == SigningKeyUseType)
119-
.Select(x =>
120-
{
121-
return new RsaSecurityKey(new System.Security.Cryptography.RSAParameters
122-
{
123-
Exponent = Base64Url.Decode(x.E),
124-
Modulus = Base64Url.Decode(x.N)
125-
})
126-
{
127-
KeyId = x.Kid
128-
};
129-
});
123+
ConfigurationManager<OpenIdConnectConfiguration> configManager =
124+
new ConfigurationManager<OpenIdConnectConfiguration>(
125+
$"{_authority}/.well-known/openid-configuration",
126+
new OpenIdConnectConfigurationRetriever());
127+
128+
OpenIdConnectConfiguration config = null;
129+
config = await configManager.GetConfigurationAsync();
130+
131+
//var keys = disco.KeySet.Keys
132+
// .Where(x => x.Use == SigningKeyUseType)
133+
// .Select(x =>
134+
// {
135+
// return new RsaSecurityKey(new System.Security.Cryptography.RSAParameters
136+
// {
137+
// Exponent = Base64Url.Decode(x.E),
138+
// Modulus = Base64Url.Decode(x.N)
139+
// })
140+
// {
141+
// KeyId = x.Kid
142+
// };
143+
// });
130144

131145
return new TokenValidationParameters
132146
{
133147
ValidIssuer = disco.Issuer,
134148
ValidAudience = _audience,
135-
IssuerSigningKeys = keys,
149+
IssuerSigningKeys = config.SigningKeys,
136150
NameClaimType = NameClaimType,
137151
RoleClaimType = RoleClaimType
138152
};

dotnet/ServerlessMicroservices.Shared/Services/UserService.cs

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,21 @@
44
using System.Net.Http.Headers;
55
using System.Text;
66
using System.Threading.Tasks;
7-
using Microsoft.IdentityModel.Clients.ActiveDirectory;
7+
using Microsoft.Identity.Client;
88
using Newtonsoft.Json;
99

1010
namespace ServerlessMicroservices.Shared.Services
1111
{
1212
public class UserService : IUserService
1313
{
14-
const string GraphBaseUrl = "https://graph.windows.net/";
15-
const string GraphVersionQueryString = "?" + GraphVersion;
16-
const string GraphVersion = "api-version=1.6";
14+
const string GraphBaseUrl = "https://graph.microsoft.com/v1.0";
15+
const string GraphVersionQueryString = "?";
16+
17+
private string[] _scopes = new[] { "https://graph.microsoft.com/.default" };
18+
private IConfidentialClientApplication _app;
19+
private readonly string _authority = "https://login.microsoftonline.com/";
20+
1721

18-
private readonly AuthenticationContext _authContext;
19-
private readonly ClientCredential _clientCreds;
20-
private readonly string _graphUrl;
2122

2223
public UserService(ISettingService settingService)
2324
: this(settingService.GetGraphTenantId(), settingService.GetGraphClientId(), settingService.GetGraphClientSecret())
@@ -28,22 +29,24 @@ public UserService(string tenantId, string clientId, string clientSecret)
2829
{
2930
if (string.IsNullOrEmpty(tenantId)) throw new ArgumentNullException(nameof(tenantId), "GraphTenantId environment variable must be set before instantiating UserService.");
3031

31-
_graphUrl = GraphBaseUrl + tenantId;
32+
_authority = _authority + tenantId;
3233

33-
var authority = "https://login.microsoftonline.com/" + tenantId;
34-
_authContext = new AuthenticationContext(authority);
35-
_clientCreds = new ClientCredential(clientId, clientSecret);
34+
_app = ConfidentialClientApplicationBuilder.Create(clientId)
35+
.WithClientSecret(clientSecret)
36+
.WithAuthority(new Uri(_authority))
37+
.Build();
3638
}
3739

3840
async Task<string> GetAccessToken()
3941
{
40-
var authResult = await _authContext.AcquireTokenAsync(GraphBaseUrl, _clientCreds);
41-
return authResult.AccessToken;
42+
var result = await _app.AcquireTokenForClient(_scopes)
43+
.ExecuteAsync();
44+
return result.AccessToken;
4245
}
4346

4447
public async Task<(User, string error)> CreateUser(CreateUser newUser)
4548
{
46-
var url = _graphUrl + "/users" + GraphVersionQueryString;
49+
var url = GraphBaseUrl + "/users";
4750

4851
var client = new HttpClient();
4952
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await GetAccessToken());
@@ -70,7 +73,7 @@ async Task<string> GetAccessToken()
7073

7174
public async Task<(IEnumerable<User>, string error)> GetUsers()
7275
{
73-
var url = _graphUrl + "/users" + GraphVersionQueryString;
76+
var url = GraphBaseUrl + "/users";
7477

7578
var client = new HttpClient();
7679
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await GetAccessToken());
@@ -98,7 +101,7 @@ async Task<string> GetAccessToken()
98101
{
99102
if (String.IsNullOrWhiteSpace(userId)) throw new ArgumentNullException(nameof(userId));
100103

101-
var url = _graphUrl + "/users/" + userId + GraphVersionQueryString;
104+
var url = GraphBaseUrl + "/users/" + userId;
102105

103106
var client = new HttpClient();
104107
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await GetAccessToken());

test/settings.example.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ window.authClientId = 'a298b04d-dbe2-4fc8-8191-b64c1fd287e2';
33
window.authAuthority = 'https://wviriyab2c.b2clogin.com/wviriyab2c.onmicrosoft.com/B2C_1_default-signin';
44
window.knownAuthority = 'wviriyab2c.b2clogin.com';
55
window.redirectUri = 'http://localhost:4280';
6-
window.loginScopes = ['openid','https://wviriyab2c.onmicrosoft.com/3ebcd877-a9a5-4d12-9ac8-2c66a925bd77/rideshare'];
7-
window.apiScopes = ['https://wviriyab2c.onmicrosoft.com/3ebcd877-a9a5-4d12-9ac8-2c66a925bd77/rideshare'];
6+
window.loginScopes = ['https://wviriyab2c.onmicrosoft.com/a298b04d-dbe2-4fc8-8191-b64c1fd287e2/rideshare'];
7+
window.apiScopes = ['https://wviriyab2c.onmicrosoft.com/a298b04d-dbe2-4fc8-8191-b64c1fd287e2/rideshare'];
88
window.authEnabled = true;
99

1010

web/serverless-microservices-web/package-lock.json

Lines changed: 2 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

web/serverless-microservices-web/src/utils/Authentication.js

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { LogLevel, PublicClientApplication } from '@azure/msal-browser';
22

3+
// refer to https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/working-with-b2c.md
4+
35
const ACCESS_TOKEN = 'rideshare_access_token';
46
const USER_DETAILS = 'rideshare_user_details';
57
let _accountId = null;
@@ -74,17 +76,17 @@ export class Authentication {
7476
_tokenRequest.account = this._publicClientApplication.getAccountByHomeId(_accountId);
7577
return this._publicClientApplication.acquireTokenSilent(_tokenRequest).then(
7678
accessToken => {
77-
return accessToken;
78-
},
79-
error => {
80-
return this._publicClientApplication.acquireTokenPopup(_tokenRequest).then(
79+
if (accessToken.accessToken === null || accessToken.accessToken === "") {
80+
return this._publicClientApplication.acquireTokenPopup(_tokenRequest).then(
8181
accessToken => {
82-
return accessToken;
82+
return accessToken.accessToken;
8383
},
8484
err => {
8585
console.error(err);
8686
}
8787
);
88+
}
89+
return accessToken.accessToken;
8890
}
8991
);
9092
}

0 commit comments

Comments
 (0)