API设计-一个域上的应用程序,另一域上的api。 如何在不传递用户ID的情况下检索用户特定的数据

I am trying to build quite a simple web app (for learning purposes) using Golang and Angular JS.

I am comfortable with the Go and AngularJS code but I am having difficulties trying to create an adequate API structure.

At the moment I have all my code running the app and the API code bundled together.

Ideally I would like to separate this out, so I can have my app run on a subdomain such as app.mything.com and the API run on api.mything.com

The problem I have is my API has MYSQL calls such as -

select * FROM sometable where userid = userID

userID is a user ID that it is saved in a session.

So while all the code is bundled together this is possible and works fine. If I was to separate the code to two separate sub domains the session will not be accessible on both.

How is it possible to achieve something like this?

Thanks Dave

There are two ways you can solve this:

  • Change the session storage to something the API and app both share (i.e.: MySQL).
  • Start using (encrypted) cookies instead of session data.

You can still access the user ID.

  • Your API server on api.domain.com can save the ID in a session cookie on login. The cookie will be for the api.domain.com domain. Use gorilla/sessions to get signed cookies by default.
  • The Angular client on www.example.com (different domain) won't be able to read/write to the cookie at all due to the same-origin policy that browsers enforce on cookies, but will still send the cookie back in AJAX requests to the api.domain.com server.

As per the Angular docs (https://docs.angularjs.org/api/ng/service/$http) you'll want to set withCredentials = true to send a cookie on cross-domain requests (ref: Mozilla CORS docs). Make a request to get a cookie (e.g. POST login credentials over HTTPS), and then successive AJAX requests will present that cookie to the server.

The alternative would be to issue OAuth2 Bearer Tokens ("token auth"), record token <=> user ID in a backend (Redis, Bolt, mySQL, etc) and have the Angular app save that in local storage and send it in the header of each request.