Search code examples
asp.net-mvcasp.net-web-apiasp.net-mvc-5asp.net-web-api2asp.net-authorization

Authorization in WebApi


I am building an admin page (MVC 5) using an AdminColntroller:

[Authorize(Roles = "Admin")]
public class AdminController : ApplicationBaseController
{
    public ActionResult Index()
    {
        return View();
    }
}

I want to implement it as a single page application so I will be making client-side ajax calls to an admin web api which I also want to secure access to:

[RoutePrefix("api/admin")]
[Authorize(Roles = "admin")]
public class AdminApiController : ApiController
{
    [Route("echo")]
    public HttpResponseMessage GetEcho()
    {
        return Request.CreateResponse(HttpStatusCode.OK, new {Result = "Hello World"});
    }
}

This is the ajax call I'm making form the admin view:

<script>
    jQuery.ajax("https://example.com/api/admin/echo").done(function(data) {
        console.log(data);
    }).fail(function(a,b,c) {
        console.log(a);
    });
</script>

This throws an error (fail() method): "Authorization has been denied for this request." I don't understand why - my user has a role Admin (that's why I am able to even get to the admin page), and if I remove [Authorize] from GetEcho() method and then set a breakpoint inside it, I see the correct User object. Any ideas what I am doing wrong?


Solution

  • The issue that you are having is that against the MVC controller, you have this:

    [Authorize(Roles = "Admin")]
    

    Whilst against the API controller, you have this:

    [Authorize(Roles = "admin")]
    

    The role check is case sensitive. If you change the API controller to use Admin instead of admin, it should solve the issue.