|
9 | 9 | using System.Threading.Tasks;
|
10 | 10 | using Microsoft.AspNetCore.Authentication;
|
11 | 11 | using Microsoft.AspNetCore.Authorization;
|
| 12 | +using Microsoft.AspNetCore.Authorization.Policy; |
12 | 13 | using Microsoft.AspNetCore.Mvc.Core;
|
13 | 14 | using Microsoft.AspNetCore.Mvc.Filters;
|
14 | 15 | using Microsoft.AspNetCore.Mvc.Internal;
|
@@ -125,41 +126,26 @@ public virtual async Task OnAuthorizationAsync(AuthorizationFilterContext contex
|
125 | 126 | return;
|
126 | 127 | }
|
127 | 128 |
|
128 |
| - // Build a ClaimsPrincipal with the Policy's required authentication types |
129 |
| - if (effectivePolicy.AuthenticationSchemes != null && effectivePolicy.AuthenticationSchemes.Count > 0) |
130 |
| - { |
131 |
| - ClaimsPrincipal newPrincipal = null; |
132 |
| - for (var i = 0; i < effectivePolicy.AuthenticationSchemes.Count; i++) |
133 |
| - { |
134 |
| - var scheme = effectivePolicy.AuthenticationSchemes[i]; |
135 |
| - var result = await context.HttpContext.AuthenticateAsync(scheme); |
136 |
| - if (result.Succeeded) |
137 |
| - { |
138 |
| - newPrincipal = SecurityHelper.MergeUserPrincipal(newPrincipal, result.Principal); |
139 |
| - } |
140 |
| - } |
141 |
| - // If all schemes failed authentication, provide a default identity anyways |
142 |
| - if (newPrincipal == null) |
143 |
| - { |
144 |
| - newPrincipal = new ClaimsPrincipal(new ClaimsIdentity()); |
145 |
| - } |
146 |
| - context.HttpContext.User = newPrincipal; |
147 |
| - } |
| 129 | + var policyEvaluator = context.HttpContext.RequestServices.GetRequiredService<IPolicyEvaluator>(); |
| 130 | + |
| 131 | + var authenticateResult = await policyEvaluator.AuthenticateAsync(effectivePolicy, context.HttpContext); |
148 | 132 |
|
149 | 133 | // Allow Anonymous skips all authorization
|
150 | 134 | if (context.Filters.Any(item => item is IAllowAnonymousFilter))
|
151 | 135 | {
|
152 | 136 | return;
|
153 | 137 | }
|
154 | 138 |
|
155 |
| - var httpContext = context.HttpContext; |
156 |
| - var authService = httpContext.RequestServices.GetRequiredService<IAuthorizationService>(); |
| 139 | + var authorizeResult = await policyEvaluator.AuthorizeAsync(effectivePolicy, authenticateResult, context.HttpContext); |
157 | 140 |
|
158 |
| - // Note: Default Anonymous User is new ClaimsPrincipal(new ClaimsIdentity()) |
159 |
| - if (!await authService.AuthorizeAsync(httpContext.User, context, effectivePolicy)) |
| 141 | + if (authorizeResult.Challenged) |
160 | 142 | {
|
161 | 143 | context.Result = new ChallengeResult(effectivePolicy.AuthenticationSchemes.ToArray());
|
162 | 144 | }
|
| 145 | + else if (authorizeResult.Forbidden) |
| 146 | + { |
| 147 | + context.Result = new ForbidResult(effectivePolicy.AuthenticationSchemes.ToArray()); |
| 148 | + } |
163 | 149 | }
|
164 | 150 |
|
165 | 151 | IFilterMetadata IFilterFactory.CreateInstance(IServiceProvider serviceProvider)
|
|
0 commit comments