Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API : Correct way to return a 401/unauthorised response

I have an MVC webapi site that uses OAuth/token authentication to authenticate requests. All the relevant controllers have the right attributes, and authentication is working ok.

The problem is that not all of the request can be authorised in the scope of an attribute - some authorisation checks have to be performed in code that is called by controller methods - what is the correct way to return a 401 unauthorised response in this case?

I have tried throw new HttpException(401, "Unauthorized access");, but when I do this the response status code is 500 and I get also get a stack trace. Even in our logging DelegatingHandler we can see that the response is 500, not 401.

like image 741
GoatInTheMachine Avatar asked Jul 03 '15 11:07

GoatInTheMachine


People also ask

How do you throw UnauthorizedAccessException?

An UnauthorizedAccessException exception is typically thrown by a method that wraps a Windows API call. To find the reasons for the exception, examine the text of the exception object's Message property. UnauthorizedAccessException uses the HRESULT COR_E_UNAUTHORIZEDACCESS , which has the value 0x80070005.

What does the HTTP status code 401 indicate?

The HyperText Transfer Protocol (HTTP) 401 Unauthorized response status code indicates that the client request has not been completed because it lacks valid authentication credentials for the requested resource.


2 Answers

You should be throwing a HttpResponseException from your API method, not HttpException:

throw new HttpResponseException(HttpStatusCode.Unauthorized); 

Or, if you want to supply a custom message:

var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Oops!!!" }; throw new HttpResponseException(msg); 
like image 139
LukeH Avatar answered Sep 18 '22 11:09

LukeH


Just return the following:

return Unauthorized(); 
like image 44
JohnWrensby Avatar answered Sep 18 '22 11:09

JohnWrensby