Dokumen ini menjelaskan cara menerapkan pengendali callback otorisasi OAuth 2.0 menggunakan servlet Java melalui contoh aplikasi web yang akan menampilkan tugas pengguna menggunakan Google Tasks API. Aplikasi contoh akan meminta otorisasi terlebih dahulu untuk mengakses Google Tasks pengguna, lalu akan menampilkan tugas pengguna dalam daftar tugas default.
Audiens
Dokumen ini disesuaikan untuk orang yang memahami arsitektur aplikasi web Java dan J2EE. Sebaiknya Anda memiliki pengetahuan tentang alur otorisasi OAuth 2.0.
Daftar Isi
Agar memiliki contoh yang berfungsi sepenuhnya, Anda perlu melakukan beberapa langkah berikut:
- Mendeklarasikan pemetaan servlet dalam file web.xml
- Melakukan autentikasi pengguna di sistem Anda dan meminta otorisasi untuk mengakses Tugasnya
- Memproses Kode otorisasi dari endpoint Otorisasi Google
- Menukar kode otorisasi dengan token akses dan refresh
- Membaca tugas pengguna dan menampilkannya
Mendeklarasikan pemetaan servlet dalam file web.xml
Kita akan menggunakan 2 servlet dalam aplikasi:
- PrintTasksTitlesServlet (dipetakan ke /): Titik entri aplikasi yang akan menangani autentikasi pengguna, dan akan menampilkan tugas pengguna
- OAuthCodeCallbackHandlerServlet (dipetakan ke /oauth2callback): Callback OAuth 2.0 yang menangani respons dari endpoint otorisasi OAuth
Berikut adalah file web.xml yang memetakan 2 servlet ini ke URL di aplikasi kita:
<?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>
Mengautentikasi pengguna di sistem Anda dan meminta otorisasi untuk mengakses tugasnya
Pengguna memasuki aplikasi melalui URL root '/' yang dipetakan ke servlet PrintTaskListsTitlesServlet. Dalam servlet tersebut, tugas berikut dilakukan:
- Memeriksa apakah pengguna diautentikasi di sistem
- Jika pengguna tidak diautentikasi, ia akan dialihkan ke halaman autentikasi
- Jika pengguna diautentikasi, kita akan memeriksa apakah kita sudah memiliki token refresh di penyimpanan data kita - yang ditangani oleh OAuthTokenDao di bawah. Jika tidak ada token refresh yang disimpan untuk pengguna, artinya pengguna belum memberikan otorisasi aplikasi untuk mengakses tugasnya. Dalam hal ini, pengguna akan dialihkan ke endpoint Otorisasi OAuth 2.0 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; } }
Catatan: Implementasi di atas menggunakan beberapa library App Engine, yang digunakan untuk menyederhanakan. Jika Anda mengembangkan untuk platform lain, jangan ragu untuk menerapkan ulang antarmuka UserService yang menangani autentikasi pengguna.
Aplikasi menggunakan DAO untuk mempertahankan dan mengakses token otorisasi pengguna. Berikut adalah antarmuka - OAuthTokenDao - dan implementasi tiruan (dalam memori) - OAuthTokenDaoMemoryImpl - yang digunakan dalam contoh ini:
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); } }
Selain itu, kredensial OAuth 2.0 untuk aplikasi disimpan dalam file properti. Atau, Anda dapat memilikinya sebagai konstanta di salah satu class Java, meskipun berikut adalah class OAuthProperties dan file oauth.properties yang digunakan dalam contoh:
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 { } }
Berikut adalah file oauth.properties yang berisi kredensial OAuth 2.0 aplikasi Anda. Anda harus mengubah nilai di bawah ini sendiri.
# 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
Client ID dan Rahasia klien OAuth 2.0 mengidentifikasi aplikasi Anda dan memungkinkan Tasks API menerapkan filter dan aturan kuota yang ditentukan untuk aplikasi Anda. Client ID dan secret dapat ditemukan di Konsol Google API. Setelah berada di konsol, Anda harus:
- Buat atau pilih project.
- Aktifkan Tasks API dengan mengalihkan status Tasks API ke AKTIF dalam daftar layanan.
- Di bagian Akses API, buat Client ID OAuth 2.0 jika belum dibuat.
- Pastikan URL pengendali callback kode OAuth 2.0 project terdaftar/diizinkan di URI Pengalihan. Misalnya, dalam project contoh ini, Anda harus mendaftarkan https://www.example.com/oauth2callback jika aplikasi web Anda ditayangkan dari domain https://www.example.com.

Memproses Kode otorisasi dari endpoint Otorisasi Google
Jika pengguna belum memberikan otorisasi kepada aplikasi untuk mengakses tugasnya, sehingga dialihkan ke endpoint Otorisasi OAuth 2.0 Google, pengguna akan melihat dialog otorisasi dari Google yang meminta pengguna untuk memberikan akses aplikasi Anda ke tugasnya:

