Skip to content

Commit

Permalink
Custom jwt issuer exception (#397)
Browse files Browse the repository at this point in the history
* Add extra info when token issuer is maskinporten token

---------

Co-authored-by: Hammerbeck <[email protected]>
  • Loading branch information
Andreass2 and Hammerbeck authored Apr 17, 2024
1 parent aa7461d commit e454460
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/Altinn.Broker.API/Helpers/JWTBearerEventsHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

namespace Altinn.Broker.Helpers;
public class JWTBearerEventsHelper
{
public static Task OnAuthenticationFailed(AuthenticationFailedContext context)
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
context.Response.ContentType = "application/json";
context.Response.Headers.Append("WWW-Authenticate", context.Options.Challenge + " error=\"invalid_token\", error_description=\"" + context.Exception.Message + "\"");
string err = "";
if (context.Exception is SecurityTokenInvalidIssuerException)
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
context.Response.ContentType = "application/json";
var issuer = ((SecurityTokenInvalidIssuerException)context.Exception).InvalidIssuer;
if (issuer.ToString().Contains("maskinporten.no"))
{
err = "IDX10205: Issuer validation failed. Maskinporten token is not valid. Exchange to Altinn token and try again. Read more at https://docs.altinn.studio/api/scenarios/authentication/#maskinporten-jwt-access-token-input";
}
}
return context.Response.WriteAsync(err);
}
}
10 changes: 10 additions & 0 deletions src/Altinn.Broker.API/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Altinn.Broker.API.Configuration;
using Altinn.Broker.Application;
using Altinn.Broker.Core.Options;
using Altinn.Broker.Helpers;
using Altinn.Broker.Integrations;
using Altinn.Broker.Integrations.Azure;
using Altinn.Broker.Integrations.Hangfire;
Expand Down Expand Up @@ -124,6 +125,15 @@ static void ConfigureServices(IServiceCollection services, IConfiguration config
ValidateLifetime = !hostEnvironment.IsDevelopment(), // Do not validate lifetime in tests
ClockSkew = TimeSpan.Zero
};
options.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = context => JWTBearerEventsHelper.OnAuthenticationFailed(context),
OnChallenge = c =>
{
c.HandleResponse();
return Task.CompletedTask;
}
};
})
.AddJwtBearer(AuthorizationConstants.Legacy, options => // To support "overgangslosningen"
{
Expand Down

0 comments on commit e454460

Please sign in to comment.