How to capture the Exception generated by a method whose access is not authorized by a particular user profile

Asked

Viewed 169 times

4

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

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

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

That function salvaApontamento() calls a method in 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 you are the logged in "Administrator":

 [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 triggering the request, the return falls straight into the Ajax error and my request does not even arrive in the method there in Controller.

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

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

inserir a descrição da imagem aqui

When the user is authorized, my data object returns the data I built there in the Controller method.

inserir a descrição da imagem aqui

  • I believe what Eduardo said is correct.

  • When the user is authorized, as is the returned date object?

  • Eduardo, I updated the question.

  • When the result returns with error, there is some field called result? Note that when the result returns OK, the value of result is "Success".

2 answers

3

Tag statusCode 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 it with the above code.

  • Eduardo, I did the test, but the value obtained in the statusCode is 200.

  • 1

    Strange.... how does it return an error with status 200? What else comes in data?

2


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

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 use is identical:

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

And for the call from Ajax, the response of @Eduardofernandes takes good care.

  • 1

    Great idea :)!!

  • 1

    A cool alternative is to use Httpmodule, which intercepts all requests and performs any custom activity. At that point, you can treat unauthorized code. See this link with a legal tutorial on Httpmodule and Httphandler: http://www.codeproject.com/Articles/30907/The-Two-Interceptors-HttpModule-and-HttpHandlers

  • @Gypsy Morrison Mendez , the filterContext line.Result = new Httpunauthorizedresult(); will always be executed, even if the top condition is met. Is there any special reason?

  • @Eduardofernandes HttpHandler is for something more comprehensive. As the author of the question is simpler, derive the attribute of authorization becomes simpler and more elegant.

  • 1

    @Ciganomorrisonmendez, the advantage of using HttpHandler is that the management of this HTTP code, and of any other, can be done in only one location. Moreover, using HttpHandler, all controllers will have equal behavior for handling this problem and any other that may appear for authorization, without the need to use inheritance.

  • @Eduardofernandes Still, for his case there is no need for it. It’s just a simple permission check.

  • @Emerson is right. I changed the answer.

  • 1

    Eduardofernandes and @Cigano Morrison Mendes, I implemented according to the guidelines you gave me and it worked. Thanks

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.