Search in sources :

Example 1 with OAuthRequestException

use of com.google.appengine.api.oauth.OAuthRequestException in project java-docs-samples by GoogleCloudPlatform.

the class Oauth2Filter method doFilter.

// [START oauth2]
@Override
public void doFilter(final ServletRequest servletReq, final ServletResponse servletResp, final FilterChain chain) throws IOException, ServletException {
    final String scope = "https://www.googleapis.com/auth/userinfo.email";
    ImmutableSet<String> allowedClients = new ImmutableSet.Builder<String>().add("407408718192.apps.googleusercontent.com").add("755878275993-j4k7emq6rlupctce1c28enpcrr50vfo1.apps.googleusercontent.com").build();
    HttpServletResponse resp = (HttpServletResponse) servletResp;
    OAuthService oauth = OAuthServiceFactory.getOAuthService();
    // Only check Oauth2 when in production, skip if run in development.
    SystemProperty.Environment.Value env = environment.value();
    if (env == SystemProperty.Environment.Value.Production) {
        // APIs only work in Production
        try {
            String tokenAudience = oauth.getClientId(scope);
            if (!allowedClients.contains(tokenAudience)) {
                throw new OAuthRequestException("audience of token '" + tokenAudience + "' is not in allowed list " + allowedClients);
            }
        } catch (OAuthRequestException ex) {
            // Not allowed
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        } catch (OAuthServiceFailureException ex) {
            // some failure - reject
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            context.log("oauth2 failure", ex);
            return;
        }
    }
    // continue processing
    chain.doFilter(servletReq, servletResp);
}
Also used : OAuthService(com.google.appengine.api.oauth.OAuthService) OAuthRequestException(com.google.appengine.api.oauth.OAuthRequestException) ImmutableSet(com.google.common.collect.ImmutableSet) OAuthServiceFailureException(com.google.appengine.api.oauth.OAuthServiceFailureException) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 2 with OAuthRequestException

use of com.google.appengine.api.oauth.OAuthRequestException in project endpoints-java by cloudendpoints.

the class GoogleAppEngineAuthenticator method getOAuth2User.

@VisibleForTesting
com.google.appengine.api.users.User getOAuth2User(HttpServletRequest request, ApiMethodConfig config) throws ServiceUnavailableException {
    String token = GoogleAuth.getAuthToken(request);
    if (!GoogleAuth.isOAuth2Token(token)) {
        return null;
    }
    AuthScopeExpression scopeExpression = config.getScopeExpression();
    String[] allScopes = scopeExpression.getAllScopes();
    String clientId = null;
    if (EnvUtil.isRunningOnAppEngineProd()) {
        try {
            String[] authorizedScopes = oauthService.getAuthorizedScopes(allScopes);
            boolean authorized = false;
            if (authorizedScopes != null) {
                // Authorize against the scopes based on the scope expression.
                authorized = scopeExpression.isAuthorized(ImmutableSet.copyOf(authorizedScopes));
            }
            if (!authorized) {
                logger.atWarning().log("Access token does not contain sufficient scopes from: %s", scopeExpression);
                return null;
            }
            clientId = oauthService.getClientId(allScopes);
        } catch (OAuthRequestException e) {
            logger.atWarning().withCause(e).log("Failed to get client id for '%s'", scopeExpression);
            return null;
        }
    } else {
        // Dev env.
        clientId = getOAuth2ClientIdDev(token);
    }
    // Check client id.
    if ((Attribute.from(request).isEnabled(Attribute.ENABLE_CLIENT_ID_WHITELIST) && !GoogleAuth.checkClientId(clientId, config.getClientIds(), true))) {
        logger.atWarning().log("ClientId is not allowed: %s", clientId);
        return null;
    }
    try {
        com.google.appengine.api.users.User appEngineUser = oauthService.getCurrentUser(allScopes);
        return appEngineUser;
    } catch (OAuthRequestException e) {
        logger.atWarning().withCause(e).log("Failed to get user for '%s'", scopeExpression);
    }
    return null;
}
Also used : OAuthRequestException(com.google.appengine.api.oauth.OAuthRequestException) AuthScopeExpression(com.google.api.server.spi.config.scope.AuthScopeExpression) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 3 with OAuthRequestException

use of com.google.appengine.api.oauth.OAuthRequestException in project endpoints-java by cloudendpoints.

the class GoogleAppEngineAuthenticatorTest method testGetOAuth2UserAppEngineProdClientIdNotAllowed.

@Test
public void testGetOAuth2UserAppEngineProdClientIdNotAllowed() throws Exception {
    when(config.getScopeExpression()).thenReturn(AuthScopeExpressions.interpret(SCOPES));
    when(oauthService.getAuthorizedScopes(SCOPES)).thenReturn(SCOPES);
    when(oauthService.getClientId(SCOPES)).thenThrow(new OAuthRequestException("any")).thenReturn(null).thenReturn(CLIENT_ID);
    when(config.getClientIds()).thenReturn(ImmutableList.of("clientId2"));
    for (int i = 0; i < 3; i++) {
        assertNull(authenticator.getOAuth2User(request, config));
    }
}
Also used : OAuthRequestException(com.google.appengine.api.oauth.OAuthRequestException) Test(org.junit.Test)

Example 4 with OAuthRequestException

use of com.google.appengine.api.oauth.OAuthRequestException in project java-docs-samples by GoogleCloudPlatform.

the class HelloServlet method doPost.

@Override
public void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException {
    resp.setContentType("text/plain");
    PrintWriter out = resp.getWriter();
    final String scope = "https://www.googleapis.com/auth/userinfo.email";
    OAuthService oauth = OAuthServiceFactory.getOAuthService();
    User user = null;
    try {
        user = oauth.getCurrentUser(scope);
    } catch (OAuthRequestException e) {
        getServletContext().log("Oauth error", e);
        out.print("auth error");
        return;
    }
    out.print("Hello world, welcome to Oauth2: " + user.getEmail());
}
Also used : OAuthService(com.google.appengine.api.oauth.OAuthService) User(com.google.appengine.api.users.User) OAuthRequestException(com.google.appengine.api.oauth.OAuthRequestException) PrintWriter(java.io.PrintWriter)

Example 5 with OAuthRequestException

use of com.google.appengine.api.oauth.OAuthRequestException in project endpoints-java by cloudendpoints.

the class GoogleAppEngineAuthenticatorTest method testGetOAuth2UserScopeNotAllowed.

@Test
public void testGetOAuth2UserScopeNotAllowed() throws Exception {
    when(config.getScopeExpression()).thenReturn(AuthScopeExpressions.interpret(SCOPES));
    when(oauthService.getAuthorizedScopes(SCOPES)).thenThrow(new OAuthRequestException("any")).thenReturn(null).thenReturn(new String[] { "scope3" });
    for (int i = 0; i < 3; i++) {
        assertNull(authenticator.getOAuth2User(request, config));
    }
}
Also used : OAuthRequestException(com.google.appengine.api.oauth.OAuthRequestException) Test(org.junit.Test)

Aggregations

OAuthRequestException (com.google.appengine.api.oauth.OAuthRequestException)5 OAuthService (com.google.appengine.api.oauth.OAuthService)2 Test (org.junit.Test)2 AuthScopeExpression (com.google.api.server.spi.config.scope.AuthScopeExpression)1 OAuthServiceFailureException (com.google.appengine.api.oauth.OAuthServiceFailureException)1 User (com.google.appengine.api.users.User)1 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 PrintWriter (java.io.PrintWriter)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1