|
6 | 6 | using Microsoft.Identity.Web.Client;
|
7 | 7 | using Microsoft.Identity.Web.Resource;
|
8 | 8 | using System.Collections.Generic;
|
| 9 | +using System.IdentityModel.Tokens.Jwt; |
| 10 | +using System.Linq; |
| 11 | +using System.Security.Claims; |
9 | 12 | using System.Threading.Tasks;
|
10 | 13 |
|
11 | 14 | namespace Microsoft.Identity.Web
|
@@ -59,22 +62,38 @@ public static IServiceCollection AddProtectWebApiWithMicrosoftIdentityPlatformV2
|
59 | 62 | /// </summary>
|
60 | 63 | /// <param name="services">Service collection to which to add authentication</param>
|
61 | 64 | /// <param name="configuration">Configuration</param>
|
| 65 | + /// <param name="scopes">Optional parameters. If not specified, the token used to call the protected API |
| 66 | + /// will be kept with the user's claims until the API calls a downstream API. Otherwise the account for the |
| 67 | + /// user is immediately added to the token cache</param> |
62 | 68 | /// <returns></returns>
|
63 |
| - public static IServiceCollection AddProtectedApiCallsWebApis(this IServiceCollection services, IConfiguration configuration, IEnumerable<string> scopes) |
| 69 | + public static IServiceCollection AddProtectedApiCallsWebApis(this IServiceCollection services, IConfiguration configuration, IEnumerable<string> scopes=null) |
64 | 70 | {
|
65 | 71 | services.AddTokenAcquisition();
|
66 | 72 | services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options =>
|
67 | 73 | {
|
| 74 | + // If you don't pre-provide scopes when adding calling AddProtectedApiCallsWebApis, the On behalf of |
| 75 | + // flow will be delayed (lazy construction of MSAL's application |
| 76 | + |
68 | 77 | options.Events.OnTokenValidated = async context =>
|
69 | 78 | {
|
70 |
| - var tokenAcquisition = context.HttpContext.RequestServices.GetRequiredService<ITokenAcquisition>(); |
71 |
| - context.Success(); |
| 79 | + if (scopes != null && scopes.Any()) |
| 80 | + { |
| 81 | + var tokenAcquisition = context.HttpContext.RequestServices.GetRequiredService<ITokenAcquisition>(); |
| 82 | + context.Success(); |
| 83 | + tokenAcquisition.AddAccountToCacheFromJwt(context, scopes); |
| 84 | + } |
| 85 | + else |
| 86 | + { |
| 87 | + context.Success(); |
72 | 88 |
|
| 89 | + // Todo : rather use options.SaveToken? |
| 90 | + (context.Principal.Identity as ClaimsIdentity).AddClaim(new Claim("jwt", (context.SecurityToken as JwtSecurityToken).RawData)); |
| 91 | + } |
73 | 92 | // Adds the token to the cache, and also handles the incremental consent and claim challenges
|
74 |
| - tokenAcquisition.AddAccountToCacheFromJwt(context, scopes); |
75 | 93 | await Task.FromResult(0);
|
76 | 94 | };
|
77 | 95 | });
|
| 96 | + |
78 | 97 | return services;
|
79 | 98 | }
|
80 | 99 | }
|
|
0 commit comments