Skip to content

Commit cab3481

Browse files
authored
Merge pull request #5 from eclipse-mnestix/init
refactor: change the header for API-KEY
2 parents 87b5773 + f7c73a9 commit cab3481

File tree

8 files changed

+81
-22
lines changed

8 files changed

+81
-22
lines changed

compose.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ services:
4343
ports:
4444
- '5064:5064'
4545
environment:
46+
ServerUrls ServerUrls: 'http://mnestix-proxy:5065/repo/'
4647
# API key authorization
4748
CustomerEndpointsSecurity__ApiKey: ${MNESTIX_BACKEND_API_KEY:-verySecureApiKey}
4849
# Connection to Repository Service:
@@ -103,6 +104,8 @@ services:
103104
profiles: ['', 'basyx', 'tests']
104105
depends_on:
105106
- mongodb
107+
ports:
108+
- '8081:8081'
106109
environment:
107110
# MongoDb configuration for Basyx Repository
108111
BASYX__BACKEND: MongoDB

mnestix-proxy.Tests/TestMockService/DownstreamService.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ private void StartServer()
2828
{
2929
var path = context.Request.Path.Value?.ToLowerInvariant();
3030

31-
if (path != null && path.StartsWith("/test-endpoint"))
31+
if (path != null && path.StartsWith("/api/test-endpoint"))
3232
{
3333
context.Response.StatusCode = 200;
3434
await context.Response.WriteAsync("Mnestix Api called!");

mnestix-proxy/Authentication/ApiKeyAuthentication/ApiKeyRequirementHandler.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,6 @@ private void SucceedRequirementIfApiKeyPresentAndValid(AuthorizationHandlerConte
5353
_httpContextAccessor.HttpContext?.Request.Method,
5454
_httpContextAccessor.HttpContext?.Request.Path);
5555
context.Fail(new AuthorizationFailureReason(this,
56-
"For all methods except 'GET' you need a valid ApiKey in your header."));
56+
"For all methods except 'GET' you need a valid X-API-KEY in your header."));
5757
}
5858
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
using Microsoft.AspNetCore.Authorization.Policy;
2+
using Microsoft.AspNetCore.Authorization;
3+
4+
namespace mnestix_proxy.Authentication.ApiKeyAuthentication
5+
{
6+
public class CustomAuthorizationMiddlewareResultHandler : IAuthorizationMiddlewareResultHandler
7+
{
8+
private readonly AuthorizationMiddlewareResultHandler _defaultHandler = new();
9+
10+
public async Task HandleAsync(RequestDelegate next, HttpContext context,
11+
AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
12+
{
13+
if (authorizeResult.Forbidden)
14+
{
15+
context.Response.StatusCode = StatusCodes.Status403Forbidden;
16+
context.Response.ContentType = "application/json";
17+
18+
var message = "Forbidden";
19+
if (authorizeResult.AuthorizationFailure?.FailureReasons?.Any() == true)
20+
{
21+
message = authorizeResult.AuthorizationFailure.FailureReasons
22+
.Select(r => r.Message)
23+
.FirstOrDefault() ?? message;
24+
}
25+
26+
await context.Response.WriteAsJsonAsync(new { error = message });
27+
return;
28+
}
29+
30+
if (authorizeResult.Challenged)
31+
{
32+
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
33+
context.Response.ContentType = "application/json";
34+
35+
await context.Response.WriteAsJsonAsync(new
36+
{
37+
error = "Unauthorized: You must provide valid authentication credentials."
38+
});
39+
return;
40+
}
41+
42+
await _defaultHandler.HandleAsync(next, context, policy, authorizeResult);
43+
}
44+
}
45+
46+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
using Microsoft.Extensions.Configuration;
2+
3+
namespace mnestix_proxy.Authentication
4+
{
5+
public static class ApplicationBuilderAuthExtensions
6+
{
7+
public static IApplicationBuilder UseMnestixConfiguredAuth(this IApplicationBuilder app, IConfiguration configuration)
8+
{
9+
var openIdEnabled = configuration.GetSection("OpenId").GetValue("EnableOpenIdAuth", false);
10+
var azureAdEnabled = configuration.GetSection("AzureAd").GetValue("EnableAzureAdAuth", false);
11+
12+
if (openIdEnabled || azureAdEnabled) {
13+
app.UseAuthentication();
14+
app.UseAuthorization();
15+
}
16+
17+
return app;
18+
}
19+
}
20+
}

mnestix-proxy/Authentication/AuthenticationServicesRegistration.cs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
using Microsoft.AspNetCore.Authentication.JwtBearer;
2+
using Microsoft.AspNetCore.Authorization;
23
using Microsoft.Identity.Web;
34
using Microsoft.IdentityModel.Tokens;
5+
using mnestix_proxy.Authentication.ApiKeyAuthentication;
46

57
namespace mnestix_proxy.Authentication;
68

@@ -55,11 +57,7 @@ public static void AddAuthenticationServices(this IServiceCollection services, I
5557
services.AddMicrosoftIdentityWebApiAuthentication(configuration);
5658
}
5759
else {
58-
services.AddAuthentication(options =>
59-
{
60-
options.DefaultAuthenticateScheme = null;
61-
options.DefaultChallengeScheme = null;
62-
});
60+
services.AddSingleton<IAuthorizationMiddlewareResultHandler, CustomAuthorizationMiddlewareResultHandler>();
6361
}
6462
}
6563
}

mnestix-proxy/Program.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,9 @@ public static void Main(string[] args)
4949
// pipeline settings
5050
var app = builder.Build();
5151

52-
app.UseAuthentication();
53-
app.UseAuthorization();
52+
app.UseMnestixConfiguredAuth(builder.Configuration);
53+
54+
app.UseCors("allowAnything");
5455

5556
app.MapReverseProxy(proxyPipeline =>
5657
{

mnestix-proxy/appsettings.json

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
"ApiKey": "9FB8BCDFAEE81367A1668E16BDC37"
1010
},
1111
"AzureAd": {
12-
"EnableAzureAdAuth": "true",
12+
"EnableAzureAdAuth": "false",
1313
"Instance": "https://login.microsoftonline.com/",
1414
"ClientId": "ffade4c2-76c8-44fd-9258-743d9cfc2289",
1515
"CallbackPath": "",
@@ -22,8 +22,8 @@
2222
},
2323
// if both OpenId and AzureAd are enabled OpenId will be used
2424
"OpenId": {
25-
"EnableOpenIdAuth": "true",
26-
"Issuer": "http://localhost:8080/realms/BaSyx",
25+
"EnableOpenIdAuth": "false",
26+
"Issuer": "http://localhost:8080/realms/Menstix",
2727
"ClientID": "mnestixApi-demo",
2828
"RequireHttpsMetadata": "false"
2929
},
@@ -39,16 +39,7 @@
3939
"AuthorizationPolicy": "customApiKeyToModifyValuesPolicy",
4040
"Match": {
4141
"Path": "api/{**catch-all}"
42-
},
43-
"Transforms": [
44-
{
45-
"PathPattern": "/{**catch-all}"
46-
},
47-
{
48-
"ResponseHeader": "Access-Control-Allow-Origin",
49-
"Set": "*"
50-
}
51-
]
42+
}
5243
},
5344
"EnvironmentRoute": {
5445
"ClusterId": "aasRepoCluster",

0 commit comments

Comments
 (0)