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.
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
AuthorizeAttributeto perform the authentication in your code, that gives you a lot of control. Alternatively, you can use a controller base class and override theOnAuthorizationmethod.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
401status codes from time to time, typically omitting the (mandatory)WWW-Authenticateheader because it was not their intention to challenge the client.