I'm building a RESTful API for a project I'm working on and I'd like to make the main application consume the API because:
- It will result in having one set of code to maintain
- Should we decide to expose the API for 3rd party devs it will already be done
- It opens up the possibility to make mobile applications that consume it
- I really want to learn how to do it
The API will be hosted on a subdomain https://api.example.com
and the main web application will be hosted at the root domain https://example.com
.
Conceptually I understand how everything works, but my main question is how the authentication flow will change if, at all. Ordinarily 3rd party apps would:
- Obtain a request token from
https://api.example.com/request_token
- Redirect the user to authenticate on
https://api.authenticate.com/authorize
- Get redirected back to the 3rd party application
- Obtain an access token from
https://api.example.com/access_token
Since I control both domains, can I do something similar to:
- Obtain a request token when the user lands on the login screen at
https://www.example.com
- The user authenticates using a form on
https://www.example.com
that calls the same code ashttps://api.example.com/authorize
- If the credentials are valid, the request token is swapped for the access token
- Access token is saved in the session and expires when the user logs out like it normally would
Step 3 feels like it's wrong since there will be duplicate code, but wouldn't it open me up to XSS attacks is the login form on https://www.example.com
sent the data to https://api.example.com
since they are technically different domains?
Am I overcomplicating this?