-
Notifications
You must be signed in to change notification settings - Fork 217
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Create a mix of ScopesRequiredHttpContextExtensions and RolesRequired… #1814
Open
BluMichele
wants to merge
2
commits into
AzureAD:master
Choose a base branch
from
BluMichele:patch-2
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
90 changes: 90 additions & 0 deletions
90
src/Microsoft.Identity.Web/Resource/RolesOrScopesRequiredHttpContextExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT License. | ||
|
||
using global::Microsoft.AspNetCore.Http; | ||
using global::Microsoft.Identity.Web; | ||
using System.Globalization; | ||
using System.Net; | ||
using System.Security.Claims; | ||
|
||
namespace Microsoft.Identity.Web.Resource; | ||
|
||
/// <summary> | ||
/// Extension class providing the extension methods for <see cref="HttpContent"/> that | ||
/// can be used in web APIs to validate scopes and roles in controller actions. | ||
/// </summary> | ||
public static class RolesOrScopesRequiredHttpContextExtensions | ||
{ | ||
/// <summary> | ||
/// When applied to an <see cref="HttpContext"/>, verifies that the user authenticated in the | ||
/// web API has any of the accepted scopes or roles. | ||
/// If there is no authenticated user, the response is a 401 (Unauthenticated). | ||
/// If the authenticated user does not have any of these <paramref name="acceptedScopes"/> or <paramref name="acceptedRoles"/>, the | ||
/// method updates the HTTP response providing a status code 403 (Forbidden) | ||
/// and writes to the response body a message telling which scopes or roles are expected in the token. | ||
/// </summary> | ||
/// <param name="context">HttpContext (from the controller).</param> | ||
/// <param name="acceptedScopes">Scopes accepted by this web API.</param> | ||
/// <param name="acceptedRoles">Roles accepted by this web API.</param> | ||
|
||
public static void ValidateAppRolesOrScopes(this HttpContext context, string[] acceptedScopes, string[] acceptedRoles) | ||
{ | ||
if (acceptedScopes?.Any() != true && acceptedRoles?.Any() != true) | ||
{ | ||
throw new ArgumentException($"{nameof(acceptedScopes)} and {nameof(acceptedRoles)} are null or empty"); | ||
} | ||
ArgumentNullException.ThrowIfNull(context); | ||
|
||
IEnumerable<Claim> userClaims; | ||
ClaimsPrincipal user; | ||
|
||
// Need to lock due to https://docs.microsoft.com/en-us/aspnet/core/performance/performance-best-practices?#do-not-access-httpcontext-from-multiple-threads | ||
lock (context) | ||
{ | ||
user = context.User; | ||
userClaims = user.Claims; | ||
} | ||
|
||
if (user == null || userClaims == null || !userClaims.Any()) | ||
{ | ||
lock (context) | ||
{ | ||
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; | ||
} | ||
//throw new UnauthorizedAccessException(IDWebErrorMessage.UnauthenticatedUser); | ||
throw new UnauthorizedAccessException("IDW10204: The user is unauthenticated. The HttpContext does not contain any claims. "); | ||
} | ||
|
||
var hasScopeOrRole = false; | ||
if (acceptedScopes?.Any() == true) | ||
{ | ||
var scpClaim = user.FindFirst(ClaimConstants.Scp)?.Value?.Split(' '); | ||
var scopeClaim = user.FindFirst(ClaimConstants.Scope)?.Value?.Split(' '); | ||
|
||
hasScopeOrRole = scpClaim?.Any(acceptedScopes.Contains) == true || scopeClaim?.Any(acceptedScopes.Contains) == true; | ||
} | ||
if (acceptedRoles?.Any() == true) | ||
{ | ||
var rolesClaim = userClaims.Where(claims => claims.Type == ClaimConstants.Roles || claims.Type == ClaimConstants.Role) | ||
.SelectMany(roles => roles.Value.Split(' ')); | ||
hasScopeOrRole = rolesClaim?.Any(acceptedRoles.Contains) == true; | ||
} | ||
if (hasScopeOrRole) | ||
{ | ||
return; | ||
} | ||
|
||
var message = string.Format(CultureInfo.InvariantCulture, | ||
$"The 'scope' or 'scp' claim does not contain scopes '{0}' nor " + | ||
$"the 'roles' or 'role' claim does not contain roles '{1}'", | ||
new string[] { string.Join(",", acceptedScopes), string.Join(",", acceptedRoles) }); | ||
|
||
lock (context) | ||
{ | ||
context.Response.StatusCode = (int)HttpStatusCode.Forbidden; | ||
context.Response.WriteAsync(message); | ||
context.Response.CompleteAsync(); | ||
} | ||
throw new UnauthorizedAccessException(message); | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We should rather set that in an ErrorDescription header or www-Authenticate header, maybe (and not WriteAsync / CompleteAsync())
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You might be right, I quite much copied the code style of https://github.com/AzureAD/microsoft-identity-web/blob/master/src/Microsoft.Identity.Web/Resource/ScopesRequiredHttpContextExtensions.cs