I'm trying to develop a web service to be consumed by mobile clients (iOS clients, for now), I read that RESTful services are much more lightweight than SOAP services, so I'd li开发者_高级运维ke to try my hand at this.
Most methods will require authentication, but I'm not sure how to handle this, as I read REST is supposed to be stateless, so how can I validate the user accessing the service from iOS and then use that authentication to validate successive calls to other web methods?
Note: I'll be using WCF 4's WebHttp on IIS.
Thank you!
There are a number of fairly established patterns for doing this.
- The simplest way to do so would be to provide the username:password as an Authorization header or part of the request (querystring/form data). This would require you to authenticate/authorize the user on each call. Not ideal for you, perhaps, but if you're using WebHttp (if you didn't mean this, I'd take a serious look at WCF Web Api), it would be fairly easy to build an HttpModule or something in the WCF channel stack to intercept the calls and authenticate the user.
- A very common way is to expose an endpoint that takes user:password and generates an API token. The user then takes that API token and uses it to authenticate subsequent calls. That token can be anything from weakly-encrypted data to a hash consisting of a shared secret key, the HTTP verb, requested resource, etc. You'll find several example of this if you google "HMAC Authentication". Azure's authentication schemes are an example of a really granular token. The nice thing about this approach is that you have one endpoint concerned with authentication and building the tokens, and your other endpoints just need to know how to validate the hash or decrypt the token; a nice separation of concerns.
- OAuth/OAuth2 are pretty much the de facto standard if you expect your API's consumer to be a third-party application.
I would suggest using a strategy similar to OAuth. You would write one service specifically to validate credentials and hand out access tokens, and require a valid access token for any request to your API.
If you're hosting in IIS, I've accomplished this before using an HttpModule to inspect all incoming requests for a valid token. If there isn't one, the module just ends the request with a 401 Unauthorized Http status code.
EDIT:
If you'd like to do more fine-grained authorization on a per operation basis, I'd suggest using a custom authorization policy. Check out http://msdn.microsoft.com/en-us/library/ms731181.aspx for more details.
精彩评论