Questo documento spiega come implementare un gestore del callback di autorizzazione OAuth 2.0 utilizzando i servlet Java tramite un'applicazione web di esempio che mostri le attività dell'utente utilizzando l'API Google Tasks. L'applicazione di esempio richiederà prima l'autorizzazione per accedere a Google Tasks dell'utente e poi mostrerà le attività dell'utente nell'elenco delle attività predefinito.
Pubblico
Questo documento è pensato per chi ha familiarità con l'architettura delle applicazioni web Java e J2EE. È consigliata una certa conoscenza del flusso di autorizzazione OAuth 2.0.
Sommario
Per avere un esempio completamente funzionante, sono necessari diversi passaggi:
- Dichiara le mappature dei servlet nel file web.xml
- Autentica gli utenti sul tuo sistema e richiedi l'autorizzazione per accedere alle relative attività
- Ascoltare il codice di autorizzazione dall'endpoint di autorizzazione di Google
- Scambiare il codice di autorizzazione con un token di aggiornamento e di accesso
- Leggere le attività dell'utente e visualizzarle
Dichiara le mappature dei servlet nel file web.xml
Nella nostra applicazione utilizzeremo due servlet:
- PrintTasksTitlesServlet (mappato a /): il punto di contatto dell'applicazione che gestisce l'autenticazione dell'utente e mostra le sue attività
- OAuthCodeCallbackHandlerServlet (mappata a /oauth2callback): il callback OAuth 2.0 che gestisce la risposta dall'endpoint di autorizzazione OAuth
Di seguito è riportato il file web.xml che mappa questi due servlet agli URL nella nostra applicazione:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>PrintTasksTitles</servlet-name> <servlet-class>com.google.oauthsample.PrintTasksTitlesServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>PrintTasksTitles</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <servlet> <servlet-name>OAuthCodeCallbackHandlerServlet</servlet-name> <servlet-class>com.google.oauthsample.OAuthCodeCallbackHandlerServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>OAuthCodeCallbackHandlerServlet</servlet-name> <url-pattern>/oauth2callback</url-pattern> </servlet-mapping> </web-app>
Autentica gli utenti sul tuo sistema e richiedi l'autorizzazione per accedere alle relative attività
L'utente accede all'applicazione tramite l'URL principale "/", che è mappato al servlet PrintTaskListsTitlesServlet. In questo servlet vengono eseguite le seguenti attività:
- Controlla se l'utente è autenticato nel sistema
- Se l'utente non è autenticato, viene reindirizzato alla pagina di autenticazione
- Se l'utente è autenticato, controlliamo se è già presente un token di aggiornamento nel nostro spazio di archiviazione dei dati, gestito da OAuthTokenDao di seguito. Se non è presente alcun token di aggiornamento per l'utente, significa che l'utente non ha ancora concesso all'applicazione l'autorizzazione ad accedere alle sue attività. In questo caso, l'utente viene reindirizzato all'endpoint di autorizzazione OAuth 2.0 di Google.
package com.google.oauthsample; import ... /** * Simple sample Servlet which will display the tasks in the default task list of the user. */ @SuppressWarnings("serial") public class PrintTasksTitlesServlet extends HttpServlet { /** * The OAuth Token DAO implementation, used to persist the OAuth refresh token. * Consider injecting it instead of using a static initialization. Also we are * using a simple memory implementation as a mock. Change the implementation to * using your database system. */ public static OAuthTokenDao oauthTokenDao = new OAuthTokenDaoMemoryImpl(); public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Getting the current user // This is using App Engine's User Service but you should replace this to // your own user/login implementation UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); // If the user is not logged-in it is redirected to the login service, then back to this page if (user == null) { resp.sendRedirect(userService.createLoginURL(getFullRequestUrl(req))); return; } // Checking if we already have tokens for this user in store AccessTokenResponse accessTokenResponse = oauthTokenDao.getKeys(user.getEmail()); // If we don't have tokens for this user if (accessTokenResponse == null) { OAuthProperties oauthProperties = new OAuthProperties(); // Redirect to the Google OAuth 2.0 authorization endpoint resp.sendRedirect(new GoogleAuthorizationRequestUrl(oauthProperties.getClientId(), OAuthCodeCallbackHandlerServlet.getOAuthCodeCallbackHandlerUrl(req), oauthProperties .getScopesAsString()).build()); return; } } /** * Construct the request's URL without the parameter part. * * @param req the HttpRequest object * @return The constructed request's URL */ public static String getFullRequestUrl(HttpServletRequest req) { String scheme = req.getScheme() + "://"; String serverName = req.getServerName(); String serverPort = (req.getServerPort() == 80) ? "" : ":" + req.getServerPort(); String contextPath = req.getContextPath(); String servletPath = req.getServletPath(); String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo(); String queryString = (req.getQueryString() == null) ? "" : "?" + req.getQueryString(); return scheme + serverName + serverPort + contextPath + servletPath + pathInfo + queryString; } }
Nota: l'implementazione riportata sopra utilizza alcune librerie App Engine, che vengono utilizzate per semplificare. Se stai sviluppando per un'altra piattaforma, non esitare a implementare di nuovo l'interfaccia UserService che gestisce l'autenticazione utente.
L'applicazione utilizza un DAO per mantenere e accedere ai token di autorizzazione dell'utente. Di seguito sono riportate l'interfaccia OAuthTokenDao e un'implementazione simulata (in memoria) OAuthTokenDaoMemoryImpl utilizzate in questo esempio:
package com.google.oauthsample; import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse; /** * Allows easy storage and access of authorization tokens. */ public interface OAuthTokenDao { /** * Stores the given AccessTokenResponse using the {@code username}, the OAuth * {@code clientID} and the tokens scopes as keys. * * @param tokens The AccessTokenResponse to store * @param userName The userName associated wit the token */ public void saveKeys(AccessTokenResponse tokens, String userName); /** * Returns the AccessTokenResponse stored for the given username, clientId and * scopes. Returns {@code null} if there is no AccessTokenResponse for this * user and scopes. * * @param userName The username of which to get the stored AccessTokenResponse * @return The AccessTokenResponse of the given username */ public AccessTokenResponse getKeys(String userName); }
package com.google.oauthsample; import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse; ... /** * Quick and Dirty memory implementation of {@link OAuthTokenDao} based on * HashMaps. */ public class OAuthTokenDaoMemoryImpl implements OAuthTokenDao { /** Object where all the Tokens will be stored */ private static Map<String, AccessTokenResponse> tokenPersistance = new HashMap<String, AccessTokenResponse>(); public void saveKeys(AccessTokenResponse tokens, String userName) { tokenPersistance.put(userName, tokens); } public AccessTokenResponse getKeys(String userName) { return tokenPersistance.get(userName); } }
Inoltre, le credenziali OAuth 2.0 per l'applicazione sono memorizzate in un file di proprietà. In alternativa, puoi semplicemente inserirli come costanti in uno dei tuoi class Java, anche se di seguito sono riportati la classe OAuthProperties e il file oauth.properties utilizzati nel Sample:
package com.google.oauthsample; import ... /** * Object representation of an OAuth properties file. */ public class OAuthProperties { public static final String DEFAULT_OAUTH_PROPERTIES_FILE_NAME = "oauth.properties"; /** The OAuth 2.0 Client ID */ private String clientId; /** The OAuth 2.0 Client Secret */ private String clientSecret; /** The Google APIs scopes to access */ private String scopes; /** * Instantiates a new OauthProperties object reading its values from the * {@code OAUTH_PROPERTIES_FILE_NAME} properties file. * * @throws IOException IF there is an issue reading the {@code propertiesFile} * @throws OauthPropertiesFormatException If the given {@code propertiesFile} * is not of the right format (does not contains the keys {@code * clientId}, {@code clientSecret} and {@code scopes}) */ public OAuthProperties() throws IOException { this(OAuthProperties.class.getResourceAsStream(DEFAULT_OAUTH_PROPERTIES_FILE_NAME)); } /** * Instantiates a new OauthProperties object reading its values from the given * properties file. * * @param propertiesFile the InputStream to read an OAuth Properties file. The * file should contain the keys {@code clientId}, {@code * clientSecret} and {@code scopes} * @throws IOException IF there is an issue reading the {@code propertiesFile} * @throws OAuthPropertiesFormatException If the given {@code propertiesFile} * is not of the right format (does not contains the keys {@code * clientId}, {@code clientSecret} and {@code scopes}) */ public OAuthProperties(InputStream propertiesFile) throws IOException { Properties oauthProperties = new Properties(); oauthProperties.load(propertiesFile); clientId = oauthProperties.getProperty("clientId"); clientSecret = oauthProperties.getProperty("clientSecret"); scopes = oauthProperties.getProperty("scopes"); if ((clientId == null) || (clientSecret == null) || (scopes == null)) { throw new OAuthPropertiesFormatException(); } } /** * @return the clientId */ public String getClientId() { return clientId; } /** * @return the clientSecret */ public String getClientSecret() { return clientSecret; } /** * @return the scopes */ public String getScopesAsString() { return scopes; } /** * Thrown when the OAuth properties file was not at the right format, i.e not * having the right properties names. */ @SuppressWarnings("serial") public class OAuthPropertiesFormatException extends RuntimeException { } }
Di seguito è riportato il file oauth.properties che contiene le credenziali OAuth 2.0 della tua applicazione. Devi modificare i valori riportati di seguito.
# Client ID and secret. They can be found in the APIs console. clientId=1234567890.apps.googleusercontent.com clientSecret=aBcDeFgHiJkLmNoPqRsTuVwXyZ # API scopes. Space separated. scopes=https://www.googleapis.com/auth/tasks
L'ID client e il segreto client OAuth 2.0 identificano la tua applicazione e consentono all'API Tasks di applicare i filtri e le regole di quota definiti per la tua applicazione. L'ID client e il client secret sono disponibili nella console API di Google. Una volta nella console, dovrai:
- Crea o seleziona un progetto.
- Abilita l'API Tasks impostando lo stato dell'API Tasks su ON nell'elenco dei servizi.
- In Accesso API, crea un ID client OAuth 2.0 se non ne è stato ancora creato uno.
- Assicurati che l'URL del gestore del callback del codice OAuth 2.0 del progetto sia registrato/inserito nella lista consentita negli URI di reindirizzamento. Ad esempio, in questo progetto di esempio devi registrare https://www.example.com/oauth2callback se la tua applicazione web viene pubblicata dal dominio https://www.example.com.

Ascolta il codice di autorizzazione dall'endpoint di autorizzazione di Google
Se l'utente non ha ancora autorizzato l'applicazione ad accedere alle sue attività e di conseguenza è stato reindirizzato all'endpoint di autorizzazione OAuth 2.0 di Google, gli viene mostrata una finestra di dialogo di autorizzazione di Google che gli chiede di concedere alla tua applicazione l'accesso alle sue attività:

Dopo aver concesso o negato l'accesso, l'utente verrà reindirizzato al gestore del callback del codice OAuth 2.0 che è stato specificato come reindirizzamento/callback durante la creazione dell'URL di autorizzazione di Google:
new GoogleAuthorizationRequestUrl(oauthProperties.getClientId(), OAuthCodeCallbackHandlerServlet.getOAuthCodeCallbackHandlerUrl(req), oauthProperties .getScopesAsString()).build()
Il gestore del callback del codice OAuth 2.0 (OAuthCodeCallbackHandlerServlet) gestisce il reindirizzamento dall'endpoint OAuth 2.0 di Google. Esistono due casi da gestire:
- L'utente ha concesso l'accesso: analizza la richiesta per ottenere il codice OAuth 2.0 dai parametri URL
- L'utente ha negato l'accesso: viene mostrato un messaggio all'utente
package com.google.oauthsample; import ... /** * Servlet handling the OAuth callback from the authentication service. We are * retrieving the OAuth code, then exchanging it for a refresh and an access * token and saving it. */ @SuppressWarnings("serial") public class OAuthCodeCallbackHandlerServlet extends HttpServlet { /** The name of the Oauth code URL parameter */ public static final String CODE_URL_PARAM_NAME = "code"; /** The name of the OAuth error URL parameter */ public static final String ERROR_URL_PARAM_NAME = "error"; /** The URL suffix of the servlet */ public static final String URL_MAPPING = "/oauth2callback"; public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Getting the "error" URL parameter String[] error = req.getParameterValues(ERROR_URL_PARAM_NAME); // Checking if there was an error such as the user denied access if (error != null && error.length > 0) { resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "There was an error: \""+error[0]+"\"."); return; } // Getting the "code" URL parameter String[] code = req.getParameterValues(CODE_URL_PARAM_NAME); // Checking conditions on the "code" URL parameter if (code == null || code.length == 0) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "The \"code\" URL parameter is missing"); return; } } /** * Construct the OAuth code callback handler URL. * * @param req the HttpRequest object * @return The constructed request's URL */ public static String getOAuthCodeCallbackHandlerUrl(HttpServletRequest req) { String scheme = req.getScheme() + "://"; String serverName = req.getServerName(); String serverPort = (req.getServerPort() == 80) ? "" : ":" + req.getServerPort(); String contextPath = req.getContextPath(); String servletPath = URL_MAPPING; String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo(); return scheme + serverName + serverPort + contextPath + servletPath + pathInfo; } }
Scambia il codice di autorizzazione con un token di aggiornamento e di accesso
Quindi, OAuthCodeCallbackHandlerServlet scambia il codice Auth 2.0 con un token di aggiornamento e di accesso, lo rende permanente nel datastore e reindirizza l'utente all'URL PrintTaskListsTitlesServlet:
Il codice aggiunto al file di seguito è evidenziato in sintassi, mentre il codice esistente non è selezionabile.
package com.google.oauthsample; import ... /** * Servlet handling the OAuth callback from the authentication service. We are * retrieving the OAuth code, then exchanging it for a refresh and an access * token and saving it. */ @SuppressWarnings("serial") public class OAuthCodeCallbackHandlerServlet extends HttpServlet { /** The name of the Oauth code URL parameter */ public static final String CODE_URL_PARAM_NAME = "code"; /** The name of the OAuth error URL parameter */ public static final String ERROR_URL_PARAM_NAME = "error"; /** The URL suffix of the servlet */ public static final String URL_MAPPING = "/oauth2callback";/** L'URL a cui reindirizzare l'utente dopo la gestione del callback. Valuta la possibilità di memorizzare questo valore in un cookie prima di reindirizzare gli utenti all'URL di autorizzazione di Google se hai più URL a cui reindirizzare gli utenti. */ public static final String REDIRECT_URL = "/"; /** L'implementazione della DAO del token OAuth. Prendi in considerazione l'iniezione anziché l'utilizzo * di un'inizializzazione statica. Inoltre, utilizziamo una semplice implementazione della memoria * come simulazione. Modifica l'implementazione in modo da utilizzare il tuo sistema di database. */ public static OAuthTokenDao oauthTokenDao = new OAuthTokenDaoMemoryImpl();// Costruisci l'URL della richiesta in arrivo String requestUrl = getOAuthCodeCallbackHandlerUrl(req); // Scambia il codice con i token OAuth AccessTokenResponse accessTokenResponse = exchangeCodeForAccessAndRefreshTokens(code[0], requestUrl); // Recupera l'utente corrente // Viene utilizzato il servizio utente di App Engine, ma devi sostituirlo con la tua implementazione di utente/accesso UserService userService = UserServiceFactory.getUserService(); String email = userService.getCurrentUser().getEmail(); // Salva i token oauthTokenDao.saveKeys(accessTokenResponse, email); resp.sendRedirect(REDIRECT_URL); } public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Getting the "error" URL parameter String[] error = req.getParameterValues(ERROR_URL_PARAM_NAME); // Checking if there was an error such as the user denied access if (error != null && error.length > 0) { resp.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "There was an error: \""+error[0]+"\"."); return; } // Getting the "code" URL parameter String[] code = req.getParameterValues(CODE_URL_PARAM_NAME); // Checking conditions on the "code" URL parameter if (code == null || code.length == 0) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "The \"code\" URL parameter is missing"); return; }/** * Scambia il codice specificato con una piattaforma di scambio pubblicitario e un token di aggiornamento. * * @param code Il codice restituito dal servizio di autorizzazione * @param currentUrl L'URL del callback * @param oauthProperties L'oggetto contenente la configurazione OAuth * @return L'oggetto contenente sia un token di accesso che un token di aggiornamento * @throws IOException */ public AccessTokenResponse exchangeCodeForAccessAndRefreshTokens(String code, String currentUrl) throws IOException { HttpTransport httpTransport = new NetHttpTransport(); JacksonFactory jsonFactory = new JacksonFactory(); // Caricamento del file di configurazione OAuth OAuthProperties oauthProperties = new OAuthProperties(); return new GoogleAuthorizationCodeGrant(httpTransport, jsonFactory, oauthProperties .getClientId(), oauthProperties.getClientSecret(), code, currentUrl).execute(); } } /** * Construct the OAuth code callback handler URL. * * @param req the HttpRequest object * @return The constructed request's URL */ public static String getOAuthCodeCallbackHandlerUrl(HttpServletRequest req) { String scheme = req.getScheme() + "://"; String serverName = req.getServerName(); String serverPort = (req.getServerPort() == 80) ? "" : ":" + req.getServerPort(); String contextPath = req.getContextPath(); String servletPath = URL_MAPPING; String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo(); return scheme + serverName + serverPort + contextPath + servletPath + pathInfo; }File OAuthCodeCallbackHandlerServlet.javaNota: l'implementazione riportata sopra utilizza alcune librerie App Engine, che vengono utilizzate per semplificare. Se stai sviluppando per un'altra piattaforma, non esitare a implementare di nuovo l'interfaccia UserService che gestisce l'autenticazione utente.
Leggere le attività dell'utente e visualizzarle
L'utente ha concesso all'applicazione l'accesso alle sue attività. L'applicazione ha un token di aggiornamento salvato nel datastore accessibile tramite OAuthTokenDao. Ora il servlet PrintTaskListsTitlesServlet può utilizzare questi token per accedere alle attività dell'utente e visualizzarle:
Il codice aggiunto al file di seguito è evidenziato in sintassi, mentre il codice esistente non è selezionabile.
package com.google.oauthsample; import ... /** * Simple sample Servlet which will display the tasks in the default task list of the user. */ @SuppressWarnings("serial") public class PrintTasksTitlesServlet extends HttpServlet { /** * The OAuth Token DAO implementation, used to persist the OAuth refresh token. * Consider injecting it instead of using a static initialization. Also we are * using a simple memory implementation as a mock. Change the implementation to * using your database system. */ public static OAuthTokenDao oauthTokenDao = new OAuthTokenDaoMemoryImpl(); public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Getting the current user // This is using App Engine's User Service but you should replace this to // your own user/login implementation UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); // If the user is not logged-in it is redirected to the login service, then back to this page if (user == null) { resp.sendRedirect(userService.createLoginURL(getFullRequestUrl(req))); return; } // Checking if we already have tokens for this user in store AccessTokenResponse accessTokenResponse = oauthTokenDao.getKeys(user.getEmail()); // If we don't have tokens for this user if (accessTokenResponse == null) { OAuthProperties oauthProperties = new OAuthProperties(); // Redirect to the Google OAuth 2.0 authorization endpoint resp.sendRedirect(new GoogleAuthorizationRequestUrl(oauthProperties.getClientId(), OAuthCodeCallbackHandlerServlet.getOAuthCodeCallbackHandlerUrl(req), oauthProperties .getScopesAsString()).build()); return; }// Stampa i titoli degli elenchi di attività dell'utente nella risposta resp.setContentType("text/plain"); resp.getWriter().append("Task Lists titles for user " + user.getEmail() + ":\n\n"); printTasksTitles(accessTokenResponse, resp.getWriter());/** * Utilizza l'API Google Tasks per recuperare un elenco delle attività degli utenti nell'elenco di attività predefinito. * * @param accessTokenResponse L'oggetto AccessTokenResponse OAuth 2.0 * contenente il token di accesso e un token di aggiornamento. * @param output lo stream di output in cui scrivere i titoli degli elenchi di attività * @return Un elenco dei titoli delle attività degli utenti nell'elenco di attività predefinito. * @throws IOException */ public void printTasksTitles(AccessTokenResponse accessTokenResponse, Writer output) throws IOException { // Inizializzazione del servizio Tasks HttpTransport transport = new NetHttpTransport(); JsonFactory jsonFactory = new JacksonFactory(); OAuthProperties oauthProperties = new OAuthProperties(); GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource( accessTokenResponse.accessToken, transport, jsonFactory, oauthProperties.getClientId(), oauthProperties.getClientSecret(), accessTokenResponse.refreshToken); Tasks service = new Tasks(transport, accessProtectedResource, jsonFactory); // Utilizzo del servizio API Tasks inizializzato per eseguire query sull'elenco degli elenchi di attività com.google.api.services.tasks.model.Tasks tasks = service.tasks.list("@default").execute(); for (Task task : tasks.items) { output.append(task.title + "\n"); } } } } /** * Construct the request's URL without the parameter part. * * @param req the HttpRequest object * @return The constructed request's URL */ public static String getFullRequestUrl(HttpServletRequest req) { String scheme = req.getScheme() + "://"; String serverName = req.getServerName(); String serverPort = (req.getServerPort() == 80) ? "" : ":" + req.getServerPort(); String contextPath = req.getContextPath(); String servletPath = req.getServletPath(); String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo(); String queryString = (req.getQueryString() == null) ? "" : "?" + req.getQueryString(); return scheme + serverName + serverPort + contextPath + servletPath + pathInfo + queryString; }File PrintTasksTitlesServlet.javaL'utente verrà visualizzato con le relative attività:
Le attività dell'utenteApplicazione di esempio
Il codice di questa applicazione di esempio può essere scaricato qui. Non esitare a dare un'occhiata.