Search in sources :

Example 1 with Oauth2Credentials

use of io.vertx.ext.auth.oauth2.Oauth2Credentials in project google-auth-library-java by google.

the class HttpCredentialsAdapterTest method initialize_noURI.

@Test
public void initialize_noURI() throws IOException {
    final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2";
    final String expectedAuthorization = InternalAuthHttpConstants.BEARER_PREFIX + accessToken;
    MockTokenServerTransportFactory tokenServerTransportFactory = new MockTokenServerTransportFactory();
    tokenServerTransportFactory.transport.addClient(CLIENT_ID, CLIENT_SECRET);
    tokenServerTransportFactory.transport.addRefreshToken(REFRESH_TOKEN, accessToken);
    OAuth2Credentials credentials = UserCredentials.newBuilder().setClientId(CLIENT_ID).setClientSecret(CLIENT_SECRET).setRefreshToken(REFRESH_TOKEN).setHttpTransportFactory(tokenServerTransportFactory).build();
    HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(credentials);
    HttpRequestFactory requestFactory = tokenServerTransportFactory.transport.createRequestFactory();
    HttpRequest request = requestFactory.buildGetRequest(null);
    adapter.initialize(request);
    HttpHeaders requestHeaders = request.getHeaders();
    String authorizationHeader = requestHeaders.getAuthorization();
    assertEquals(authorizationHeader, expectedAuthorization);
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) MockTokenServerTransportFactory(com.google.auth.oauth2.GoogleCredentialsTest.MockTokenServerTransportFactory) OAuth2Credentials(com.google.auth.oauth2.OAuth2Credentials) Test(org.junit.Test)

Example 2 with Oauth2Credentials

use of io.vertx.ext.auth.oauth2.Oauth2Credentials in project grpc-java by grpc.

the class GoogleAuthLibraryCallCredentialsTest method oauth2Credential.

@Test
public void oauth2Credential() {
    final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
    OAuth2Credentials credentials = new OAuth2Credentials() {

        @Override
        public AccessToken refreshAccessToken() throws IOException {
            return token;
        }
    };
    GoogleAuthLibraryCallCredentials callCredentials = new GoogleAuthLibraryCallCredentials(credentials);
    callCredentials.applyRequestMetadata(new RequestInfoImpl(SecurityLevel.NONE), executor, applier);
    assertEquals(1, runPendingRunnables());
    verify(applier).apply(headersCaptor.capture());
    Metadata headers = headersCaptor.getValue();
    Iterable<String> authorization = headers.getAll(AUTHORIZATION);
    assertArrayEquals(new String[] { "Bearer allyourbase" }, Iterables.toArray(authorization, String.class));
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) Metadata(io.grpc.Metadata) OAuth2Credentials(com.google.auth.oauth2.OAuth2Credentials) Date(java.util.Date) Test(org.junit.Test)

Example 3 with Oauth2Credentials

use of io.vertx.ext.auth.oauth2.Oauth2Credentials in project grpc-java by grpc.

the class AbstractInteropTest method oauth2AuthToken.

/**
 * Sends a unary rpc with raw oauth2 access token credentials.
 */
public void oauth2AuthToken(String jsonKey, InputStream credentialsStream, String authScope) throws Exception {
    GoogleCredentials utilCredentials = GoogleCredentials.fromStream(credentialsStream);
    utilCredentials = utilCredentials.createScoped(Arrays.asList(authScope));
    AccessToken accessToken = utilCredentials.refreshAccessToken();
    OAuth2Credentials credentials = OAuth2Credentials.create(accessToken);
    TestServiceGrpc.TestServiceBlockingStub stub = blockingStub.withCallCredentials(MoreCallCredentials.from(credentials));
    final SimpleRequest request = SimpleRequest.newBuilder().setFillUsername(true).setFillOauthScope(true).build();
    final SimpleResponse response = stub.unaryCall(request);
    assertFalse(response.getUsername().isEmpty());
    assertTrue("Received username: " + response.getUsername(), jsonKey.contains(response.getUsername()));
    assertFalse(response.getOauthScope().isEmpty());
    assertTrue("Received oauth scope: " + response.getOauthScope(), authScope.contains(response.getOauthScope()));
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) SimpleResponse(io.grpc.testing.integration.Messages.SimpleResponse) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) OAuth2Credentials(com.google.auth.oauth2.OAuth2Credentials) SimpleRequest(io.grpc.testing.integration.Messages.SimpleRequest)

Example 4 with Oauth2Credentials

use of io.vertx.ext.auth.oauth2.Oauth2Credentials in project grpc-java by grpc.

the class ClientAuthInterceptorTest method testWithOAuth2Credential.

@Test
public void testWithOAuth2Credential() {
    final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
    final OAuth2Credentials oAuth2Credentials = new OAuth2Credentials() {

        @Override
        public AccessToken refreshAccessToken() throws IOException {
            return token;
        }
    };
    interceptor = new ClientAuthInterceptor(oAuth2Credentials, executor);
    ClientCall<String, Integer> interceptedCall = interceptor.interceptCall(descriptor, CallOptions.DEFAULT, channel);
    Metadata headers = new Metadata();
    interceptedCall.start(listener, headers);
    assertEquals(listener, call.responseListener);
    assertEquals(headers, call.headers);
    Iterable<String> authorization = headers.getAll(AUTHORIZATION);
    Assert.assertArrayEquals(new String[] { "Bearer allyourbase" }, Iterables.toArray(authorization, String.class));
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) Metadata(io.grpc.Metadata) OAuth2Credentials(com.google.auth.oauth2.OAuth2Credentials) Date(java.util.Date) Test(org.junit.Test)

Example 5 with Oauth2Credentials

