/** * Authenticate the given user. If you are distributing an installed application, this method * should exist on your server so that the client ID and secret are not shared with the end * user. */ private static Credential authenticate(String userId, SessionConfiguration config) throws Exception { OAuth2Credentials oAuth2Credentials = createOAuth2Credentials(config); // First try to load an existing Credential. If that credential is null, authenticate the user. Credential credential = oAuth2Credentials.loadCredential(userId); if (credential == null || credential.getAccessToken() == null) { // Send user to authorize your application. System.out.printf("Add the following redirect URI to your developer.uber.com application: %s%n", oAuth2Credentials.getRedirectUri()); System.out.println("Press Enter when done."); System.in.read(); // Generate an authorization URL. String authorizationUrl = oAuth2Credentials.getAuthorizationUrl(); System.out.printf("In your browser, navigate to: %s%n", authorizationUrl); System.out.println("Waiting for authentication..."); // Wait for the authorization code. String authorizationCode = localServerReceiver.waitForCode(); System.out.println("Authentication received."); // Authenticate the user with the authorization code. credential = oAuth2Credentials.authenticate(authorizationCode, userId); } localServerReceiver.stop(); return credential; }
@Test public void clearCredential() throws Exception { OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder() .setClientSecrets("CLIENT_ID", "CLIENT_SECRET") .setRedirectUri("http://redirect") .setHttpTransport(mockHttpTransport) .setScopes(Arrays.asList(Scope.PROFILE, Scope.REQUEST)) .build(); oAuth2Credentials.authenticate("authorizationCode", "userId"); Credential credential = oAuth2Credentials.loadCredential("userId"); assertNotNull(credential); oAuth2Credentials.clearCredential("userId"); credential = oAuth2Credentials.loadCredential("userId"); assertNull(credential); }
httpSession.setAttribute(Server.USER_SESSION_ID, new Random().nextLong()); credential = oAuth2Credentials.loadCredential(httpSession.getAttribute(Server.USER_SESSION_ID).toString()); resp.sendRedirect(oAuth2Credentials.getAuthorizationUrl());
@Test public void loadCredential() throws Exception { OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder() .setClientSecrets("CLIENT_ID", "CLIENT_SECRET") .setRedirectUri("http://redirect") .setHttpTransport(mockHttpTransport) .setScopes(Arrays.asList(Scope.PROFILE, Scope.REQUEST)) .build(); oAuth2Credentials.authenticate("authorizationCode", "userId"); Credential credential = oAuth2Credentials.loadCredential("userId"); assertEquals("Refresh token does not match.", "refreshToken", credential.getRefreshToken()); assertTrue("Expected expires_in between 0 and 3600. Was actually: " + credential.getExpiresInSeconds(), credential.getExpiresInSeconds() > 0 && credential.getExpiresInSeconds() <= 3600); assertEquals("Access token does not match.", "accessToken", credential.getAccessToken()); assertEquals("Access method (Bearer) does not match", BearerToken.authorizationHeaderAccessMethod().getClass(), credential.getMethod().getClass()); }
@Test public void getAuthorizationUrl_whenThereAreCustomScopes() throws Exception { OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder() .setClientSecrets("CLIENT_ID", "CLIENT_SECRET") .setScopes(Arrays.asList(Scope.PROFILE)) .setCustomScopes(Arrays.asList("custom")) .build(); assertTrue( "https://login.uber.com/oauth/v2/authorize?client_id=CLIENT_ID&response_type=code&scope=custom%20profile" .equals(oAuth2Credentials.getAuthorizationUrl()) || "https://login.uber.com/oauth/v2/authorize?client_id=CLIENT_ID&response_type=code&scope=profile%20custom" .equals(oAuth2Credentials.getAuthorizationUrl())); }
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String requestUrl = req.getRequestURL().append('?').append(req.getQueryString()).toString(); AuthorizationCodeResponseUrl authorizationCodeResponseUrl = new AuthorizationCodeResponseUrl(requestUrl); if (authorizationCodeResponseUrl.getError() != null) { throw new IOException("Received error: " + authorizationCodeResponseUrl.getError()); } else { // Authenticate the user and store their credential with their user ID (derived from // the request). HttpSession httpSession = req.getSession(true); if (httpSession.getAttribute(Server.USER_SESSION_ID) == null) { httpSession.setAttribute(Server.USER_SESSION_ID, new Random().nextLong()); } String authorizationCode = authorizationCodeResponseUrl.getCode(); oAuth2Credentials.authenticate(authorizationCode, httpSession.getAttribute(Server.USER_SESSION_ID).toString()); } resp.sendRedirect("/"); } }
OAuth2Credentials oAuth2Credentials = new OAuth2Credentials(); oAuth2Credentials.redirectUri = redirectUri;
.build(); Credential storedCredential = oAuth2Credentials.authenticate("authorizationCode", "userId"); Credential loadedCredential = oAuth2Credentials.loadCredential("userId");
@Test public void getAuthorizationUrl_whenThereAreDuplicateCustomScopes() throws Exception { OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder() .setClientSecrets("CLIENT_ID", "CLIENT_SECRET") .setScopes(Arrays.asList(Scope.PROFILE)) .setCustomScopes(Arrays.asList("profile")) .build(); assertEquals("https://login.uber.com/oauth/v2/authorize?client_id=CLIENT_ID&response_type=code&scope=profile", oAuth2Credentials.getAuthorizationUrl()); }
@Test public void authenticate() throws Exception { String authorizationCode = "authorizationCode"; String expectedRequestContent = "code=authorizationCode&grant_type=authorization_code" + "&redirect_uri=http%3A%2F%2Fredirect&scope=profile+request" + "&client_id=CLIENT_ID&client_secret=CLIENT_SECRET"; OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder() .setClientSecrets("CLIENT_ID", "CLIENT_SECRET") .setRedirectUri("http://redirect") .setHttpTransport(mockHttpTransport) .setScopes(Arrays.asList(Scope.PROFILE, Scope.REQUEST)) .build(); Credential credential = oAuth2Credentials.authenticate(authorizationCode, "userId"); assertEquals("Request URL did not match.", TOKEN_REQUEST_URL, mockHttpTransport.lastRequestUrl); assertEquals("Request content did not match.", expectedRequestContent, mockHttpTransport.lastRequestContent); assertEquals("Refresh token does not match.", "refreshToken", credential.getRefreshToken()); assertTrue("Expected expires_in between 0 and 3600. Was actually: " + credential.getExpiresInSeconds(), credential.getExpiresInSeconds() > 0 && credential.getExpiresInSeconds() <= 3600); assertEquals("Access token does not match.", "accessToken", credential.getAccessToken()); assertEquals("Access method (Bearer) does not match", BearerToken.authorizationHeaderAccessMethod().getClass(), credential.getMethod().getClass()); }
@Test public void getAuthorizationUrl_whenThereIsARedirectUri() throws Exception { OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder() .setClientSecrets("CLIENT_ID", "CLIENT_SECRET") .setRedirectUri("https://localhost:8181/OAuth2Callback") .setScopes(Arrays.asList(Scope.PROFILE)) .setCustomScopes(Arrays.asList("profile")) .build(); assertEquals("https://login.uber.com/oauth/v2/authorize?client_id=CLIENT_ID" + "&response_type=code&scope=profile&redirect_uri=https%3A%2F%2Flocalhost%3A8181%2FOAuth2Callback", oAuth2Credentials.getAuthorizationUrl()); }
@Test public void authenticate_whenThereAreNoScopes() throws Exception { String authorizationCode = "authorizationCode"; String expectedRequestContent = "code=authorizationCode&grant_type=authorization_code" + "&redirect_uri=http%3A%2F%2Fredirect" + "&client_id=CLIENT_ID&client_secret=CLIENT_SECRET"; OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder() .setClientSecrets("CLIENT_ID", "CLIENT_SECRET") .setRedirectUri("http://redirect") .setHttpTransport(mockHttpTransport) .build(); Credential credential = oAuth2Credentials.authenticate(authorizationCode, "userId"); assertEquals("Request URL did not match.", TOKEN_REQUEST_URL, mockHttpTransport.lastRequestUrl); assertEquals("Request content did not match.", expectedRequestContent, mockHttpTransport.lastRequestContent); assertEquals("Refresh token does not match.", "refreshToken", credential.getRefreshToken()); assertTrue("Expected expires_in between 0 and 3600. Was actually: " + credential.getExpiresInSeconds(), credential.getExpiresInSeconds() > 0 && credential.getExpiresInSeconds() <= 3600); assertEquals("Access token does not match.", "accessToken", credential.getAccessToken()); assertEquals("Access method (Bearer) does not match", BearerToken.authorizationHeaderAccessMethod().getClass(), credential.getMethod().getClass()); }
@Test public void getAuthorizationUrl() throws Exception { OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder() .setClientSecrets("CLIENT_ID", "CLIENT_SECRET") .setScopes(Arrays.asList(Scope.PROFILE, Scope.REQUEST, Scope.HISTORY)) .build(); assertEquals("https://login.uber.com/oauth/v2/authorize?client_id=CLIENT_ID" + "&response_type=code&scope=history%20profile%20request", oAuth2Credentials.getAuthorizationUrl()); }
@Test public void authenticate_whenCantAuthenticate_shouldThrowException() throws Exception { exception.expect(AuthException.class); exception.expectCause(any(IOException.class)); String authorizationCode = "authorizationCode"; mockHttpTransport.setHttpResponseContent("failed"); mockHttpTransport.setHttpStatusCode(403); OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder() .setClientSecrets("CLIENT_ID", "CLIENT_SECRET") .setRedirectUri("http://redirect") .setHttpTransport(mockHttpTransport) .build(); oAuth2Credentials.authenticate(authorizationCode, "userId"); }
@Test public void getAuthorizationUrl_whenThereIsAnEmptyScopeList() throws Exception { OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder() .setClientSecrets("CLIENT_ID", "CLIENT_SECRET") .setScopes(new ArrayList<Scope>()) .build(); assertEquals("https://login.uber.com/oauth/v2/authorize?client_id=CLIENT_ID&response_type=code", oAuth2Credentials.getAuthorizationUrl()); }
@Test public void getAuthorizationUrl_whenThereAreNoScopes() throws Exception { OAuth2Credentials oAuth2Credentials = new OAuth2Credentials.Builder() .setClientSecrets("CLIENT_ID", "CLIENT_SECRET") .build(); assertEquals("https://login.uber.com/oauth/v2/authorize?client_id=CLIENT_ID&response_type=code", oAuth2Credentials.getAuthorizationUrl()); }