diff --git a/README.md b/README.md index a18d15fe..c9ff5a61 100644 --- a/README.md +++ b/README.md @@ -30,7 +30,7 @@ A quick list of Ocelot's capabilities for more information see the [documentatio * Kubernetes * WebSockets * Authentication -* Authorisation +* Authorization * Rate Limiting * Caching * Retry policies / QoS diff --git a/docs/features/authentication.rst b/docs/features/authentication.rst index 8aeca15f..e41c0033 100644 --- a/docs/features/authentication.rst +++ b/docs/features/authentication.rst @@ -1,7 +1,7 @@ Authentication ============== -In order to authenticate Routes and subsequently use any of Ocelot's claims based features such as authorisation or modifying the request with values from the token. Users must register authentication services in their Startup.cs as usual but they provide a scheme (authentication provider key) with each registration e.g. +In order to authenticate Routes and subsequently use any of Ocelot's claims based features such as authorization or modifying the request with values from the token. Users must register authentication services in their Startup.cs as usual but they provide a scheme (authentication provider key) with each registration e.g. .. code-block:: csharp diff --git a/docs/features/authorisation.rst b/docs/features/authorization.rst similarity index 51% rename from docs/features/authorisation.rst rename to docs/features/authorization.rst index ab1bc1b5..c890c14c 100644 --- a/docs/features/authorisation.rst +++ b/docs/features/authorization.rst @@ -1,7 +1,7 @@ -Authorisation +Authorization ============= -Ocelot supports claims based authorisation which is run post authentication. This means if you have a route you want to authorise you can add the following to you Route configuration. +Ocelot supports claims based authorization which is run post authentication. This means if you have a route you want to authorize you can add the following to you Route configuration. .. code-block:: json @@ -9,7 +9,7 @@ Ocelot supports claims based authorisation which is run post authentication. Thi "UserType": "registered" } -In this example when the authorisation middleware is called Ocelot will check to seeif the user has the claim type UserType and if the value of that claim is registered. If it isn't then the user will not be authorised and the response will be 403 forbidden. +In this example when the authorization middleware is called Ocelot will check to seeif the user has the claim type UserType and if the value of that claim is registered. If it isn't then the user will not be authorized and the response will be 403 forbidden. diff --git a/docs/features/claimstransformation.rst b/docs/features/claimstransformation.rst index d58801e5..c82657a4 100644 --- a/docs/features/claimstransformation.rst +++ b/docs/features/claimstransformation.rst @@ -3,7 +3,7 @@ Claims Transformation Ocelot allows the user to access claims and transform them into headers, query string parameters, other claims and change downstream paths. This is only available once a user has been authenticated. -After the user is authenticated we run the claims to claims transformation middleware. This allows the user to transform claims before the authorisation middleware is called. After the user is authorised first we call the claims to headers middleware, thenthe claims to query string parameters middleware, and Finally the claims to downstream pathmiddleware. +After the user is authenticated we run the claims to claims transformation middleware. This allows the user to transform claims before the authorization middleware is called. After the user is authorized first we call the claims to headers middleware, thenthe claims to query string parameters middleware, and Finally the claims to downstream pathmiddleware. The syntax for performing the transforms is the same for each process. In the Route configuration a json dictionary is added with a specific name either AddClaimsToRequest, AddHeadersToRequest, AddQueriesToRequest, or ChangeDownstreamPathTemplate. diff --git a/docs/features/errorcodes.rst b/docs/features/errorcodes.rst index aeea7b63..d07eb3a4 100644 --- a/docs/features/errorcodes.rst +++ b/docs/features/errorcodes.rst @@ -3,7 +3,7 @@ Http Error Status Codes Ocelot will return HTTP status error codes based on internal logic in certain siturations: - 401 if the authentication middleware runs and the user is not authenticated. -- 403 if the authorisation middleware runs and the user is unauthenticated, claim value not authroised, scope not authorised, user doesnt have required claim or cannot find claim. +- 403 if the authorization middleware runs and the user is unauthenticated, claim value not authroised, scope not authorized, user doesnt have required claim or cannot find claim. - 503 if the downstream request times out. - 499 if the request is cancelled by the client. - 404 if unable to find a downstream route. diff --git a/docs/features/middlewareinjection.rst b/docs/features/middlewareinjection.rst index 4b663658..7fccc599 100644 --- a/docs/features/middlewareinjection.rst +++ b/docs/features/middlewareinjection.rst @@ -31,9 +31,9 @@ The user can set functions against the following. * AuthenticationMiddleware - This overrides Ocelots authentication middleware. -* PreAuthorisationMiddleware - This allows the user to run pre authorisation logic and then call Ocelot's authorisation middleware. +* PreAuthorizationMiddleware - This allows the user to run pre authorization logic and then call Ocelot's authorization middleware. -* AuthorisationMiddleware - This overrides Ocelots authorisation middleware. +* AuthorizationMiddleware - This overrides Ocelots authorization middleware. * PreQueryStringBuilderMiddleware - This allows the user to manipulate the query string on the http request before it is passed to Ocelots request creator. diff --git a/docs/features/requestid.rst b/docs/features/requestid.rst index 519cc21a..d3673402 100644 --- a/docs/features/requestid.rst +++ b/docs/features/requestid.rst @@ -44,8 +44,8 @@ Below is an example of the logging when set at Debug level for a normal request. requestId: asdf, previousRequestId: no previous request id, message: downstream template is {downstreamRoute.Data.Route.DownstreamPath}, dbug: Ocelot.RateLimit.Middleware.ClientRateLimitMiddleware[0] requestId: asdf, previousRequestId: no previous request id, message: EndpointRateLimiting is not enabled for Ocelot.Values.PathTemplate, - dbug: Ocelot.Authorisation.Middleware.AuthorisationMiddleware[0] - requestId: 1234, previousRequestId: asdf, message: /posts/{postId} route does not require user to be authorised, + dbug: Ocelot.Authorization.Middleware.AuthorizationMiddleware[0] + requestId: 1234, previousRequestId: asdf, message: /posts/{postId} route does not require user to be authorized, dbug: Ocelot.DownstreamUrlCreator.Middleware.DownstreamUrlCreatorMiddleware[0] requestId: 1234, previousRequestId: asdf, message: downstream url is {downstreamUrl.Data.Value}, dbug: Ocelot.Request.Middleware.HttpRequestBuilderMiddleware[0] diff --git a/docs/features/websockets.rst b/docs/features/websockets.rst index 8a1acfdb..ad185f29 100644 --- a/docs/features/websockets.rst +++ b/docs/features/websockets.rst @@ -102,7 +102,7 @@ Unfortunately a lot of Ocelot's features are non websocket specific such as head 9. Claims Transformation 10. Caching 11. Authentication - If anyone requests it we might be able to do something with basic authentication. -12. Authorisation +12. Authorization I'm not 100% sure what will happen with this feature when it get's into the wild so please make sure you test thoroughly! diff --git a/docs/index.rst b/docs/index.rst index 44ad05c3..983d2471 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -26,7 +26,7 @@ Thanks for taking a look at the Ocelot documentation. Please use the left hand n features/servicefabric features/kubernetes features/authentication - features/authorisation + features/authorization features/websockets features/administration features/ratelimiting diff --git a/samples/OcelotGraphQL/README.md b/samples/OcelotGraphQL/README.md index ed6c1660..7f16ed98 100644 --- a/samples/OcelotGraphQL/README.md +++ b/samples/OcelotGraphQL/README.md @@ -1,7 +1,7 @@ # Ocelot using GraphQL example Loads of people keep asking me if Ocelot will every support GraphQL, in my mind Ocelot and GraphQL are two different things that can work together. -I would not try and implement GraphQL in Ocelot instead I would either have Ocelot in front of GraphQL to handle things like authorisation / authentication or I would +I would not try and implement GraphQL in Ocelot instead I would either have Ocelot in front of GraphQL to handle things like authorization / authentication or I would bring in the awesome [graphql-dotnet](https://github.com/graphql-dotnet/graphql-dotnet) library and use it in a [DelegatingHandler](http://ocelot.readthedocs.io/en/latest/features/delegatinghandlers.html). This way you could have Ocelot and GraphQL without the extra hop to GraphQL. This same is an example of how to do that. ## Example diff --git a/src/Ocelot/Authorisation/ClaimValueNotAuthorisedError.cs b/src/Ocelot/Authorisation/ClaimValueNotAuthorisedError.cs deleted file mode 100644 index 98f8309f..00000000 --- a/src/Ocelot/Authorisation/ClaimValueNotAuthorisedError.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace Ocelot.Authorisation -{ - using Ocelot.Errors; - using System.Net; - - public class ClaimValueNotAuthorisedError : Error - { - public ClaimValueNotAuthorisedError(string message) - : base(message, OcelotErrorCode.ClaimValueNotAuthorisedError, 403) - { - } - } -} diff --git a/src/Ocelot/Authorisation/Middleware/AuthorisationMiddlewareMiddlewareExtensions.cs b/src/Ocelot/Authorisation/Middleware/AuthorisationMiddlewareMiddlewareExtensions.cs deleted file mode 100644 index 0bd1579a..00000000 --- a/src/Ocelot/Authorisation/Middleware/AuthorisationMiddlewareMiddlewareExtensions.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Ocelot.Authorisation.Middleware -{ - using Microsoft.AspNetCore.Builder; - - public static class AuthorisationMiddlewareMiddlewareExtensions - { - public static IApplicationBuilder UseAuthorisationMiddleware(this IApplicationBuilder builder) - { - return builder.UseMiddleware(); - } - } -} diff --git a/src/Ocelot/Authorisation/ScopeNotAuthorisedError.cs b/src/Ocelot/Authorisation/ScopeNotAuthorisedError.cs deleted file mode 100644 index c7f403de..00000000 --- a/src/Ocelot/Authorisation/ScopeNotAuthorisedError.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace Ocelot.Authorisation -{ - using Ocelot.Errors; - - public class ScopeNotAuthorisedError : Error - { - public ScopeNotAuthorisedError(string message) - : base(message, OcelotErrorCode.ScopeNotAuthorisedError, 403) - { - } - } -} diff --git a/src/Ocelot/Authorization/ClaimValueNotAuthorizedError.cs b/src/Ocelot/Authorization/ClaimValueNotAuthorizedError.cs new file mode 100644 index 00000000..c4d4e814 --- /dev/null +++ b/src/Ocelot/Authorization/ClaimValueNotAuthorizedError.cs @@ -0,0 +1,13 @@ +namespace Ocelot.Authorization +{ + using Ocelot.Errors; + using System.Net; + + public class ClaimValueNotAuthorizedError : Error + { + public ClaimValueNotAuthorizedError(string message) + : base(message, OcelotErrorCode.ClaimValueNotAuthorizedError, 403) + { + } + } +} diff --git a/src/Ocelot/Authorisation/ClaimsAuthoriser.cs b/src/Ocelot/Authorization/ClaimsAuthorizer.cs similarity index 86% rename from src/Ocelot/Authorisation/ClaimsAuthoriser.cs rename to src/Ocelot/Authorization/ClaimsAuthorizer.cs index d6c99440..15da73d7 100644 --- a/src/Ocelot/Authorisation/ClaimsAuthoriser.cs +++ b/src/Ocelot/Authorization/ClaimsAuthorizer.cs @@ -1,4 +1,4 @@ -namespace Ocelot.Authorisation +namespace Ocelot.Authorization { using Ocelot.Infrastructure.Claims.Parser; using Ocelot.DownstreamRouteFinder.UrlMatcher; @@ -8,16 +8,16 @@ using System.Security.Claims; using System.Text.RegularExpressions; - public class ClaimsAuthoriser : IClaimsAuthoriser + public class ClaimsAuthorizer : IClaimsAuthorizer { private readonly IClaimsParser _claimsParser; - public ClaimsAuthoriser(IClaimsParser claimsParser) + public ClaimsAuthorizer(IClaimsParser claimsParser) { _claimsParser = claimsParser; } - public Response Authorise( + public Response Authorize( ClaimsPrincipal claimsPrincipal, Dictionary routeClaimsRequirement, List urlPathPlaceholderNameAndValues @@ -45,10 +45,10 @@ { // match var actualValue = matchingPlaceholders[0].Value; - var authorised = values.Data.Contains(actualValue); - if (!authorised) + var authorized = values.Data.Contains(actualValue); + if (!authorized) { - return new ErrorResponse(new ClaimValueNotAuthorisedError( + return new ErrorResponse(new ClaimValueNotAuthorizedError( $"dynamic claim value for {variableName} of {string.Join(", ", values.Data)} is not the same as required value: {actualValue}")); } } @@ -57,12 +57,12 @@ // config error if (matchingPlaceholders.Length == 0) { - return new ErrorResponse(new ClaimValueNotAuthorisedError( + return new ErrorResponse(new ClaimValueNotAuthorizedError( $"config error: requires variable claim value: {variableName} placeholders does not contain that variable: {string.Join(", ", urlPathPlaceholderNameAndValues.Select(p => p.Name))}")); } else { - return new ErrorResponse(new ClaimValueNotAuthorisedError( + return new ErrorResponse(new ClaimValueNotAuthorizedError( $"config error: requires variable claim value: {required.Value} but placeholders are ambiguous: {string.Join(", ", urlPathPlaceholderNameAndValues.Where(p => p.Name.Equals(variableName)).Select(p => p.Value))}")); } } @@ -70,10 +70,10 @@ else { // static claim - var authorised = values.Data.Contains(required.Value); - if (!authorised) + var authorized = values.Data.Contains(required.Value); + if (!authorized) { - return new ErrorResponse(new ClaimValueNotAuthorisedError( + return new ErrorResponse(new ClaimValueNotAuthorizedError( $"claim value: {string.Join(", ", values.Data)} is not the same as required value: {required.Value} for type: {required.Key}")); } } diff --git a/src/Ocelot/Authorisation/IClaimsAuthoriser.cs b/src/Ocelot/Authorization/IClaimsAuthorizer.cs similarity index 74% rename from src/Ocelot/Authorisation/IClaimsAuthoriser.cs rename to src/Ocelot/Authorization/IClaimsAuthorizer.cs index 5e4b9c59..dc89f010 100644 --- a/src/Ocelot/Authorisation/IClaimsAuthoriser.cs +++ b/src/Ocelot/Authorization/IClaimsAuthorizer.cs @@ -2,16 +2,16 @@ using Ocelot.Responses; using System.Security.Claims; -namespace Ocelot.Authorisation +namespace Ocelot.Authorization { using System.Collections.Generic; - public interface IClaimsAuthoriser + public interface IClaimsAuthorizer { - Response Authorise( + Response Authorize( ClaimsPrincipal claimsPrincipal, Dictionary routeClaimsRequirement, - List urlPathPlaceholderNameAndValues + List urlPathPlaceholderNameAndValues ); } -} +} diff --git a/src/Ocelot/Authorisation/IScopesAuthoriser.cs b/src/Ocelot/Authorization/IScopesAuthorizer.cs similarity index 50% rename from src/Ocelot/Authorisation/IScopesAuthoriser.cs rename to src/Ocelot/Authorization/IScopesAuthorizer.cs index 57047ce7..e0041cd2 100644 --- a/src/Ocelot/Authorisation/IScopesAuthoriser.cs +++ b/src/Ocelot/Authorization/IScopesAuthorizer.cs @@ -1,12 +1,12 @@ using Ocelot.Responses; using System.Security.Claims; -namespace Ocelot.Authorisation +namespace Ocelot.Authorization { using System.Collections.Generic; - public interface IScopesAuthoriser + public interface IScopesAuthorizer { - Response Authorise(ClaimsPrincipal claimsPrincipal, List routeAllowedScopes); + Response Authorize(ClaimsPrincipal claimsPrincipal, List routeAllowedScopes); } -} +} diff --git a/src/Ocelot/Authorisation/Middleware/AuthorisationMiddleware.cs b/src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs similarity index 58% rename from src/Ocelot/Authorisation/Middleware/AuthorisationMiddleware.cs rename to src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs index 0d02c62e..3a9c5d80 100644 --- a/src/Ocelot/Authorisation/Middleware/AuthorisationMiddleware.cs +++ b/src/Ocelot/Authorization/Middleware/AuthorizationMiddleware.cs @@ -1,4 +1,4 @@ -namespace Ocelot.Authorisation.Middleware +namespace Ocelot.Authorization.Middleware { using Ocelot.Configuration; using Ocelot.Logging; @@ -8,21 +8,21 @@ using Microsoft.AspNetCore.Http; using Ocelot.DownstreamRouteFinder.Middleware; - public class AuthorisationMiddleware : OcelotMiddleware + public class AuthorizationMiddleware : OcelotMiddleware { private readonly RequestDelegate _next; - private readonly IClaimsAuthoriser _claimsAuthoriser; - private readonly IScopesAuthoriser _scopesAuthoriser; + private readonly IClaimsAuthorizer _claimsAuthorizer; + private readonly IScopesAuthorizer _scopesAuthorizer; - public AuthorisationMiddleware(RequestDelegate next, - IClaimsAuthoriser claimsAuthoriser, - IScopesAuthoriser scopesAuthoriser, + public AuthorizationMiddleware(RequestDelegate next, + IClaimsAuthorizer claimsAuthorizer, + IScopesAuthorizer scopesAuthorizer, IOcelotLoggerFactory loggerFactory) - : base(loggerFactory.CreateLogger()) + : base(loggerFactory.CreateLogger()) { _next = next; - _claimsAuthoriser = claimsAuthoriser; - _scopesAuthoriser = scopesAuthoriser; + _claimsAuthorizer = claimsAuthorizer; + _scopesAuthorizer = scopesAuthorizer; } public async Task Invoke(HttpContext httpContext) @@ -33,65 +33,65 @@ { Logger.LogInformation("route is authenticated scopes must be checked"); - var authorised = _scopesAuthoriser.Authorise(httpContext.User, downstreamRoute.AuthenticationOptions.AllowedScopes); + var authorized = _scopesAuthorizer.Authorize(httpContext.User, downstreamRoute.AuthenticationOptions.AllowedScopes); - if (authorised.IsError) + if (authorized.IsError) { - Logger.LogWarning("error authorising user scopes"); + Logger.LogWarning("error authorizing user scopes"); - httpContext.Items.UpsertErrors(authorised.Errors); + httpContext.Items.UpsertErrors(authorized.Errors); return; } - if (IsAuthorised(authorised)) + if (IsAuthorized(authorized)) { - Logger.LogInformation("user scopes is authorised calling next authorisation checks"); + Logger.LogInformation("user scopes is authorized calling next authorization checks"); } else { - Logger.LogWarning("user scopes is not authorised setting pipeline error"); + Logger.LogWarning("user scopes is not authorized setting pipeline error"); - httpContext.Items.SetError(new UnauthorisedError( + httpContext.Items.SetError(new UnauthorizedError( $"{httpContext.User.Identity.Name} unable to access {downstreamRoute.UpstreamPathTemplate.OriginalValue}")); } } - if (!IsOptionsHttpMethod(httpContext) && IsAuthorisedRoute(downstreamRoute)) + if (!IsOptionsHttpMethod(httpContext) && IsAuthorizedRoute(downstreamRoute)) { - Logger.LogInformation("route is authorised"); + Logger.LogInformation("route is authorized"); - var authorised = _claimsAuthoriser.Authorise(httpContext.User, downstreamRoute.RouteClaimsRequirement, httpContext.Items.TemplatePlaceholderNameAndValues()); + var authorized = _claimsAuthorizer.Authorize(httpContext.User, downstreamRoute.RouteClaimsRequirement, httpContext.Items.TemplatePlaceholderNameAndValues()); - if (authorised.IsError) + if (authorized.IsError) { - Logger.LogWarning($"Error whilst authorising {httpContext.User.Identity.Name}. Setting pipeline error"); + Logger.LogWarning($"Error whilst authorizing {httpContext.User.Identity.Name}. Setting pipeline error"); - httpContext.Items.UpsertErrors(authorised.Errors); + httpContext.Items.UpsertErrors(authorized.Errors); return; } - if (IsAuthorised(authorised)) + if (IsAuthorized(authorized)) { - Logger.LogInformation($"{httpContext.User.Identity.Name} has succesfully been authorised for {downstreamRoute.UpstreamPathTemplate.OriginalValue}."); + Logger.LogInformation($"{httpContext.User.Identity.Name} has succesfully been authorized for {downstreamRoute.UpstreamPathTemplate.OriginalValue}."); await _next.Invoke(httpContext); } else { - Logger.LogWarning($"{httpContext.User.Identity.Name} is not authorised to access {downstreamRoute.UpstreamPathTemplate.OriginalValue}. Setting pipeline error"); + Logger.LogWarning($"{httpContext.User.Identity.Name} is not authorized to access {downstreamRoute.UpstreamPathTemplate.OriginalValue}. Setting pipeline error"); - httpContext.Items.SetError(new UnauthorisedError($"{httpContext.User.Identity.Name} is not authorised to access {downstreamRoute.UpstreamPathTemplate.OriginalValue}")); + httpContext.Items.SetError(new UnauthorizedError($"{httpContext.User.Identity.Name} is not authorized to access {downstreamRoute.UpstreamPathTemplate.OriginalValue}")); } } else { - Logger.LogInformation($"{downstreamRoute.DownstreamPathTemplate.Value} route does not require user to be authorised"); + Logger.LogInformation($"{downstreamRoute.DownstreamPathTemplate.Value} route does not require user to be authorized"); await _next.Invoke(httpContext); } } - private static bool IsAuthorised(Response authorised) + private static bool IsAuthorized(Response authorized) { - return authorised.Data; + return authorized.Data; } private static bool IsAuthenticatedRoute(DownstreamRoute route) @@ -99,9 +99,9 @@ return route.IsAuthenticated; } - private static bool IsAuthorisedRoute(DownstreamRoute route) + private static bool IsAuthorizedRoute(DownstreamRoute route) { - return route.IsAuthorised; + return route.IsAuthorized; } private static bool IsOptionsHttpMethod(HttpContext httpContext) diff --git a/src/Ocelot/Authorization/Middleware/AuthorizationMiddlewareMiddlewareExtensions.cs b/src/Ocelot/Authorization/Middleware/AuthorizationMiddlewareMiddlewareExtensions.cs new file mode 100644 index 00000000..260cc86e --- /dev/null +++ b/src/Ocelot/Authorization/Middleware/AuthorizationMiddlewareMiddlewareExtensions.cs @@ -0,0 +1,12 @@ +namespace Ocelot.Authorization.Middleware +{ + using Microsoft.AspNetCore.Builder; + + public static class AuthorizationMiddlewareMiddlewareExtensions + { + public static IApplicationBuilder UseAuthorizationMiddleware(this IApplicationBuilder builder) + { + return builder.UseMiddleware(); + } + } +} diff --git a/src/Ocelot/Authorization/ScopeNotAuthorizedError.cs b/src/Ocelot/Authorization/ScopeNotAuthorizedError.cs new file mode 100644 index 00000000..dc5823a3 --- /dev/null +++ b/src/Ocelot/Authorization/ScopeNotAuthorizedError.cs @@ -0,0 +1,12 @@ +namespace Ocelot.Authorization +{ + using Ocelot.Errors; + + public class ScopeNotAuthorizedError : Error + { + public ScopeNotAuthorizedError(string message) + : base(message, OcelotErrorCode.ScopeNotAuthorizedError, 403) + { + } + } +} diff --git a/src/Ocelot/Authorisation/ScopesAuthoriser.cs b/src/Ocelot/Authorization/ScopesAuthorizer.cs similarity index 78% rename from src/Ocelot/Authorisation/ScopesAuthoriser.cs rename to src/Ocelot/Authorization/ScopesAuthorizer.cs index 8344d80b..7fd7e2aa 100644 --- a/src/Ocelot/Authorisation/ScopesAuthoriser.cs +++ b/src/Ocelot/Authorization/ScopesAuthorizer.cs @@ -1,47 +1,47 @@ -using Ocelot.Responses; -using System.Collections.Generic; -using System.Linq; -using System.Security.Claims; - -namespace Ocelot.Authorisation -{ - using Infrastructure.Claims.Parser; - - public class ScopesAuthoriser : IScopesAuthoriser - { - private readonly IClaimsParser _claimsParser; - private readonly string _scope = "scope"; - - public ScopesAuthoriser(IClaimsParser claimsParser) - { - _claimsParser = claimsParser; - } - - public Response Authorise(ClaimsPrincipal claimsPrincipal, List routeAllowedScopes) - { - if (routeAllowedScopes == null || routeAllowedScopes.Count == 0) - { - return new OkResponse(true); - } - - var values = _claimsParser.GetValuesByClaimType(claimsPrincipal.Claims, _scope); - - if (values.IsError) - { - return new ErrorResponse(values.Errors); - } - - var userScopes = values.Data; - - var matchesScopes = routeAllowedScopes.Intersect(userScopes).ToList(); - - if (matchesScopes.Count == 0) - { - return new ErrorResponse( - new ScopeNotAuthorisedError($"no one user scope: '{string.Join(",", userScopes)}' match with some allowed scope: '{string.Join(",", routeAllowedScopes)}'")); - } - - return new OkResponse(true); - } - } -} +using Ocelot.Responses; +using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; + +namespace Ocelot.Authorization +{ + using Infrastructure.Claims.Parser; + + public class ScopesAuthorizer : IScopesAuthorizer + { + private readonly IClaimsParser _claimsParser; + private readonly string _scope = "scope"; + + public ScopesAuthorizer(IClaimsParser claimsParser) + { + _claimsParser = claimsParser; + } + + public Response Authorize(ClaimsPrincipal claimsPrincipal, List routeAllowedScopes) + { + if (routeAllowedScopes == null || routeAllowedScopes.Count == 0) + { + return new OkResponse(true); + } + + var values = _claimsParser.GetValuesByClaimType(claimsPrincipal.Claims, _scope); + + if (values.IsError) + { + return new ErrorResponse(values.Errors); + } + + var userScopes = values.Data; + + var matchesScopes = routeAllowedScopes.Intersect(userScopes).ToList(); + + if (matchesScopes.Count == 0) + { + return new ErrorResponse( + new ScopeNotAuthorizedError($"no one user scope: '{string.Join(",", userScopes)}' match with some allowed scope: '{string.Join(",", routeAllowedScopes)}'")); + } + + return new OkResponse(true); + } + } +} diff --git a/src/Ocelot/Authorisation/UnauthorisedError.cs b/src/Ocelot/Authorization/UnauthorizedError.cs similarity index 50% rename from src/Ocelot/Authorisation/UnauthorisedError.cs rename to src/Ocelot/Authorization/UnauthorizedError.cs index fc32ea83..689f9e2f 100644 --- a/src/Ocelot/Authorisation/UnauthorisedError.cs +++ b/src/Ocelot/Authorization/UnauthorizedError.cs @@ -1,10 +1,10 @@ -namespace Ocelot.Authorisation +namespace Ocelot.Authorization { using Ocelot.Errors; - public class UnauthorisedError : Error + public class UnauthorizedError : Error { - public UnauthorisedError(string message) + public UnauthorizedError(string message) : base(message, OcelotErrorCode.UnauthorizedError, 403) { } diff --git a/src/Ocelot/Authorisation/UserDoesNotHaveClaimError.cs b/src/Ocelot/Authorization/UserDoesNotHaveClaimError.cs similarity index 84% rename from src/Ocelot/Authorisation/UserDoesNotHaveClaimError.cs rename to src/Ocelot/Authorization/UserDoesNotHaveClaimError.cs index 6f9aa3eb..08c19d9f 100644 --- a/src/Ocelot/Authorisation/UserDoesNotHaveClaimError.cs +++ b/src/Ocelot/Authorization/UserDoesNotHaveClaimError.cs @@ -1,12 +1,12 @@ -namespace Ocelot.Authorisation -{ +namespace Ocelot.Authorization +{ using Ocelot.Errors; public class UserDoesNotHaveClaimError : Error { - public UserDoesNotHaveClaimError(string message) + public UserDoesNotHaveClaimError(string message) : base(message, OcelotErrorCode.UserDoesNotHaveClaimError, 403) { } } -} +} diff --git a/src/Ocelot/Configuration/Builder/DownstreamReRouteBuilder.cs b/src/Ocelot/Configuration/Builder/DownstreamReRouteBuilder.cs index b51c33db..5ee5ddf7 100644 --- a/src/Ocelot/Configuration/Builder/DownstreamReRouteBuilder.cs +++ b/src/Ocelot/Configuration/Builder/DownstreamReRouteBuilder.cs @@ -18,7 +18,7 @@ namespace Ocelot.Configuration.Builder private List _claimsToHeaders; private List _claimToClaims; private Dictionary _routeClaimRequirement; - private bool _isAuthorised; + private bool _isAuthorized; private List _claimToQueries; private List _claimToDownstreamPath; private string _requestIdHeaderKey; @@ -101,9 +101,9 @@ namespace Ocelot.Configuration.Builder return this; } - public DownstreamRouteBuilder WithIsAuthorised(bool input) + public DownstreamRouteBuilder WithIsAuthorized(bool input) { - _isAuthorised = input; + _isAuthorized = input; return this; } @@ -289,7 +289,7 @@ namespace Ocelot.Configuration.Builder _claimToClaims, _claimToDownstreamPath, _isAuthenticated, - _isAuthorised, + _isAuthorized, _authenticationOptions, new DownstreamPathTemplate(_downstreamPathTemplate), _loadBalancerKey, diff --git a/src/Ocelot/Configuration/Builder/RouteOptionsBuilder.cs b/src/Ocelot/Configuration/Builder/RouteOptionsBuilder.cs index ef1cdcd3..7906dad3 100644 --- a/src/Ocelot/Configuration/Builder/RouteOptionsBuilder.cs +++ b/src/Ocelot/Configuration/Builder/RouteOptionsBuilder.cs @@ -3,7 +3,7 @@ namespace Ocelot.Configuration.Builder public class RouteOptionsBuilder { private bool _isAuthenticated; - private bool _isAuthorised; + private bool _isAuthorized; private bool _isCached; private bool _enableRateLimiting; private bool _useServiceDiscovery; @@ -20,9 +20,9 @@ namespace Ocelot.Configuration.Builder return this; } - public RouteOptionsBuilder WithIsAuthorised(bool isAuthorised) + public RouteOptionsBuilder WithIsAuthorized(bool isAuthorized) { - _isAuthorised = isAuthorised; + _isAuthorized = isAuthorized; return this; } @@ -40,7 +40,7 @@ namespace Ocelot.Configuration.Builder public RouteOptions Build() { - return new RouteOptions(_isAuthenticated, _isAuthorised, _isCached, _enableRateLimiting, _useServiceDiscovery); + return new RouteOptions(_isAuthenticated, _isAuthorized, _isCached, _enableRateLimiting, _useServiceDiscovery); } } } diff --git a/src/Ocelot/Configuration/Creator/RouteOptionsCreator.cs b/src/Ocelot/Configuration/Creator/RouteOptionsCreator.cs index 506bd32a..703cb71f 100644 --- a/src/Ocelot/Configuration/Creator/RouteOptionsCreator.cs +++ b/src/Ocelot/Configuration/Creator/RouteOptionsCreator.cs @@ -1,6 +1,6 @@ namespace Ocelot.Configuration.Creator -{ - using Ocelot.Configuration.Builder; +{ + using Ocelot.Configuration.Builder; using Ocelot.Configuration.File; public class RouteOptionsCreator : IRouteOptionsCreator @@ -8,14 +8,14 @@ namespace Ocelot.Configuration.Creator public RouteOptions Create(FileRoute fileRoute) { var isAuthenticated = IsAuthenticated(fileRoute); - var isAuthorised = IsAuthorised(fileRoute); + var isAuthorized = IsAuthorized(fileRoute); var isCached = IsCached(fileRoute); var enableRateLimiting = IsEnableRateLimiting(fileRoute); var useServiceDiscovery = !string.IsNullOrEmpty(fileRoute.ServiceName); var options = new RouteOptionsBuilder() .WithIsAuthenticated(isAuthenticated) - .WithIsAuthorised(isAuthorised) + .WithIsAuthorized(isAuthorized) .WithIsCached(isCached) .WithRateLimiting(enableRateLimiting) .WithUseServiceDiscovery(useServiceDiscovery) @@ -34,7 +34,7 @@ namespace Ocelot.Configuration.Creator return !string.IsNullOrEmpty(fileRoute.AuthenticationOptions?.AuthenticationProviderKey); } - private bool IsAuthorised(FileRoute fileRoute) + private bool IsAuthorized(FileRoute fileRoute) { return fileRoute.RouteClaimsRequirement?.Count > 0; } diff --git a/src/Ocelot/Configuration/Creator/RoutesCreator.cs b/src/Ocelot/Configuration/Creator/RoutesCreator.cs index a5b34862..48845ce0 100644 --- a/src/Ocelot/Configuration/Creator/RoutesCreator.cs +++ b/src/Ocelot/Configuration/Creator/RoutesCreator.cs @@ -119,7 +119,7 @@ namespace Ocelot.Configuration.Creator .WithClaimsToHeaders(claimsToHeaders) .WithClaimsToClaims(claimsToClaims) .WithRouteClaimsRequirement(fileRoute.RouteClaimsRequirement) - .WithIsAuthorised(fileRouteOptions.IsAuthorised) + .WithIsAuthorized(fileRouteOptions.IsAuthorized) .WithClaimsToQueries(claimsToQueries) .WithClaimsToDownstreamPath(claimsToDownstreamPath) .WithRequestIdKey(requestIdKey) diff --git a/src/Ocelot/Configuration/DownstreamRoute.cs b/src/Ocelot/Configuration/DownstreamRoute.cs index 8dd9f30d..b2bde0ed 100644 --- a/src/Ocelot/Configuration/DownstreamRoute.cs +++ b/src/Ocelot/Configuration/DownstreamRoute.cs @@ -31,7 +31,7 @@ namespace Ocelot.Configuration List claimsToClaims, List claimsToPath, bool isAuthenticated, - bool isAuthorised, + bool isAuthorized, AuthenticationOptions authenticationOptions, DownstreamPathTemplate downstreamPathTemplate, string loadBalancerKey, @@ -69,7 +69,7 @@ namespace Ocelot.Configuration ClaimsToClaims = claimsToClaims ?? new List(); ClaimsToPath = claimsToPath ?? new List(); IsAuthenticated = isAuthenticated; - IsAuthorised = isAuthorised; + IsAuthorized = isAuthorized; AuthenticationOptions = authenticationOptions; DownstreamPathTemplate = downstreamPathTemplate; LoadBalancerKey = loadBalancerKey; @@ -102,7 +102,7 @@ namespace Ocelot.Configuration public List ClaimsToClaims { get; } public List ClaimsToPath { get; } public bool IsAuthenticated { get; } - public bool IsAuthorised { get; } + public bool IsAuthorized { get; } public AuthenticationOptions AuthenticationOptions { get; } public DownstreamPathTemplate DownstreamPathTemplate { get; } public string LoadBalancerKey { get; } diff --git a/src/Ocelot/Configuration/RouteOptions.cs b/src/Ocelot/Configuration/RouteOptions.cs index 9b5ba8d9..41123598 100644 --- a/src/Ocelot/Configuration/RouteOptions.cs +++ b/src/Ocelot/Configuration/RouteOptions.cs @@ -2,17 +2,17 @@ namespace Ocelot.Configuration { public class RouteOptions { - public RouteOptions(bool isAuthenticated, bool isAuthorised, bool isCached, bool isEnableRateLimiting, bool useServiceDiscovery) + public RouteOptions(bool isAuthenticated, bool isAuthorized, bool isCached, bool isEnableRateLimiting, bool useServiceDiscovery) { IsAuthenticated = isAuthenticated; - IsAuthorised = isAuthorised; + IsAuthorized = isAuthorized; IsCached = isCached; EnableRateLimiting = isEnableRateLimiting; UseServiceDiscovery = useServiceDiscovery; } public bool IsAuthenticated { get; private set; } - public bool IsAuthorised { get; private set; } + public bool IsAuthorized { get; private set; } public bool IsCached { get; private set; } public bool EnableRateLimiting { get; private set; } public bool UseServiceDiscovery { get; private set; } diff --git a/src/Ocelot/DependencyInjection/OcelotBuilder.cs b/src/Ocelot/DependencyInjection/OcelotBuilder.cs index f4fbf844..20c4e4bb 100644 --- a/src/Ocelot/DependencyInjection/OcelotBuilder.cs +++ b/src/Ocelot/DependencyInjection/OcelotBuilder.cs @@ -5,7 +5,7 @@ namespace Ocelot.DependencyInjection using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; - using Ocelot.Authorisation; + using Ocelot.Authorization; using Ocelot.Cache; using Ocelot.Claims; using Ocelot.Configuration; @@ -96,8 +96,8 @@ namespace Ocelot.DependencyInjection Services.TryAddSingleton(); Services.TryAddSingleton(); Services.TryAddSingleton(); - Services.TryAddSingleton(); - Services.TryAddSingleton(); + Services.TryAddSingleton(); + Services.TryAddSingleton(); Services.TryAddSingleton(); Services.TryAddSingleton(); Services.TryAddSingleton(); diff --git a/src/Ocelot/Errors/OcelotErrorCode.cs b/src/Ocelot/Errors/OcelotErrorCode.cs index 46864181..9063e714 100644 --- a/src/Ocelot/Errors/OcelotErrorCode.cs +++ b/src/Ocelot/Errors/OcelotErrorCode.cs @@ -16,8 +16,8 @@ NoInstructionsError = 11, InstructionNotForClaimsError = 12, UnauthorizedError = 13, - ClaimValueNotAuthorisedError = 14, - ScopeNotAuthorisedError = 15, + ClaimValueNotAuthorizedError = 14, + ScopeNotAuthorizedError = 15, UserDoesNotHaveClaimError = 16, DownstreamPathTemplateContainsSchemeError = 17, DownstreamPathNullOrEmptyError = 18, diff --git a/src/Ocelot/Middleware/OcelotPipelineConfiguration.cs b/src/Ocelot/Middleware/OcelotPipelineConfiguration.cs index b1f1bf99..f24efa2d 100644 --- a/src/Ocelot/Middleware/OcelotPipelineConfiguration.cs +++ b/src/Ocelot/Middleware/OcelotPipelineConfiguration.cs @@ -39,22 +39,22 @@ public Func, Task> AuthenticationMiddleware { get; set; } /// - /// This is to allow the user to run any extra authorisation before the Ocelot authentication + /// This is to allow the user to run any extra authorization before the Ocelot authentication /// kicks in /// /// - /// This is to allow the user to run any extra authorisation before the Ocelot authentication + /// This is to allow the user to run any extra authorization before the Ocelot authentication /// kicks in /// - public Func, Task> PreAuthorisationMiddleware { get; set; } + public Func, Task> PreAuthorizationMiddleware { get; set; } /// - /// This allows the user to completely override the ocelot authorisation middleware + /// This allows the user to completely override the ocelot authorization middleware /// /// - /// This allows the user to completely override the ocelot authorisation middleware + /// This allows the user to completely override the ocelot authorization middleware /// - public Func, Task> AuthorisationMiddleware { get; set; } + public Func, Task> AuthorizationMiddleware { get; set; } /// /// This allows the user to implement there own query string manipulation logic diff --git a/src/Ocelot/Middleware/OcelotPipelineExtensions.cs b/src/Ocelot/Middleware/OcelotPipelineExtensions.cs index 6158c72b..58ab855d 100644 --- a/src/Ocelot/Middleware/OcelotPipelineExtensions.cs +++ b/src/Ocelot/Middleware/OcelotPipelineExtensions.cs @@ -8,7 +8,7 @@ using Ocelot.Responder.Middleware; using Ocelot.Security.Middleware; using Ocelot.Authentication.Middleware; - using Ocelot.Authorisation.Middleware; + using Ocelot.Authorization.Middleware; using Ocelot.Cache.Middleware; using Ocelot.Claims.Middleware; using Ocelot.DownstreamRouteFinder.Middleware; @@ -102,23 +102,23 @@ app.Use(pipelineConfiguration.AuthenticationMiddleware); } - // The next thing we do is look at any claims transforms in case this is important for authorisation + // The next thing we do is look at any claims transforms in case this is important for authorization app.UseClaimsToClaimsMiddleware(); - // Allow pre authorisation logic. The idea being people might want to run something custom before what is built in. - app.UseIfNotNull(pipelineConfiguration.PreAuthorisationMiddleware); + // Allow pre authorization logic. The idea being people might want to run something custom before what is built in. + app.UseIfNotNull(pipelineConfiguration.PreAuthorizationMiddleware); // Now we have authenticated and done any claims transformation we - // can authorise the request + // can authorize the request // We allow the ocelot middleware to be overriden by whatever the // user wants - if (pipelineConfiguration.AuthorisationMiddleware == null) + if (pipelineConfiguration.AuthorizationMiddleware == null) { - app.UseAuthorisationMiddleware(); + app.UseAuthorizationMiddleware(); } else { - app.Use(pipelineConfiguration.AuthorisationMiddleware); + app.Use(pipelineConfiguration.AuthorizationMiddleware); } // Now we can run the claims to headers transformation middleware diff --git a/src/Ocelot/Responder/ErrorsToHttpStatusCodeMapper.cs b/src/Ocelot/Responder/ErrorsToHttpStatusCodeMapper.cs index 39b5e749..0f74a7ad 100644 --- a/src/Ocelot/Responder/ErrorsToHttpStatusCodeMapper.cs +++ b/src/Ocelot/Responder/ErrorsToHttpStatusCodeMapper.cs @@ -14,8 +14,8 @@ namespace Ocelot.Responder } if (errors.Any(e => e.Code == OcelotErrorCode.UnauthorizedError - || e.Code == OcelotErrorCode.ClaimValueNotAuthorisedError - || e.Code == OcelotErrorCode.ScopeNotAuthorisedError + || e.Code == OcelotErrorCode.ClaimValueNotAuthorizedError + || e.Code == OcelotErrorCode.ScopeNotAuthorizedError || e.Code == OcelotErrorCode.UserDoesNotHaveClaimError || e.Code == OcelotErrorCode.CannotFindClaimError)) { diff --git a/test/Ocelot.AcceptanceTests/AuthorisationTests.cs b/test/Ocelot.AcceptanceTests/AuthorizationTests.cs similarity index 98% rename from test/Ocelot.AcceptanceTests/AuthorisationTests.cs rename to test/Ocelot.AcceptanceTests/AuthorizationTests.cs index 9a9a3dd4..394c76bc 100644 --- a/test/Ocelot.AcceptanceTests/AuthorisationTests.cs +++ b/test/Ocelot.AcceptanceTests/AuthorizationTests.cs @@ -16,7 +16,7 @@ namespace Ocelot.AcceptanceTests using TestStack.BDDfy; using Xunit; - public class AuthorisationTests : IDisposable + public class AuthorizationTests : IDisposable { private IWebHost _identityServerBuilder; private readonly Steps _steps; @@ -24,7 +24,7 @@ namespace Ocelot.AcceptanceTests private string _identityServerRootUrl; private readonly ServiceHandler _serviceHandler; - public AuthorisationTests() + public AuthorizationTests() { _serviceHandler = new ServiceHandler(); _steps = new Steps(); @@ -41,7 +41,7 @@ namespace Ocelot.AcceptanceTests } [Fact] - public void should_return_response_200_authorising_route() + public void should_return_response_200_authorizing_route() { int port = RandomPortFinder.GetRandomPort(); @@ -101,7 +101,7 @@ namespace Ocelot.AcceptanceTests } [Fact] - public void should_return_response_403_authorising_route() + public void should_return_response_403_authorizing_route() { int port = RandomPortFinder.GetRandomPort(); diff --git a/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs b/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs index f420af6a..e155010d 100644 --- a/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs +++ b/test/Ocelot.AcceptanceTests/CustomMiddlewareTests.cs @@ -10,7 +10,7 @@ using System.Net; using System.Threading.Tasks; using TestStack.BDDfy; - using Xunit; + using Xunit; public class CustomMiddlewareTests : IDisposable { @@ -32,13 +32,13 @@ { var configuration = new OcelotPipelineConfiguration { - AuthorisationMiddleware = async (ctx, next) => + AuthorizationMiddleware = async (ctx, next) => { _counter++; await next.Invoke(); } - }; - + }; + var port = RandomPortFinder.GetRandomPort(); var fileConfiguration = new FileConfiguration @@ -73,17 +73,17 @@ } [Fact] - public void should_call_authorisation_middleware() + public void should_call_authorization_middleware() { var configuration = new OcelotPipelineConfiguration { - AuthorisationMiddleware = async (ctx, next) => + AuthorizationMiddleware = async (ctx, next) => { _counter++; await next.Invoke(); } - }; - + }; + var port = RandomPortFinder.GetRandomPort(); var fileConfiguration = new FileConfiguration @@ -127,8 +127,8 @@ _counter++; await next.Invoke(); } - }; - + }; + var port = RandomPortFinder.GetRandomPort(); var fileConfiguration = new FileConfiguration @@ -172,8 +172,8 @@ _counter++; await next.Invoke(); } - }; - + }; + var port = RandomPortFinder.GetRandomPort(); var fileConfiguration = new FileConfiguration @@ -208,17 +208,17 @@ } [Fact] - public void should_call_pre_authorisation_middleware() + public void should_call_pre_authorization_middleware() { var configuration = new OcelotPipelineConfiguration { - PreAuthorisationMiddleware = async (ctx, next) => + PreAuthorizationMiddleware = async (ctx, next) => { _counter++; await next.Invoke(); } - }; - + }; + var port = RandomPortFinder.GetRandomPort(); var fileConfiguration = new FileConfiguration @@ -262,8 +262,8 @@ _counter++; await next.Invoke(); } - }; - + }; + var port = RandomPortFinder.GetRandomPort(); var fileConfiguration = new FileConfiguration @@ -295,8 +295,8 @@ .Then(x => _steps.ThenTheStatusCodeShouldBe(HttpStatusCode.OK)) .And(x => x.ThenTheCounterIs(1)) .BDDfy(); - } - + } + [Fact(Skip = "This is just an example to show how you could hook into Ocelot pipeline with your own middleware. At the moment you must use Response.OnCompleted callback and cannot change the response :( I will see if this can be changed one day!")] public void should_fix_issue_237() { @@ -305,14 +305,14 @@ var httpContext = (HttpContext)state; if (httpContext.Response.StatusCode > 400) - { + { Debug.WriteLine("COUNT CALLED"); Console.WriteLine("COUNT CALLED"); } return Task.CompletedTask; - }; - + }; + var port = RandomPortFinder.GetRandomPort(); var fileConfiguration = new FileConfiguration @@ -376,8 +376,8 @@ public class FakeMiddleware { private readonly RequestDelegate _next; - private readonly Func _callback; - + private readonly Func _callback; + public FakeMiddleware(RequestDelegate next, Func callback) { _next = next; @@ -386,10 +386,10 @@ public async Task Invoke(HttpContext context) { - await _next(context); - + await _next(context); + context.Response.OnCompleted(_callback, context); } } } -} +} diff --git a/test/Ocelot.UnitTests/Authorization/AuthorisationMiddlewareTests.cs b/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs similarity index 78% rename from test/Ocelot.UnitTests/Authorization/AuthorisationMiddlewareTests.cs rename to test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs index 4c72849e..f1b14b0a 100644 --- a/test/Ocelot.UnitTests/Authorization/AuthorisationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Authorization/AuthorizationMiddlewareTests.cs @@ -3,8 +3,8 @@ namespace Ocelot.UnitTests.Authorization { using Microsoft.AspNetCore.Http; using Moq; - using Ocelot.Authorisation; - using Ocelot.Authorisation.Middleware; + using Ocelot.Authorization; + using Ocelot.Authorization.Middleware; using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.DownstreamRouteFinder.Middleware; @@ -18,35 +18,35 @@ namespace Ocelot.UnitTests.Authorization using TestStack.BDDfy; using Xunit; - public class AuthorisationMiddlewareTests + public class AuthorizationMiddlewareTests { - private readonly Mock _authService; - private readonly Mock _authScopesService; + private readonly Mock _authService; + private readonly Mock _authScopesService; private Mock _loggerFactory; private Mock _logger; - private readonly AuthorisationMiddleware _middleware; + private readonly AuthorizationMiddleware _middleware; private RequestDelegate _next; private HttpContext _httpContext; - public AuthorisationMiddlewareTests() + public AuthorizationMiddlewareTests() { _httpContext = new DefaultHttpContext(); - _authService = new Mock(); - _authScopesService = new Mock(); + _authService = new Mock(); + _authScopesService = new Mock(); _loggerFactory = new Mock(); _logger = new Mock(); - _loggerFactory.Setup(x => x.CreateLogger()).Returns(_logger.Object); + _loggerFactory.Setup(x => x.CreateLogger()).Returns(_logger.Object); _next = context => Task.CompletedTask; - _middleware = new AuthorisationMiddleware(_next, _authService.Object, _authScopesService.Object, _loggerFactory.Object); + _middleware = new AuthorizationMiddleware(_next, _authService.Object, _authScopesService.Object, _loggerFactory.Object); } [Fact] - public void should_call_authorisation_service() + public void should_call_authorization_service() { this.Given(x => x.GivenTheDownStreamRouteIs(new List(), new DownstreamRouteBuilder() .WithUpstreamPathTemplate(new UpstreamPathTemplateBuilder().Build()) - .WithIsAuthorised(true) + .WithIsAuthorized(true) .WithUpstreamHttpMethod(new List { "Get" }) .Build())) .And(x => x.GivenTheAuthServiceReturns(new OkResponse(true))) @@ -69,7 +69,7 @@ namespace Ocelot.UnitTests.Authorization private void GivenTheAuthServiceReturns(Response expected) { _authService - .Setup(x => x.Authorise( + .Setup(x => x.Authorize( It.IsAny(), It.IsAny>(), It.IsAny>())) @@ -79,7 +79,7 @@ namespace Ocelot.UnitTests.Authorization private void ThenTheAuthServiceIsCalledCorrectly() { _authService - .Verify(x => x.Authorise( + .Verify(x => x.Authorize( It.IsAny(), It.IsAny>(), It.IsAny>()) diff --git a/test/Ocelot.UnitTests/Authorization/ClaimsAuthoriserTests.cs b/test/Ocelot.UnitTests/Authorization/ClaimsAuthorizerTests.cs similarity index 75% rename from test/Ocelot.UnitTests/Authorization/ClaimsAuthoriserTests.cs rename to test/Ocelot.UnitTests/Authorization/ClaimsAuthorizerTests.cs index b22e7ffc..34ed4afa 100644 --- a/test/Ocelot.UnitTests/Authorization/ClaimsAuthoriserTests.cs +++ b/test/Ocelot.UnitTests/Authorization/ClaimsAuthorizerTests.cs @@ -1,4 +1,4 @@ -using Ocelot.Authorisation; +using Ocelot.Authorization; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.Responses; using Shouldly; @@ -11,21 +11,21 @@ namespace Ocelot.UnitTests.Authorization { using Ocelot.Infrastructure.Claims.Parser; - public class ClaimsAuthoriserTests + public class ClaimsAuthorizerTests { - private readonly ClaimsAuthoriser _claimsAuthoriser; + private readonly ClaimsAuthorizer _claimsAuthorizer; private ClaimsPrincipal _claimsPrincipal; private Dictionary _requirement; private List _urlPathPlaceholderNameAndValues; private Response _result; - public ClaimsAuthoriserTests() + public ClaimsAuthorizerTests() { - _claimsAuthoriser = new ClaimsAuthoriser(new ClaimsParser()); + _claimsAuthorizer = new ClaimsAuthorizer(new ClaimsParser()); } [Fact] - public void should_authorise_user() + public void should_authorize_user() { this.Given(x => x.GivenAClaimsPrincipal(new ClaimsPrincipal(new ClaimsIdentity(new List { @@ -35,8 +35,8 @@ namespace Ocelot.UnitTests.Authorization { {"UserType", "registered"} })) - .When(x => x.WhenICallTheAuthoriser()) - .Then(x => x.ThenTheUserIsAuthorised()) + .When(x => x.WhenICallTheAuthorizer()) + .Then(x => x.ThenTheUserIsAuthorized()) .BDDfy(); } @@ -55,8 +55,8 @@ namespace Ocelot.UnitTests.Authorization { new PlaceholderNameAndValue("{userId}", "14") })) - .When(x => x.WhenICallTheAuthoriser()) - .Then(x => x.ThenTheUserIsAuthorised()) + .When(x => x.WhenICallTheAuthorizer()) + .Then(x => x.ThenTheUserIsAuthorized()) .BDDfy(); } @@ -75,13 +75,13 @@ namespace Ocelot.UnitTests.Authorization { new PlaceholderNameAndValue("{userId}", "14") })) - .When(x => x.WhenICallTheAuthoriser()) - .Then(x => x.ThenTheUserIsntAuthorised()) + .When(x => x.WhenICallTheAuthorizer()) + .Then(x => x.ThenTheUserIsntAuthorized()) .BDDfy(); - } + } [Fact] - public void should_authorise_user_multiple_claims_of_same_type() + public void should_authorize_user_multiple_claims_of_same_type() { this.Given(x => x.GivenAClaimsPrincipal(new ClaimsPrincipal(new ClaimsIdentity(new List { @@ -92,21 +92,21 @@ namespace Ocelot.UnitTests.Authorization { {"UserType", "registered"} })) - .When(x => x.WhenICallTheAuthoriser()) - .Then(x => x.ThenTheUserIsAuthorised()) + .When(x => x.WhenICallTheAuthorizer()) + .Then(x => x.ThenTheUserIsAuthorized()) .BDDfy(); } [Fact] - public void should_not_authorise_user() + public void should_not_authorize_user() { this.Given(x => x.GivenAClaimsPrincipal(new ClaimsPrincipal(new ClaimsIdentity(new List())))) .And(x => x.GivenARouteClaimsRequirement(new Dictionary { { "UserType", "registered" } })) - .When(x => x.WhenICallTheAuthoriser()) - .Then(x => x.ThenTheUserIsntAuthorised()) + .When(x => x.WhenICallTheAuthorizer()) + .Then(x => x.ThenTheUserIsntAuthorized()) .BDDfy(); } @@ -125,19 +125,19 @@ namespace Ocelot.UnitTests.Authorization _urlPathPlaceholderNameAndValues = urlPathPlaceholderNameAndValues; } - private void WhenICallTheAuthoriser() + private void WhenICallTheAuthorizer() { - _result = _claimsAuthoriser.Authorise(_claimsPrincipal, _requirement, _urlPathPlaceholderNameAndValues); + _result = _claimsAuthorizer.Authorize(_claimsPrincipal, _requirement, _urlPathPlaceholderNameAndValues); } - private void ThenTheUserIsAuthorised() + private void ThenTheUserIsAuthorized() { _result.Data.ShouldBe(true); } - private void ThenTheUserIsntAuthorised() + private void ThenTheUserIsntAuthorized() { _result.Data.ShouldBe(false); } } -} +} diff --git a/test/Ocelot.UnitTests/Configuration/RouteOptionsCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RouteOptionsCreatorTests.cs index c5e0d75e..c450abf5 100644 --- a/test/Ocelot.UnitTests/Configuration/RouteOptionsCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RouteOptionsCreatorTests.cs @@ -46,7 +46,7 @@ namespace Ocelot.UnitTests.Configuration var expected = new RouteOptionsBuilder() .WithIsAuthenticated(true) - .WithIsAuthorised(true) + .WithIsAuthorized(true) .WithIsCached(true) .WithRateLimiting(true) .WithUseServiceDiscovery(true) @@ -71,7 +71,7 @@ namespace Ocelot.UnitTests.Configuration private void ThenTheFollowingIsReturned(RouteOptions expected) { _result.IsAuthenticated.ShouldBe(expected.IsAuthenticated); - _result.IsAuthorised.ShouldBe(expected.IsAuthorised); + _result.IsAuthorized.ShouldBe(expected.IsAuthorized); _result.IsCached.ShouldBe(expected.IsCached); _result.EnableRateLimiting.ShouldBe(expected.EnableRateLimiting); _result.UseServiceDiscovery.ShouldBe(expected.UseServiceDiscovery); diff --git a/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs b/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs index 81500e51..1e168cff 100644 --- a/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs +++ b/test/Ocelot.UnitTests/Configuration/RoutesCreatorTests.cs @@ -218,7 +218,7 @@ { _result[routeIndex].DownstreamRoute[0].DownstreamHttpVersion.ShouldBe(_expectedVersion); _result[routeIndex].DownstreamRoute[0].IsAuthenticated.ShouldBe(_rro.IsAuthenticated); - _result[routeIndex].DownstreamRoute[0].IsAuthorised.ShouldBe(_rro.IsAuthorised); + _result[routeIndex].DownstreamRoute[0].IsAuthorized.ShouldBe(_rro.IsAuthorized); _result[routeIndex].DownstreamRoute[0].IsCached.ShouldBe(_rro.IsCached); _result[routeIndex].DownstreamRoute[0].EnableEndpointEndpointRateLimiting.ShouldBe(_rro.EnableRateLimiting); _result[routeIndex].DownstreamRoute[0].RequestIdKey.ShouldBe(_requestId); diff --git a/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs b/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs index 65aaf096..788b4cc1 100644 --- a/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs +++ b/test/Ocelot.UnitTests/Headers/HttpHeadersTransformationMiddlewareTests.cs @@ -2,7 +2,7 @@ namespace Ocelot.UnitTests.Headers { using Microsoft.AspNetCore.Http; using Moq; - using Ocelot.Authorisation.Middleware; + using Ocelot.Authorization.Middleware; using Ocelot.Configuration; using Ocelot.Configuration.Builder; using Ocelot.DownstreamRouteFinder; @@ -38,7 +38,7 @@ namespace Ocelot.UnitTests.Headers _postReplacer = new Mock(); _loggerFactory = new Mock(); _logger = new Mock(); - _loggerFactory.Setup(x => x.CreateLogger()).Returns(_logger.Object); + _loggerFactory.Setup(x => x.CreateLogger()).Returns(_logger.Object); _next = context => Task.CompletedTask; _addHeadersToResponse = new Mock(); _addHeadersToRequest = new Mock(); diff --git a/test/Ocelot.UnitTests/Infrastructure/ScopesAuthoriserTests.cs b/test/Ocelot.UnitTests/Infrastructure/ScopesAuthorizerTests.cs similarity index 87% rename from test/Ocelot.UnitTests/Infrastructure/ScopesAuthoriserTests.cs rename to test/Ocelot.UnitTests/Infrastructure/ScopesAuthorizerTests.cs index 08aa78a1..ccc17f19 100644 --- a/test/Ocelot.UnitTests/Infrastructure/ScopesAuthoriserTests.cs +++ b/test/Ocelot.UnitTests/Infrastructure/ScopesAuthorizerTests.cs @@ -1,5 +1,5 @@ using Moq; -using Ocelot.Authorisation; +using Ocelot.Authorization; using Ocelot.Errors; using Ocelot.Infrastructure.Claims.Parser; using Ocelot.Responses; @@ -11,18 +11,18 @@ using Xunit; namespace Ocelot.UnitTests.Infrastructure { - public class ScopesAuthoriserTests + public class ScopesAuthorizerTests { - private ScopesAuthoriser _authoriser; + private ScopesAuthorizer _authorizer; public Mock _parser; private ClaimsPrincipal _principal; private List _allowedScopes; private Response _result; - public ScopesAuthoriserTests() + public ScopesAuthorizerTests() { _parser = new Mock(); - _authoriser = new ScopesAuthoriser(_parser.Object); + _authorizer = new ScopesAuthorizer(_parser.Object); } [Fact] @@ -30,7 +30,7 @@ namespace Ocelot.UnitTests.Infrastructure { this.Given(_ => GivenTheFollowing(new ClaimsPrincipal())) .And(_ => GivenTheFollowing(new List())) - .When(_ => WhenIAuthorise()) + .When(_ => WhenIAuthorize()) .Then(_ => ThenTheFollowingIsReturned(new OkResponse(true))) .BDDfy(); } @@ -40,7 +40,7 @@ namespace Ocelot.UnitTests.Infrastructure { this.Given(_ => GivenTheFollowing(new ClaimsPrincipal())) .And(_ => GivenTheFollowing((List)null)) - .When(_ => WhenIAuthorise()) + .When(_ => WhenIAuthorize()) .Then(_ => ThenTheFollowingIsReturned(new OkResponse(true))) .BDDfy(); } @@ -52,7 +52,7 @@ namespace Ocelot.UnitTests.Infrastructure this.Given(_ => GivenTheFollowing(new ClaimsPrincipal())) .And(_ => GivenTheParserReturns(new ErrorResponse>(fakeError))) .And(_ => GivenTheFollowing(new List() { "doesntmatter" })) - .When(_ => WhenIAuthorise()) + .When(_ => WhenIAuthorize()) .Then(_ => ThenTheFollowingIsReturned(new ErrorResponse(fakeError))) .BDDfy(); } @@ -66,7 +66,7 @@ namespace Ocelot.UnitTests.Infrastructure this.Given(_ => GivenTheFollowing(claimsPrincipal)) .And(_ => GivenTheParserReturns(new OkResponse>(allowedScopes))) .And(_ => GivenTheFollowing(allowedScopes)) - .When(_ => WhenIAuthorise()) + .When(_ => WhenIAuthorize()) .Then(_ => ThenTheFollowingIsReturned(new OkResponse(true))) .BDDfy(); } @@ -82,7 +82,7 @@ namespace Ocelot.UnitTests.Infrastructure this.Given(_ => GivenTheFollowing(claimsPrincipal)) .And(_ => GivenTheParserReturns(new OkResponse>(userScopes))) .And(_ => GivenTheFollowing(allowedScopes)) - .When(_ => WhenIAuthorise()) + .When(_ => WhenIAuthorize()) .Then(_ => ThenTheFollowingIsReturned(new ErrorResponse(fakeError))) .BDDfy(); } @@ -102,9 +102,9 @@ namespace Ocelot.UnitTests.Infrastructure _allowedScopes = allowedScopes; } - private void WhenIAuthorise() + private void WhenIAuthorize() { - _result = _authoriser.Authorise(_principal, _allowedScopes); + _result = _authorizer.Authorize(_principal, _allowedScopes); } private void ThenTheFollowingIsReturned(Response expected) diff --git a/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs b/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs index 04a4496f..543a1cb9 100644 --- a/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs +++ b/test/Ocelot.UnitTests/Responder/ErrorsToHttpStatusCodeMapperTests.cs @@ -29,10 +29,10 @@ namespace Ocelot.UnitTests.Responder [Theory] [InlineData(OcelotErrorCode.CannotFindClaimError)] - [InlineData(OcelotErrorCode.ClaimValueNotAuthorisedError)] - [InlineData(OcelotErrorCode.ScopeNotAuthorisedError)] + [InlineData(OcelotErrorCode.ClaimValueNotAuthorizedError)] + [InlineData(OcelotErrorCode.ScopeNotAuthorizedError)] [InlineData(OcelotErrorCode.UnauthorizedError)] - [InlineData(OcelotErrorCode.UserDoesNotHaveClaimError)] + [InlineData(OcelotErrorCode.UserDoesNotHaveClaimError)] public void should_return_forbidden(OcelotErrorCode errorCode) { ShouldMapErrorToStatusCode(errorCode, HttpStatusCode.Forbidden); @@ -52,8 +52,8 @@ namespace Ocelot.UnitTests.Responder public void should_return_internal_server_error(OcelotErrorCode errorCode) { ShouldMapErrorToStatusCode(errorCode, HttpStatusCode.InternalServerError); - } - + } + [Theory] [InlineData(OcelotErrorCode.ConnectionToDownstreamServiceError)] public void should_return_bad_gateway_error(OcelotErrorCode errorCode) @@ -104,7 +104,7 @@ namespace Ocelot.UnitTests.Responder } [Fact] - public void AuthorisationErrorsHaveSecondHighestPriority() + public void AuthorizationErrorsHaveSecondHighestPriority() { var errors = new List { @@ -177,4 +177,4 @@ namespace Ocelot.UnitTests.Responder _result.ShouldBe((int)expectedCode); } } -} +}