Search code examples
c#umbracoumbraco7

401-Unauthorized when calling UmbracoAuthorizedApiController from backoffice


Problem

When I change my controller to inherit from UmbracoAuthorizedApiController instead of UmbracoApiController I will get 401-Unauthorized and I will be redirected to loging page.

Mode Details

I want to call some of my backend Api's from the back-office and to do that I've followed the article in our.umbraco.

First I've implemented a controller inheriting from UmbracoApiController to be able to call my services from postman. Everything went fine and I could call my code and read data from Umbraco:

 [RoutePrefix("api/admins")]
 public class AdminsController : UmbracoApiController
 {
      [HttpGet]
        [Route("getdata")]
        public DataViewModel GetData(string id)
        {
          ....
         } 
 }

Then I've called my service from JavaScript in Dashboard using the plugins

  $http.get(vm.baseUrl + '/getdata?id=' + id, {})
            .then(function (response) {....}

Everything works fine, I can see that my cookies (containing token) has been sent in the request headers.

token in request

Then I've updated my controller to inherit from UmbracoAuthorizedApiController and now I don't have access to my Apis.

The controller is now like this:

   [RoutePrefix("api/admins")]
    public class AdminsController : UmbracoAuthorizedApiController

What did I do wrong?


Solution

  • Authorized controllers (same as other wrapped MVC controllers in Umbraco) are automatically routed. Backoffice authorisation will work when /umbraco/backoffice/ path will be present in the route.

    Check: https://our.umbraco.org/documentation/reference/routing/Authorized/ and: https://our.umbraco.org/documentation/reference/routing/webapi/authorization

    It's directly said:

    In order for Umbraco to authentication a request for the back office, the routing needs to be specific. Any URL that routes to :

    /umbraco/backoffice/*

    will be authenticated. If you have a controller that is not routed within the prefix, it will not be authenticated for back office use.