Skip to content
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
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,4 @@ yarn.lock
package-lock.json
[eE]ncrypted.[sS]ecret.*
*.csproj.user
*.key
266 changes: 266 additions & 0 deletions Doppler.HelloMicroservice.Test/AuthorizationTest.cs

Large diffs are not rendered by default.

16 changes: 16 additions & 0 deletions Doppler.HelloMicroservice.Test/HttpResponseMessageExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;
using System.Linq;
using System.Net.Http;

namespace Doppler.HelloMicroservice
{
public static class HttpResponseMessageExtensions
{
public static string GetHeadersAsString(this HttpResponseMessage response)
{
var keysAndValues = response.Headers.SelectMany(x => x.Value.Select(y => new { x.Key, Value = y }));
var headerLines = keysAndValues.Select(x => $"{x.Key}: {x.Value}");
return string.Join("\n", headerLines);
}
}
}
50 changes: 50 additions & 0 deletions Doppler.HelloMicroservice/Controllers/HelloController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Doppler.HelloMicroservice.DopplerSecurity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Doppler.HelloMicroservice.Controllers
{
[Authorize]
[ApiController]
public class HelloController
{
[AllowAnonymous]
[HttpGet("/hello/anonymous")]
public string GetForAnonymous()
{
return "Hello anonymous!";
}

[HttpGet("/hello/valid-token")]
public string GetForValidToken()
{
return "Hello! you have a valid token!";
}

[Authorize(Policies.ONLY_SUPERUSER)]
[HttpGet("/hello/superuser")]
public string GetForSuperUserToken()
{
return "Hello! you have a valid SuperUser token!";
}

[Authorize(Policies.OWN_RESOURCE_OR_SUPERUSER)]
[HttpGet("/accounts/{accountId:int:min(0)}/hello")]
public string GetForAccountById(int accountId)
{
return $"Hello! \"you\" that have access to the account with ID '{accountId}'";
}

[Authorize(Policies.OWN_RESOURCE_OR_SUPERUSER)]
[HttpGet("/accounts/{accountname}/hello")]
public string GetForAccountByName(string accountname)
{
return $"Hello! \"you\" that have access to the account with accountname '{accountname}'";
}
}
}
1 change: 1 addition & 0 deletions Doppler.HelloMicroservice/Doppler.HelloMicroservice.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.5" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.10.14" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.1.2" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Security.Cryptography;

