-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Authentication errors should also return ProblemDetails so that consu…
…mers can parse all errors in the same way. (#524)
- Loading branch information
Showing
1 changed file
with
16 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
}); | ||
} | ||
} |