Skip to content

Commit

Permalink
Authentication errors should also return ProblemDetails so that consu…
Browse files Browse the repository at this point in the history
…mers can parse all errors in the same way. (#524)
  • Loading branch information
Ceredron authored Aug 16, 2024
1 parent 001c374 commit 3a9b129
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions src/Altinn.Broker.API/Helpers/JWTBearerEventsHelper.cs
Original file line number Diff line number Diff line change
@@ -1,25 +1,34 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Mvc;
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.ContentType = "application/problem+json";
context.Response.Headers.Append("WWW-Authenticate", context.Options.Challenge + " error=\"invalid_token\"");
string err = context.Exception.Message;
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";
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return context.Response.WriteAsJsonAsync(new ProblemDetails()
{
Status = StatusCodes.Status403Forbidden,
Title = "IDX10205: Issuer validation failed",
Detail = "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);
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return context.Response.WriteAsJsonAsync(new ProblemDetails
{
Status = StatusCodes.Status401Unauthorized,
Title = "Authentication failed",
Detail = context.Exception.Message
});
}
}

0 comments on commit 3a9b129

Please sign in to comment.