namespace Doppler.HelloMicroservice.DopplerSecurity
{
public class ConfigureDopplerSecurityOptions : IConfigureOptions<DopplerSecurityOptions>
{
private readonly IConfiguration _configuration;
private readonly IFileProvider _fileProvider;

public ConfigureDopplerSecurityOptions(IConfiguration configuration, IWebHostEnvironment webHostEnvironment)
{
_configuration = configuration;
_fileProvider = webHostEnvironment.ContentRootFileProvider;
}

private static string ReadToEnd(IFileInfo fileInfo)
{
using var stream = fileInfo.CreateReadStream();
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}

private static RsaSecurityKey ParseXmlString(string xmlString)
{
using var rsaProvider = new RSACryptoServiceProvider();
rsaProvider.FromXmlString(xmlString);
var rsaParameters = rsaProvider.ExportParameters(false);
return new RsaSecurityKey(RSA.Create(rsaParameters));
}

public void Configure(DopplerSecurityOptions options)
{
var path = _configuration.GetValue(
DopplerSecurityDefaults.PUBLIC_KEYS_FOLDER_CONFIG_KEY,
DopplerSecurityDefaults.PUBLIC_KEYS_FOLDER_DEFAULT_CONFIG_VALUE);

var filenameRegex = new Regex(_configuration.GetValue(
DopplerSecurityDefaults.PUBLIC_KEYS_FILENAME_CONFIG_KEY,
DopplerSecurityDefaults.PUBLIC_KEYS_FILENAME_REGEX_DEFAULT_CONFIG_VALUE));

var files = _fileProvider.GetDirectoryContents(path)
.Where(x => !x.IsDirectory && filenameRegex.IsMatch(x.Name));

var publicKeys = files
.Select(ReadToEnd)
.Select(ParseXmlString)
.ToArray();

options.SigningKeys = publicKeys;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using Microsoft.AspNetCore.Authorization;

namespace Doppler.HelloMicroservice.DopplerSecurity
{
public class DopplerAuthorizationRequirement : IAuthorizationRequirement
{
public bool AllowSuperUser { get; init; }
public bool AllowOwnResource { get; init; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Doppler.HelloMicroservice.DopplerSecurity
{
public static class DopplerSecurityDefaults
{
public const string PUBLIC_KEYS_FOLDER_CONFIG_KEY = "DopplerSecurity:PublicKeysFolder";
public const string PUBLIC_KEYS_FOLDER_DEFAULT_CONFIG_VALUE = "public-keys";
public const string PUBLIC_KEYS_FILENAME_CONFIG_KEY = @"DopplerSecurity:PublicKeysFilenameRegex";
public const string PUBLIC_KEYS_FILENAME_REGEX_DEFAULT_CONFIG_VALUE = "\\.xml$";
public const string SUPERUSER_JWT_KEY = "isSU";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using Microsoft.IdentityModel.Tokens;
using System.Collections.Generic;

namespace Doppler.HelloMicroservice.DopplerSecurity
{
public class DopplerSecurityOptions
{
public IEnumerable<SecurityKey> SigningKeys { get; set; } = new SecurityKey[0];
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
using Doppler.HelloMicroservice.DopplerSecurity;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

namespace Microsoft.Extensions.DependencyInjection
{
public static class DopplerSecurityServiceCollectionExtensions
{
public static IServiceCollection AddDopplerSecurity(this IServiceCollection services)
{
services.AddSingleton<IAuthorizationHandler, IsSuperUserAuthorizationHandler>();
services.AddSingleton<IAuthorizationHandler, IsOwnResourceAuthorizationHandler>();

services.ConfigureOptions<ConfigureDopplerSecurityOptions>();

services.AddOptions<AuthorizationOptions>()
.Configure(o =>
{
var simpleAuthenticationPolicy = new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.Build();

var onlySuperUserPolicy = new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.AddRequirements(new DopplerAuthorizationRequirement()
{
AllowSuperUser = true
})
.RequireAuthenticatedUser()
.Build();

var ownResourceOrSuperUserPolicy = new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.AddRequirements(new DopplerAuthorizationRequirement()
{
AllowSuperUser = true,
AllowOwnResource = true
})
.RequireAuthenticatedUser()
.Build();

// TODO: I would like to use ownResourceOrSuperUserPolicy as the default policy, but I
// cannot override a more restrictive policy with a less restrictive one. So,
// for the moment, we have to be carefull and chooses the right one for each
// controller.
o.DefaultPolicy = simpleAuthenticationPolicy;
Comment on lines +45 to +49
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ms-darianbenito this what we were talking about today.


o.AddPolicy(Policies.ONLY_SUPERUSER, onlySuperUserPolicy);
o.AddPolicy(Policies.OWN_RESOURCE_OR_SUPERUSER, ownResourceOrSuperUserPolicy);
});

services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme)
.Configure<IOptions<DopplerSecurityOptions>>((o, securityOptions) =>
{
o.SaveToken = true;
o.TokenValidationParameters = new TokenValidationParameters()
{
IssuerSigningKeys = securityOptions.Value.SigningKeys,
ValidateIssuer = false,
ValidateAudience = false,
};
});

services.AddAuthentication()
.AddJwtBearer();

services.AddAuthorization();

return services;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@

using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Http;

namespace Doppler.HelloMicroservice.DopplerSecurity
{
public class IsOwnResourceAuthorizationHandler : AuthorizationHandler<DopplerAuthorizationRequirement>
{
private readonly ILogger<IsOwnResourceAuthorizationHandler> _logger;

public IsOwnResourceAuthorizationHandler(ILogger<IsOwnResourceAuthorizationHandler> logger)
{
_logger = logger;
}

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, DopplerAuthorizationRequirement requirement)
{
if (requirement.AllowOwnResource && IsOwnResource(context))
{
context.Succeed(requirement);
}

return Task.CompletedTask;
}

private bool IsOwnResource(AuthorizationHandlerContext context)
{
if (!TryGetRouteData(context, out var routeData))
{
_logger.LogError("Is not possible access to Resource information. Type of context.Resource: {ResourceType}", context.Resource?.GetType().Name ?? "null");
return false;
}

if (routeData.Values.TryGetValue("accountId", out var accountId) && accountId?.ToString() == GetTokenNameIdentifier(context.User))
{
// TODO: In case of using different public keys, for example Doppler and Relay,
// it is necessary to check token Issuer information, to validate right origin.
return true;
}

if (routeData.Values.TryGetValue("accountname", out var accountname) && accountname?.ToString() == GetTokenUniqueName(context.User))
{
// TODO: In case of using different public keys, for example Doppler and Relay,
// it is necessary to check token Issuer information, to validate right origin.
return true;
}

return false;
}

private static string GetTokenUniqueName(ClaimsPrincipal user) =>
user.FindFirst(c => c.Type == ClaimTypes.Name)?.Value;

private static string GetTokenNameIdentifier(ClaimsPrincipal user) =>
user.FindFirst(c => c.Type == ClaimTypes.NameIdentifier)?.Value;

private static bool TryGetRouteData(AuthorizationHandlerContext context, out RouteData routeData)
{
// In my local environment with .NET 5
if (context.Resource is HttpContext httpContext)
{
routeData = httpContext.GetRouteData();
return true;
}

// ASP.NET Core 2?
if (context.Resource is AuthorizationFilterContext authorizationFilterContext)
{
routeData = authorizationFilterContext.RouteData;
return true;
}

routeData = null;
return false;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Doppler.HelloMicroservice.DopplerSecurity
{
public class IsSuperUserAuthorizationHandler : AuthorizationHandler<DopplerAuthorizationRequirement>
{
private readonly ILogger<IsSuperUserAuthorizationHandler> _logger;

public IsSuperUserAuthorizationHandler(ILogger<IsSuperUserAuthorizationHandler> logger)
{
_logger = logger;
}

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, DopplerAuthorizationRequirement requirement)
{
if (requirement.AllowSuperUser && IsSuperUser(context))
{
context.Succeed(requirement);
}

return Task.CompletedTask;
}

private bool IsSuperUser(AuthorizationHandlerContext context)
{
if (!context.User.HasClaim(c => c.Type.Equals(DopplerSecurityDefaults.SUPERUSER_JWT_KEY)))
{
_logger.LogDebug("The token hasn't super user permissions.");
return false;
}

var isSuperUser = bool.Parse(context.User.FindFirst(c => c.Type.Equals(DopplerSecurityDefaults.SUPERUSER_JWT_KEY)).Value);
if (isSuperUser)
{
return true;
}

_logger.LogDebug("The token super user permissions is false.");
return false;
}
}
}
8 changes: 8 additions & 0 deletions Doppler.HelloMicroservice/DopplerSecurity/Policies.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace Doppler.HelloMicroservice.DopplerSecurity
{
public static class Policies
{
public const string ONLY_SUPERUSER = nameof(ONLY_SUPERUSER);
public const string OWN_RESOURCE_OR_SUPERUSER = nameof(OWN_RESOURCE_OR_SUPERUSER);
}
}
Loading