locked
AntiForgery Tokens on Web API Controllers RRS feed

  • Question

  • User-1188570427 posted

    Hello,

    When would you want to use an AntiValidationToken for an API Controller?

    I know HTTP Post will use them, but would Puts / Deletes?

    I made this:

        /// <summary>
        /// ValidateAntiForgeryTokenAttribute
        /// </summary>
        /// <seealso cref="System.Web.Http.Filters.FilterAttribute" />
        /// <seealso cref="System.Web.Http.Filters.IAuthorizationFilter" />
        [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
        public sealed class WebAPIValidateAntiForgeryTokenAttribute : FilterAttribute, IAuthorizationFilter
        {
            /// <summary>
            /// Executes the authorization filter asynchronous.
            /// </summary>
            /// <param name="actionContext">The action context.</param>
            /// <param name="cancellationToken">The cancellation token.</param>
            /// <param name="continuation">The continuation.</param>
            /// <returns>HttpResponseMessage</returns>
            public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
            {
                try
                {
                    AntiForgery.Validate();
                }
                catch
                {
                    actionContext.Response = new HttpResponseMessage
                    {
                        StatusCode = HttpStatusCode.Forbidden,
                        RequestMessage = actionContext.ControllerContext.Request
                    };
                    return FromResult(actionContext.Response);
                }
    
                return continuation();
            }
    
            /// <summary>
            /// Froms the result.
            /// </summary>
            /// <param name="result">The result.</param>
            /// <returns>HttpResponseMessage</returns>
            private Task<HttpResponseMessage> FromResult(HttpResponseMessage result)
            {
                var source = new TaskCompletionSource<HttpResponseMessage>();
                source.SetResult(result);
                return source.Task;
            }
        }

    Monday, July 27, 2020 1:20 PM

Answers

  • User-474980206 posted

    as with a post, only if you used a form url encoded payload. Generally with an api you would json or xml payload, so the anti forgery is not supported. 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 27, 2020 2:21 PM
  • User475983607 posted

    When would you want to use an AntiValidationToken for an API Controller?

    The anti-forgery token is designed for browser based HTML forms to prevent cross site scripting vulnerabilities.   Web API uses CORS to grant/deny browser based AJAX calls from a domain other than the domain that rendered the page.

    Why do you want to use the anti-forgery token in Web API?  What problem are you trying to solve?

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 27, 2020 2:30 PM
  • User475983607 posted

    See this is why I'm confused. That is what I'm trying to do - fully understand it, so I can make it correct in my application.

    https://blog.novanet.no/anti-forgery-tokens-using-mvc-web-api-and-angularjs/

    But then you are saying it is not needed!

    It seems to me you made up your mind before asking the question.

    The key is understanding that the 7 year old  tutorial is illustrating a browser based application where CSRF is a concern.  Note, the Web API was modified to handle the anti-forgery token in the header.   That means the Web API actions are dependent on the MVC application to render the HTML form and cannot be consumed by any other clients.  Basically the application is self-contained. 

    Web API is typically shared by many different types of clients.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 27, 2020 4:26 PM

All replies

  • User-474980206 posted

    as with a post, only if you used a form url encoded payload. Generally with an api you would json or xml payload, so the anti forgery is not supported. 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 27, 2020 2:21 PM
  • User475983607 posted

    When would you want to use an AntiValidationToken for an API Controller?

    The anti-forgery token is designed for browser based HTML forms to prevent cross site scripting vulnerabilities.   Web API uses CORS to grant/deny browser based AJAX calls from a domain other than the domain that rendered the page.

    Why do you want to use the anti-forgery token in Web API?  What problem are you trying to solve?

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 27, 2020 2:30 PM
  • User-1188570427 posted

    tvb2727

    When would you want to use an AntiValidationToken for an API Controller?

    The anti-forgery token is designed for browser based HTML forms to prevent cross site scripting vulnerabilities.   Web API uses CORS to grant/deny browser based AJAX calls from a domain other than the domain that rendered the page.

    Why do you want to use the anti-forgery token in Web API?  What problem are you trying to solve?

    tvb2727

    When would you want to use an AntiValidationToken for an API Controller?

    The anti-forgery token is designed for browser based HTML forms to prevent cross site scripting vulnerabilities.   Web API uses CORS to grant/deny browser based AJAX calls from a domain other than the domain that rendered the page.

    Why do you want to use the anti-forgery token in Web API?  What problem are you trying to solve?

    Thanks for your reply.

    So you are saying that it is not needed for a Web API Controller with HttpPost, HttpPut, HttpDelete?

    I'm tyring to understand it all.

    My thought was you send over the token and the anti validation token was not being validated on a Post like we do in a MVC Controller. Therefore, I needed one for my WebAPI Controller that we use for Dev Express Controls.

    Then I found the code that I posted to validate one from a WebAPI Controller. I impemented it, the attribute fires, and everything works as needed on HttpPost, HttpPut, HttpDeletes. 

    Maybe I do not need it at all and I'm misunderstanding the process for Web API Controllers with validation of anti-forgery tokens. 

    Are you saying the X-Frame-Options setting will allow for the anti validation token to not be needed on a web api controller?

      <system.webServer>
        <httpProtocol>
          <customHeaders>
            <remove name="X-Frame-Options" />
            <remove name="X-Xss-Protection" />
            <remove name="X-Permitted-Cross-Domain-Policies" />
            <remove name="Strict-Transport-Security" />
            <add name="X-Frame-Options" value="SAMEORIGIN" />
            <add name="X-Xss-Protection" value="1; mode=block" />
            <add name="X-Permitted-Cross-Domain-Policies" value="none" />
            <add name="Strict-Transport-Security" value="max-age=31536000; includeSubDomains" />
            <remove name="X-Powered-By" />
          </customHeaders>
        </httpProtocol>

    Monday, July 27, 2020 2:57 PM
  • User475983607 posted

    It very hard help you when you do not understand the problem ASP.NET anti-forgery tokens solve or Web API fundamentals.  Once you learn the basics then you'll understand why anti-forgery tokens are not used in Web API.  

    I recommend DevExpress support if you need help with DevExpress controls and programming constructs.

    Monday, July 27, 2020 3:04 PM
  • User-1188570427 posted

    It very hard help you when you do not understand the problem ASP.NET anti-forgery tokens solve or Web API fundamentals.  Once you learn the basics then you'll understand why anti-forgery tokens are not used in Web API.  

    I recommend DevExpress support if you need help with DevExpress controls and programming constructs.

    See this is why I'm confused. That is what I'm trying to do - fully understand it, so I can make it correct in my application.

    https://blog.novanet.no/anti-forgery-tokens-using-mvc-web-api-and-angularjs/

    But then you are saying it is not needed!

    Monday, July 27, 2020 3:12 PM
  • User475983607 posted

    See this is why I'm confused. That is what I'm trying to do - fully understand it, so I can make it correct in my application.

    https://blog.novanet.no/anti-forgery-tokens-using-mvc-web-api-and-angularjs/

    But then you are saying it is not needed!

    It seems to me you made up your mind before asking the question.

    The key is understanding that the 7 year old  tutorial is illustrating a browser based application where CSRF is a concern.  Note, the Web API was modified to handle the anti-forgery token in the header.   That means the Web API actions are dependent on the MVC application to render the HTML form and cannot be consumed by any other clients.  Basically the application is self-contained. 

    Web API is typically shared by many different types of clients.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 27, 2020 4:26 PM
  • User-1188570427 posted

    tvb2727

    See this is why I'm confused. That is what I'm trying to do - fully understand it, so I can make it correct in my application.

    https://blog.novanet.no/anti-forgery-tokens-using-mvc-web-api-and-angularjs/

    But then you are saying it is not needed!

    It seems to me you made up your mind before asking the question.

    The key is understanding that the 7 year old  tutorial is illustrating a browser based application where CSRF is a concern.  Note, the Web API was modified to handle the anti-forgery token in the header.   That means the Web API actions are dependent on the MVC application to render the HTML form and cannot be consumed by any other clients.  Basically the application is self-contained. 

    Web API is typically shared by many different types of clients.

    Thank you.

    Here is another context I found:

    "My take is that it isn't a form, so if the request body is being made by an app and sent through HTTPS, there could me no middleman forging a request"

    Monday, July 27, 2020 5:06 PM
  • User475983607 posted

    Here is another context I found:

    "My take is that it isn't a form, so if the request body is being made by an app and sent through HTTPS, there could me no middleman forging a request"

    Keep in mind that Bruce provided a similar answer above. 

    Monday, July 27, 2020 5:25 PM