dotnet / dotnet/aspnetcore

Ability to know why the antiforgery token validation has failed and then return custom responses

Open
#57,225 0 comments 1 reaction 0 assignees View on GitHub
area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Is your feature request related to a problem? Please describe the problem.

I have used filter `AutoValidateAntiforgeryTokenAttribute ` It further uses filter `AutoValidateAntiforgeryTokenAuthorizationFilter` which is internal and sealed and inherit from `ValidateAntiforgeryTokenAuthorizationFilter`. Following method appear to directly return the execution result `AntiforgeryValidationFailedResult` when `AntiforgeryValidationException` exeception has been raised.
`public async Task OnAuthorizationAsync(AuthorizationFilterContext context)`
There is no way to know for us why the token validation has failed.

### Describe the solution you'd like

We need ability to know somehow the message why token validation has failed (it's known that it's been logged) but would like to handle some custom logic based on the error that's sent back.
E.g. see the error reason in the screenshot of logs. Following error appears when session has timed out and user is now not authenticated anymore (claims when token issued are not matching to current claims), In this case we don't want to return 400 to user but want to return custom login page or anything we want to return.

![image](https://github.com/user-attachments/assets/aa0fe5bc-1662-43f1-94ce-c05188231e41)

We can use `IAsyncAlwaysRunResultFilter `and see if the action result of type `AntiforgeryValidationFailedResult` and then do some custom logic, but this would be applicable for all types of errors.
![image](https://github.com/user-attachments/assets/56429401-bdb2-4689-b16b-d932f4f6c8e7)

Existing implementation of Antiforgery token validation is not customizable and there is no way to know specific errors why the token validation has failed. Antiforgery appears to be now tied around identity claims, so there should be ability to recognize these errors and handle ourself the responses.
[](url)

### Additional context

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.