Skip to main content

WebApi Tutorials

Tutorial Home

More secure Basic WebApi Example

In this example, we'll ensure that calls to your API only come from users who are visiting your website. This is to protect agains CSRF attacks, where another website gets your users to interact with your API. That could be dangerous, because maybe your API has things only a logged in user should see - and without the CSRF protection, the other website could get access to that because the user is logged in.

Click to see the result of a WebApi call with the shared code:

Info about the Base Class

This tutorial inherits from the Custom.Hybrid.Razor14 base class.

This allows us to use Kit.Page to access IPageService without having to use GetService<>

Source Code of this file

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code

@inherits Custom.Hybrid.Razor14
@{
  // Tell the page that we need the 2sxc Js APIs
  Kit.Page.Activate("2sxc.JsCore"); 
}
<!-- unimportant stuff, hidden -->

More secure Basic WebApi Example In this... <!-- unimportant stuff, hidden -->
<button type="button" class="btn btn-primary" onclick="apiWithVerification(this)">
  Call WebApi
</button> 

<script>
  function apiWithVerification(moduleContext) {
    $2sxc(moduleContext).webApi.fetchJson('verified/hello')
      .then(data => alert(data));
  }
</script>

<!-- unimportant stuff, hidden -->

Source Code of /api/VerifiedController.cs

Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code

// Add namespaces for security check in Oqtane & DNN despite differences in .net core/.net Framework
// If you only target one platform, you can remove the parts you don't need
#if NETCOREAPP
using Microsoft.AspNetCore.Authorization; // .net core [AllowAnonymous] & [Authorize]
using Microsoft.AspNetCore.Mvc;           // .net core [HttpGet] / [HttpPost] etc.
#else
using System.Web.Http;                    // .net 4.5 [AllowAnonymous] / [HttpGet]
using DotNetNuke.Web.Api;                 // [DnnModuleAuthorize] & [ValidateAntiForgeryToken]
#endif

[AllowAnonymous]                          // all commands can be accessed without a login
[ValidateAntiForgeryToken]                // protects API from users not on your site (CSRF protection)
public class VerifiedController : Custom.Hybrid.Api14 // see https://r.2sxc.org/CustomWebApi
{

  [HttpGet]                               // [HttpGet] says we're listening to GET requests
  public string Hello()
  {
    return "Hello from the controller with ValidateAntiForgeryToken in /api";
  }
}

// The next line is for 2sxc-internal quality checks, you can ignore this
// 2sxclint:disable:no-dnn-namespaces - 2sxclint:disable:no-web-namespace