Setelah memberikan atau menolak akses, pengguna akan dialihkan kembali ke pengendali callback kode OAuth 2.0 yang telah ditentukan sebagai pengalihan/callback saat membuat URL otorisasi Google:
new GoogleAuthorizationRequestUrl(oauthProperties.getClientId(), OAuthCodeCallbackHandlerServlet.getOAuthCodeCallbackHandlerUrl(req), oauthProperties .getScopesAsString()).build()
Pengendali callback kode OAuth 2.0 - OAuthCodeCallbackHandlerServlet - menangani pengalihan dari endpoint OAuth 2.0 Google. Ada 2 kasus yang harus ditangani:
- Pengguna telah memberikan akses: mengurai permintaan untuk mendapatkan kode OAuth 2.0 dari parameter URL
- Pengguna telah menolak akses: menampilkan pesan kepada pengguna
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; } }
Menukar kode otorisasi dengan token refresh dan akses
Kemudian, OAuthCodeCallbackHandlerServlet menukar kode Auth 2.0 dengan token refresh dan akses, menyimpannya di datastore, dan mengalihkan pengguna kembali ke URL PrintTaskListsTitlesServlet:
Kode yang ditambahkan ke file di bawah ini adalah sintaksis yang ditandai, kode yang sudah ada berwarna abu-abu.
/** URL tujuan pengalihan pengguna setelah menangani callback. Pertimbangkan untuk * menyimpannya dalam cookie sebelum mengalihkan pengguna ke URL * otorisasi Google jika Anda memiliki beberapa kemungkinan URL untuk mengalihkan pengguna. */ public static final String REDIRECT_URL = "/"; /** Implementasi DAO Token OAuth. Pertimbangkan untuk memasukkannya, bukan menggunakan * inisialisasi statis. Selain itu, kita menggunakan implementasi memori sederhana * sebagai tiruan. Ubah implementasi untuk menggunakan sistem database Anda. */ public static OAuthTokenDao oauthTokenDao = new OAuthTokenDaoMemoryImpl(); 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";// Membuat URL permintaan masuk String requestUrl = getOAuthCodeCallbackHandlerUrl(req); // Menukar kode dengan token OAuth AccessTokenResponse accessTokenResponse = exchangeCodeForAccessAndRefreshTokens(code[0], requestUrl); // Mendapatkan pengguna saat ini // Ini menggunakan Layanan Pengguna App Engine, tetapi Anda harus menggantinya dengan // implementasi login/pengguna Anda sendiri UserService userService = UserServiceFactory.getUserService(); String email = userService.getCurrentUser().getEmail(); // Menyimpan 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; }/** * Menukarkan kode yang diberikan untuk pertukaran dan token refresh. * * @param code Kode yang diperoleh dari layanan otorisasi * @param currentUrl URL callback * @param oauthProperties Objek yang berisi konfigurasi OAuth * @return Objek yang berisi token akses dan token refresh * @throws IOException */ public AccessTokenResponse exchangeCodeForAccessAndRefreshTokens(String code, String currentUrl) throws IOException { HttpTransport httpTransport = new NetHttpTransport(); JacksonFactory jsonFactory = new JacksonFactory(); // Memuat file konfigurasi 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.javaCatatan: Implementasi di atas menggunakan beberapa library App Engine, yang digunakan untuk menyederhanakan. Jika Anda mengembangkan untuk platform lain, jangan ragu untuk menerapkan ulang antarmuka UserService yang menangani autentikasi pengguna.
Membaca tugas pengguna dan menampilkannya
Pengguna telah memberikan akses ke tugasnya kepada aplikasi. Aplikasi memiliki token refresh yang disimpan di datastore yang dapat diakses melalui OAuthTokenDao. Servlet PrintTaskListsTitlesServlet kini dapat menggunakan token ini untuk mengakses tugas pengguna dan menampilkannya:
Kode yang ditambahkan ke file di bawah ini adalah sintaksis yang ditandai, kode yang sudah ada berwarna abu-abu.
// Mencetak judul daftar tugas pengguna dalam respons resp.setContentType("text/plain"); resp.getWriter().append("Task Lists titles for user " + user.getEmail() + ":\n\n"); printTasksTitles(accessTokenResponse, resp.getWriter()); 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; }/** * Menggunakan Google Tasks API untuk mengambil daftar tugas pengguna dalam daftar tugas * default. * * @param accessTokenResponse Objek AccessTokenResponse OAuth 2.0 * yang berisi token akses dan token refresh. * @param output penulis aliran output tempat menulis judul daftar tugas * @return Daftar judul tugas pengguna dalam daftar tugas default. * @throws IOException */ public void printTasksTitles(AccessTokenResponse accessTokenResponse, Writer output) throws IOException { // Melakukan inisialisasi layanan 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); // Menggunakan layanan Tasks API yang diinisialisasi untuk membuat kueri daftar daftar tugas 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.javaPengguna akan ditampilkan dengan tugasnya:
Tugas penggunaContoh aplikasi
Kode untuk aplikasi contoh ini dapat didownload di sini. Silakan lihat.