I'm trying to understand this example project which uses Google's OAuth library to let users login with their Google account.
Specifically, I'm trying to understand the relationship between Oauth2AuthorizationCodeServlet.java and Oauth2CallbackServlet.java. I know that Google's OAuth 2.0 library uses them to kick off the authorization flow and to handle the result after the user logs in, and I've read through the documentation for both abstract classes, but I'm wondering why both classes need to repeat the same logic?
- Both classes define
getUserId()
functions which return the same value. - Both classes define
initializeFlow()
functions which return the same value. - Both classes define
getRedirectUri()
functions which return the same value.
The code works fine, and I can see that the functions are called in this order:
Oauth2AuthorizationCodeServlet#getUserId()
Oauth2AuthorizationCodeServlet#initializeFlow()
Oauth2AuthorizationCodeServlet#getRedirectUri()
Oauth2CallbackServlet#initializeFlow()
Oauth2CallbackServlet#getRedirectUrl()
Oauth2CallbackServlet#getUserId()
Oauth2CallbackServlet#onSuccess()
But I'm wondering why the repeated functions in Oauth2CallbackServlet
are necessary.
Why can't Google's OAuth 2.0 library use the values returned by the first class? Would it ever make sense for the corresponding functions to return different values? For example, would it ever make sense for their getRedirectUrl()
functions to return different URLs?
Here is simplified diagram of google oauth login flow.
No 1. here represents
Oauth2AuthorizationCodeServlet
No 2. here represents
Oauth2CallbackServlet
Those are two different servlets, responsible for separate parts of login flow. 1 - redirects user to google login form with some url params like redirect url. 2 - handles callback after user finished with login, this servlet can access user info from google, perform actions on user behalf in google etc.
To answer your questions:
Those are two separate servlets - it would be incorrect to perform communication between two separate servlets.
In common scenario i don't think it makes sense to return different values from those servlets, but maybe some exotic scenario exists, where you have to support multiple google login callback urls for different use cases.