How to catch Exception generated by a method whose access is not authorized by a given user profile

4

How can I send the user a message that the operation he wants to do is not allowed?

I have in my View a button that calls a Javascript function

 <button id="btninicio" onclick="salvaApontamento();">Inicio</button>

This salvaApontamento() function calls a method on my Controller:

function salvaApontamento()
{
    startSpin();
    $.ajax({
        type: "POST",
        url: getBaseUrl() + "/Apontamentos/AlteraApontamento";,
        dataType: "json",
        data: JSON.stringify({ apontamentos: jsonDataApontamentos }),
        contentType: "application/json; charset=utf-8",
        cache: false,
        success: function (data) {
            stopSpin();
            alert("Sucesso);

        },
        error: function (data) {
            stopSpin();
            alert("Erro: salvaApontamento() :(  " + data.message)           
        }
    });
}

I have a method in my controller that makes changes only if it is the "Administrator" login:

 [HttpPost]
 [Authorize(Roles = "Administrador")]
 public JsonResult AlteraApontamento(ApontamentosOperacao apontamentos)
 {
    //faz o que eu preciso e retorna um Json...
 }

Debugging the code, I realized that if I log in as "Operator". When firing the request, the return goes straight to the Ajax error and my request does not even get into the method there on the Controller.

The "Administrator" and the "Operator" see the same View. I would like to send a message to the View that would inform the user that their profile is not valid. What parameter do I need to capture in my data variable, there in javascript to know that the method can not be accessed by the logged in user?

Following my friend Eduardo's suggestion, when I get statusCode in ajax javascript, I get the 200 code.

Whentheuserisauthorized,mydataobjectreturnsthedataIbuiltthereintheControllermethod.

    
asked by anonymous 13.07.2015 / 16:09

2 answers

2

In its place, I would make my own authorization attribute with the ability to return a 403 or 405 error depending on its purpose:

public class MeuAuthorizeAttribute : AuthorizeAttribute 
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
    {
        if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            filterContext.Result = new HttpStatusCodeResult(403);
        else
            filterContext.Result = new HttpUnauthorizedResult();
    } 
}

The usage is identical:

[HttpPost]
[MeuAuthorize(Roles = "Administrador")]
public JsonResult AlteraApontamento(ApontamentosOperacao apontamentos)
{
   //faz o que eu preciso e retorna um Json...
}

And for the Ajax call, the reply from @EduardoFernandes goes well.

    
13.07.2015 / 16:52
3

Put the statusCode tag in your javascript, as shown below:

$.ajax({
  ....
  statusCode: {
    405: function() {
      alert( "Você não temn permisão para...." );
    }
  }
  ....
});

The Controlller returns a "Method Not Allowed" error, represented by the HTTP 405 code. Treat the same with the above code.

    
13.07.2015 / 16:16