Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authentication with a REST API

I'm building a REST API in asp.net mvc. My system uses forms authentication. Username/password or openId/fbconnect, etc. If I have the [Authorize] attribute on an action, how would an android app or a desktop app get access to the method?

Or the better question is, how would I be designing the desktop app to authenticate? Would I need to pass an API key or some token of some sort? Or would the desktop app behave like a browser and use internal cookies? I'm not quite sure how a RESTful API would work outside of a web browser with authentication.

like image 205
Shawn Mclean Avatar asked Aug 26 '11 18:08

Shawn Mclean


People also ask

How does authentication work in rest?

Basic Authentication Flow A REST request can have a special header called Authorization Header, this header can contain the credentials (username and password) in some form. Once a request with Authorization Header is received, the server can validate the credentials and can let you access the private resources.


1 Answers

I wouldn't use cookies in a REST API. FormsAuthentication is a cookie-based method. Instead, the caller should provide authentication credentials with every request in a header, or as a request parameter.

For example, you could use Basic authentication to transmit user name and password, or add a custom authentication header with some encrypted access token (which is not very RESTful). You could also implement OAuth, where the requester will provide an access token with every request.

I'd write a custom AuthorizeAttribute to perform the authentication in your code, that gives you a lot of control. Alternatively, you can use a controller base class and override the OnAuthorization method.

The API should not provide a password challenge: In a web app, an unauthorized request will typically redirect the user to a login page. In an API, the request will simply return an error code. It is now the client application's job to challenge the user through a dialog, if applicable. In a mobile app, you might want 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 REST Console for Google Chrome and cURL. The former is easier for beginners and comes with a nice GUI while cURL gives you even more fidelity and lots of protocols.

EDIT

A somewhat pedantic note: Some APIs, even those of fairly large providers, e.g. Twitter, return 401 status codes from time to time, typically omitting the (mandatory) WWW-Authenticate header because it was not their intention to challenge the client.

like image 120
mnemosyn Avatar answered Sep 30 '22 13:09

mnemosyn