Skip to content
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

add app roles #278

Merged
merged 2 commits into from
Jul 1, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/Microsoft.Identity.Web/Microsoft.Identity.Web.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;

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 the roles in controller actions.
/// </summary>
public static class RolesRequiredHttpContextExtensions
{
/// <summary>
/// When applied to an <see cref="HttpContext"/>, verifies that the application
/// has the expected roles.
/// </summary>
/// <param name="context">HttpContext (from the controller).</param>
/// <param name="acceptedRoles">Roles accepted by this web API.</param>
/// <remarks>When the roles don't match, the response is a 403 (Forbidden),
/// because the app does not have the expected roles.</remarks>
public static void ValidateAppRole(this HttpContext context, params string[] acceptedRoles)
{
if (acceptedRoles == null)
{
throw new ArgumentNullException(nameof(acceptedRoles));
}

if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
else if (context.User == null || context.User.Claims == null || !context.User.Claims.Any())
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
else
{
// Attempt with Roles claim
Claim? rolesClaim = context.User.FindFirst(ClaimConstants.Roles);

// Fallback to Role claim name
if (rolesClaim == null)
{
rolesClaim = context.User.FindFirst(ClaimConstants.Role);
}

if (rolesClaim == null || !rolesClaim.Value.Split(' ').Intersect(acceptedRoles).Any())
{
context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
string message = $"The 'roles' or 'role' claim does not contain roles '{string.Join(",", acceptedRoles)}' or was not found";
context.Response.WriteAsync(message);
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Net;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.Identity.Web.Resource;
using Microsoft.Identity.Web.Test.Common.TestHelpers;
using Xunit;

namespace Microsoft.Identity.Web.Test.Resource
{
public class RolesRequiredHttpContextExtensionsTests
{
[Fact]
public void VerifyUserHasAnyAcceptedScope_NullParameters_ThrowsException()
{
HttpContext httpContext = null;

Assert.Throws<ArgumentNullException>(() => httpContext.ValidateAppRole(string.Empty));

httpContext = HttpContextUtilities.CreateHttpContext();

Assert.Throws<ArgumentNullException>("acceptedRoles", () => httpContext.ValidateAppRole(null));
}

[Fact]
public void VerifyAppHasAnyAcceptedRoles_NoClaims_ThrowsException()
{
var acceptedRoles = new[] { "access_as_application", "access_as_application_for_write" };
var expectedStatusCode = (int)HttpStatusCode.Unauthorized;

var httpContext = HttpContextUtilities.CreateHttpContext();
httpContext.ValidateAppRole(acceptedRoles);

HttpResponse response = httpContext.Response;
Assert.Equal(expectedStatusCode, response.StatusCode);
}

[Fact]
public void VerifyAppHasAnyAcceptedRole_NoAcceptedRoles_ThrowsException()
{
var acceptedRoles = new[] { "access_as_application", "access_as_application_for_write" };
var actualRoles = new[] { "access_as_application_for_read_all_directory", "access_as_application_for_read" };
var expectedErrorMessage = $"The 'roles' or 'role' claim does not contain roles '{string.Join(",", acceptedRoles)}' or was not found";
var expectedStatusCode = (int)HttpStatusCode.Forbidden;

var httpContext = HttpContextUtilities.CreateHttpContext(actualRoles);
httpContext.ValidateAppRole(acceptedRoles);

HttpResponse response = httpContext.Response;
Assert.Equal(expectedStatusCode, response.StatusCode);
Assert.Equal(expectedErrorMessage, GetBody(response));

httpContext = HttpContextUtilities.CreateHttpContext(actualRoles);
httpContext.ValidateAppRole(acceptedRoles);
response = httpContext.Response;
Assert.Equal(expectedStatusCode, response.StatusCode);
Assert.Equal(expectedErrorMessage, GetBody(response));
}

[Fact]
public void VerifyAppHasAnyAcceptedRole_MatchesAcceptedRoles_ExecutesSuccessfully()
{
var httpContext = HttpContextUtilities.CreateHttpContext(new[] { "acceptedRole1" });
httpContext.ValidateAppRole("acceptedRole1");

httpContext = HttpContextUtilities.CreateHttpContext(new[] { "acceptedRole1 acceptedRole2" });
httpContext.ValidateAppRole("acceptedRole2");

httpContext = HttpContextUtilities.CreateHttpContext(new[] { "acceptedRole2" });
httpContext.ValidateAppRole("acceptedRole1", "acceptedRole2");

httpContext = HttpContextUtilities.CreateHttpContext(new[] { "acceptedRole2 acceptedRole1" });
httpContext.ValidateAppRole("acceptedRole1", "acceptedRole2");
}

private static string GetBody(HttpResponse response)
{
byte[] buffer = new byte[response.Body.Length];
response.Body.Seek(0, System.IO.SeekOrigin.Begin);
response.Body.Read(buffer, 0, buffer.Length);
string body = Encoding.Default.GetString(buffer);
return body;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

using System;
using System.Net;
using System.Net.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Identity.Web.Resource;
using Microsoft.Identity.Web.Test.Common.TestHelpers;
Expand Down