Managing browser sessions with Google sign in

2019-07-30 05:37发布

I have implemented a google sign in button for my website using the steps outlined in this page:

https://developers.google.com/identity/sign-in/web/sign-in

The page then extracts the id_token and sends it to my backend server, which validates it against the Google validation endpoint. I then use their Google ID that is encoded in the id_token to retrieve the application specific data associated with it (stored on my database).

I'm just a bit confused on what I need to do next to keep the user "signed in" to my application and to continue to securely retrieve data from my backend API's.

I am intending to do the following:

  1. After I have validated the id_token I create a session ID for the user
  2. I store the session ID along with the users Google ID in a "sessions" table in my database
  3. I respond to the request by setting a cookie with the session ID
  4. For all subsequent requests I check the session ID in the cookie
  5. If there is an entry for that session ID in the sessions table, I use the Google ID associated with it to retrieve the users info

I would just like to know if this sounds reasonable, is it best practice or if there is a better way to do this? Is there are secure way to generate session ID's or are there API's to help with this (I am currently using ASP.Net Web Api 2 for my backend services)

Many thanks,

1条回答
Ridiculous、
2楼-- · 2019-07-30 06:24

I think you're confusing authentication and authorization. You should have your own record of the user in your server app and the key is Google, not the "name". Here's what I do in my Django (Python) application:

def auth_id_token(request):
    # This is called by the AJAX code that triggers when 
    # the user has successfully signed in
    id_token = request.POST.get('id_token')
    # Using the google-api-python-client library
    idinfo = client.verify_id_token(
        id_token,
        settings.OAUTH2_CLIENT_ID
    )
    # Use the Django ORM to talk to my user database
    user = User.objects.get(email=idinfo['email'])
    # Using a Django primitive that makes sure the user
    # gets a session cookie and asserts that the user is now signed in
    auth.login(request, user)
    return http.HttpResponse('User is now signed in on the server')

Note. Django handles all the authorization from this point onwards. Google was just there to handle the authentication that proves to me that he/she owns that email address.

查看更多
登录 后发表回答