Digital Assistant and Mobile

Get Involved. Join the Conversation.

Topic

    Saif Abulkhair
    401- Custom Message in MCS
    Topic posted August 29, 2017 by Saif AbulkhairRed Ribbon: 250+ Points, last edited August 30, 2017 
    87 Views, 1 Comment
    Title:
    401- Custom Message in MCS
    Summary:
    401- Custom Message in MCS
    Content:

    Hi,

    In my custom API i am returning status 401 with a custom message, however, when we test the api we get only 401 unauthorized status code and not the custom message. How can we achieve this?

    In the code, if the authenticateToken is 401, I am not able to return my custom message.

    ut . h

    enticateToken.statusCode

    
    

    var result = {

            statusCode:authenticateToken.statusCode,

            success:false,

            message:authenticateToken.message

          };

          console.log("Response Object:"+ JSON.stringify(result,undefined,2));

          res.status(authenticateToken.statusCode).send(result);

    Regards

    Comment

     

    • Lonneke Dikmans

      You can use a custom status code like this:

      function(req, res) {
        res
      .statusMessage = "custum status message";
        res
      .status(401).end();
      }

      this will give you a custom message body:

      res.status(401).send('custom body message');

      However, if you are not the one throwing the error, but the server you can't really influence the response. Are you sure it is reaching your code?

      Side note:

      There's a problem with 401 Unauthorized, the HTTP status code for authentication errors. And that’s just it: it’s for authentication, not authorization. Receiving a 401 response is the server telling you, “you aren’t authenticated–either not authenticated at all or authenticated incorrectly–but please reauthenticate and try again.” To help you out, it will always include a WWW-Authenticate header that describes how to authenticate.

      This is a response generally returned by your web server, not your web application.

      It’s also something very temporary; the server is asking you to try again.

      So, for authorization I use the 403 Forbidden response. It’s permanent, it’s tied to my application logic, and it’s a more concrete response than a 401.

      Receiving a 403 response is the server telling you, “I’m sorry. I know who you are–I believe who you say you are–but you just don’t have permission to access this resource. Maybe if you ask the system administrator nicely, you’ll get permission. But please don’t bother me again until your predicament changes.”

      In summary, a 401 Unauthorized response should be used for missing or bad authentication, and a 403 Forbidden response should be used afterwards, when the user is authenticated but isn’t authorized to perform the requested operation on the given resource.