Authentication with REST API

I am creating a REST API in asp.net mvc. My system uses authentication. Username / password or openId / fbconnect etc. If I have an [Authorize] attribute for an action, how will an android or desktop application access the method?

Or the best question: how will I create desktop authentication applications? Do I need to pass an API key or some kind of token? Or will the desktop application behave like a browser and use internal cookies? I'm not quite sure how the RESTful API will work outside of the authentication web browser.

+7
source share
2 answers

I would not use cookies in the REST API. FormsAuthentication is a cookie based method. Instead, the caller must provide authentication credentials to each request in the header or as a request parameter.

For example, you can use basic authentication to pass a username and password, or add your own authentication header with some encrypted access token (which is not very RESTful). You can also implement OAuth, where the requestor will provide an access token with each request.

I would write a custom AuthorizeAttribute to authenticate in your code, which gives you a lot of control. Alternatively, you can use the base class of the controller and override the OnAuthorization method.

The API must not provide a password. In a web application, an unauthorized request usually redirects the user to the login page. In the API, the request simply returns an error code. Currently, the client application task invokes a user survey through a dialog, if applicable. In a mobile application, you may need to show a dialog. In a web application with OAuth, you probably want to redirect to an authentication server.

If you want to test your REST API, I suggest you use the REST Console for Google Chrome and cURL . The first is easier for beginners and has a nice graphical interface, while cURL gives you even more fidelity and lots of protocols.

EDIT

Somewhat pedantic note: some APIs, even those from fairly large suppliers, for example. Twitter, return 401 status codes from time to time, usually omitting the WWW-Authenticate header (required), because this was not the goal to challenge the client.

+14
source

Take a look at the Amazons AWS authentication scheme. It does what most wants, and uses the standard HTTP authorization header.

+1
source

All Articles