use of io.vertx.ext.auth.oauth2.Oauth2Credentials in project vertx-web by vert-x3.

the class OAuth2AuthHandlerImpl method setupCallback.

@Override
public OAuth2AuthHandler setupCallback(final Route route) {
    if (callbackURL == null) {
        // warn that the setup is probably wrong
        throw new IllegalStateException("OAuth2AuthHandler was created without a origin/callback URL");
    }
    final String routePath = route.getPath();
    if (routePath == null) {
        // warn that the setup is probably wrong
        throw new IllegalStateException("OAuth2AuthHandler callback route created without a path");
    }
    final String callbackPath = callbackURL.resource();
    if (callbackPath != null && !"".equals(callbackPath)) {
        if (!callbackPath.endsWith(routePath)) {
            if (LOG.isWarnEnabled()) {
                LOG.warn("callback route doesn't match OAuth2AuthHandler origin configuration");
            }
        }
    }
    route.method(HttpMethod.GET);
    route.handler(ctx -> {
        // Some IdP's (e.g.: AWS Cognito) returns errors as query arguments
        String error = ctx.request().getParam("error");
        if (error != null) {
            int errorCode;
            // standard error's from the Oauth2 RFC
            switch(error) {
                case "invalid_token":
                    errorCode = 401;
                    break;
                case "insufficient_scope":
                    errorCode = 403;
                    break;
                case "invalid_request":
                default:
                    errorCode = 400;
                    break;
            }
            String errorDescription = ctx.request().getParam("error_description");
            if (errorDescription != null) {
                ctx.fail(errorCode, new IllegalStateException(error + ": " + errorDescription));
            } else {
                ctx.fail(errorCode, new IllegalStateException(error));
            }
            return;
        }
        // Handle the callback of the flow
        final String code = ctx.request().getParam("code");
        // code is a require value
        if (code == null) {
            ctx.fail(400, new IllegalStateException("Missing code parameter"));
            return;
        }
        final Oauth2Credentials credentials = new Oauth2Credentials().setCode(code);
        // the state that was passed to the IdP server. The state can be
        // an opaque random string (to protect against replay attacks)
        // or if there was no session available the target resource to
        // server after validation
        final String state = ctx.request().getParam("state");
        // state is a required field
        if (state == null) {
            ctx.fail(400, new IllegalStateException("Missing IdP state parameter to the callback endpoint"));
            return;
        }
        final String resource;
        final Session session = ctx.session();
        if (session != null) {
            // validate the state. Here we are a bit lenient, if there is no session
            // we always assume valid, however if there is session it must match
            String ctxState = session.remove("state");
            // if there's a state in the context they must match
            if (!state.equals(ctxState)) {
                // forbidden, the state is not valid (this is a replay attack)
                ctx.fail(401, new IllegalStateException("Invalid oauth2 state"));
                return;
            }
            // remove the code verifier, from the session as it will be trade for the
            // token during the final leg of the oauth2 handshake
            String codeVerifier = session.remove("pkce");
            credentials.setCodeVerifier(codeVerifier);
            // state is valid, extract the redirectUri from the session
            resource = session.get("redirect_uri");
        } else {
            resource = state;
        }
        // The valid callback URL set in your IdP application settings.
        // This must exactly match the redirect_uri passed to the authorization URL in the previous step.
        credentials.setRedirectUri(callbackURL.href());
        authProvider.authenticate(credentials, res -> {
            if (res.failed()) {
                ctx.fail(res.cause());
            } else {
                ctx.setUser(res.result());
                String location = resource != null ? resource : "/";
                if (session != null) {
                    // the user has upgraded from unauthenticated to authenticated
                    // session should be upgraded as recommended by owasp
                    session.regenerateId();
                } else {
                    // we will reroute to "location"
                    if (location.length() != 0 && location.charAt(0) == '/') {
                        ctx.reroute(location);
                        return;
                    }
                }
                // we should redirect the UA so this link becomes invalid
                ctx.response().putHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate").putHeader("Pragma", "no-cache").putHeader(HttpHeaders.EXPIRES, "0").putHeader(HttpHeaders.LOCATION, location).setStatusCode(302).end("Redirecting to " + location + ".");
            }
        });
    });
    // the redirect handler has been setup so we can process this
    // handler has full oauth2
    bearerOnly = false;
    return this;
}
Also used : Oauth2Credentials(io.vertx.ext.auth.oauth2.Oauth2Credentials) Session(io.vertx.ext.web.Session)

Aggregations

OAuth2Credentials (com.google.auth.oauth2.OAuth2Credentials)6 Test (org.junit.Test)5 HttpRequest (com.google.api.client.http.HttpRequest)3 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)3 AccessToken (com.google.auth.oauth2.AccessToken)3 MockTokenServerTransportFactory (com.google.auth.oauth2.GoogleCredentialsTest.MockTokenServerTransportFactory)3 GenericUrl (com.google.api.client.http.GenericUrl)2 HttpHeaders (com.google.api.client.http.HttpHeaders)2 Metadata (io.grpc.Metadata)2 Date (java.util.Date)2 HttpResponse (com.google.api.client.http.HttpResponse)1 HttpTransport (com.google.api.client.http.HttpTransport)1 GoogleCredentials (com.google.auth.oauth2.GoogleCredentials)1 MockTokenCheckingTransport (com.google.auth.oauth2.MockTokenCheckingTransport)1 SimpleRequest (io.grpc.testing.integration.Messages.SimpleRequest)1 SimpleResponse (io.grpc.testing.integration.Messages.SimpleResponse)1 Oauth2Credentials (io.vertx.ext.auth.oauth2.Oauth2Credentials)1 Session (io.vertx.ext.web.Session)1