com.linecorp.armeria.common.auth.OAuth2Token Java Examples

The following examples show how to use com.linecorp.armeria.common.auth.OAuth2Token. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SessionTokenAuthorizer.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@Override
public CompletionStage<Boolean> authorize(ServiceRequestContext ctx, HttpRequest data) {
    final OAuth2Token token = AuthTokenExtractors.oAuth2().apply(data.headers());
    if (token == null) {
        return completedFuture(false);
    }
    return sessionManager.get(token.accessToken())
                         .thenApply(session -> {
                             if (session == null) {
                                 return false;
                             }
                             final String username = session.username();
                             final List<String> roles = administrators.contains(username) ? LEVEL_ADMIN
                                                                                          : LEVEL_USER;
                             final User user = new User(username, roles);
                             AuthUtil.setCurrentUser(ctx, user);
                             return true;
                         });
}
 
Example #2
Source File: GoogleIdAuthorizer.java    From curiostack with MIT License 6 votes vote down vote up
@Override
public CompletionStage<Boolean> authorize(ServiceRequestContext ctx, OAuth2Token data) {
  final GoogleIdToken token;
  try {
    token = GoogleIdToken.parse(JacksonFactory.getDefaultInstance(), data.accessToken());
  } catch (IOException e) {
    logger.info("Could not parse id token {}", data.accessToken());
    return completedFuture(false);
  }
  return verifier
      .verify(token)
      .thenApply(
          result -> {
            if (!result) {
              logger.info("Invalid signature.");
              return false;
            }
            if (!commonNamesProvider.get().contains(token.getPayload().getEmail())) {
              logger.info("Rejecting client: {}", token.getPayload().getEmail());
              return false;
            }
            return true;
          });
}
 
Example #3
Source File: AuthServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testOAuth2() throws Exception {
    final WebClient webClient = WebClient.builder(server.httpUri())
                                         .auth(OAuth2Token.of("dummy_oauth2_token"))
                                         .build();
    assertThat(webClient.get("/oauth2").aggregate().join().status()).isEqualTo(HttpStatus.OK);
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        try (CloseableHttpResponse res = hc.execute(
                oauth2GetRequest("/oauth2-custom", OAuth2Token.of("dummy_oauth2_token"),
                                 CUSTOM_TOKEN_HEADER))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
        }
        try (CloseableHttpResponse res = hc.execute(
                oauth2GetRequest("/oauth2", OAuth2Token.of("DUMMY_oauth2_token"), AUTHORIZATION))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 401 Unauthorized");
        }
    }
}
 
Example #4
Source File: OAuth2TokenExtractor.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public OAuth2Token apply(RequestHeaders headers) {
    final String authorization = requireNonNull(headers, "headers").get(header);
    if (Strings.isNullOrEmpty(authorization)) {
        return null;
    }

    final Matcher matcher = AUTHORIZATION_HEADER_PATTERN.matcher(authorization);
    if (!matcher.matches()) {
        logger.warn("Invalid authorization header: " + authorization);
        return null;
    }

    return OAuth2Token.of(matcher.group("accessToken"));
}
 
Example #5
Source File: ApplicationTokenAuthorizer.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Override
public CompletionStage<Boolean> authorize(ServiceRequestContext ctx, HttpRequest data) {
    final OAuth2Token token = AuthTokenExtractors.oAuth2().apply(data.headers());
    if (token == null || !Tokens.isValidSecret(token.accessToken())) {
        return completedFuture(false);
    }

    final CompletableFuture<Boolean> res = new CompletableFuture<>();
    tokenLookupFunc.apply(token.accessToken())
                   .thenAccept(appToken -> {
                       if (appToken != null && appToken.isActive()) {
                           final StringBuilder login = new StringBuilder(appToken.appId());
                           final SocketAddress ra = ctx.remoteAddress();
                           if (ra instanceof InetSocketAddress) {
                               login.append('@').append(((InetSocketAddress) ra).getHostString());
                           }

                           AuthUtil.setCurrentUser(
                                   ctx, new UserWithToken(login.toString(), appToken));
                           res.complete(true);
                       } else {
                           res.complete(false);
                       }
                   })
                   // Should be authorized by the next authorizer.
                   .exceptionally(voidFunction(cause -> {
                       cause = Exceptions.peel(cause);
                       if (!(cause instanceof IllegalArgumentException)) {
                           logger.warn("Application token authorization failed: {}",
                                       token.accessToken(), cause);
                       }
                       res.complete(false);
                   }));

    return res;
}
 
Example #6
Source File: FirebaseAuthorizer.java    From curiostack with MIT License 5 votes vote down vote up
@Override
public CompletionStage<Boolean> authorize(ServiceRequestContext ctx, OAuth2Token data) {
  CompletableFuture<Boolean> result = new CompletableFuture<>();
  ApiFutures.addCallback(
      firebaseAuth.verifyIdTokenAsync(data.accessToken()),
      new ApiFutureCallback<FirebaseToken>() {
        @Override
        public void onFailure(Throwable t) {
          result.complete(false);
        }

        @Override
        public void onSuccess(FirebaseToken token) {
          if (!token.isEmailVerified() && !config.isAllowUnverifiedEmail()) {
            result.complete(false);
            return;
          }
          if (!config.getAllowedGoogleDomains().isEmpty()) {
            @SuppressWarnings("unchecked")
            Map<String, Object> firebaseClaims =
                (Map<String, Object>) token.getClaims().get("firebase");
            if (!firebaseClaims.get("sign_in_provider").equals("google.com")
                || !config.getAllowedGoogleDomains().contains(getEmailDomain(token.getEmail()))) {
              result.complete(false);
              return;
            }
          }
          ctx.setAttr(FIREBASE_TOKEN, token);
          ctx.setAttr(RAW_FIREBASE_TOKEN, data.accessToken());
          result.complete(true);
        }
      },
      MoreExecutors.directExecutor());
  return result;
}
 
Example #7
Source File: CsrfTokenAuthorizer.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
@Override
public CompletionStage<Boolean> authorize(ServiceRequestContext ctx, HttpRequest data) {
    final OAuth2Token token = AuthTokenExtractors.oAuth2().apply(data.headers());
    if (token != null && CsrfToken.ANONYMOUS.equals(token.accessToken())) {
        AuthUtil.setCurrentUser(ctx, User.ADMIN);
        return CompletableFuture.completedFuture(true);
    } else {
        return CompletableFuture.completedFuture(false);
    }
}
 
Example #8
Source File: JwtAuthorizer.java    From curiostack with MIT License 5 votes vote down vote up
@Override
public CompletionStage<Boolean> authorize(ServiceRequestContext ctx, OAuth2Token data) {
  return verifier
      .verify(data.accessToken())
      .handle(
          (jwt, t) -> {
            if (t != null) {
              return false;
            }
            ctx.setAttr(DECODED_JWT, jwt);
            ctx.setAttr(RAW_JWT, data.accessToken());
            return true;
          });
}
 
Example #9
Source File: AuthServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testArbitraryToken() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        try (CloseableHttpResponse res = hc.execute(
                oauth2GetRequest("/insecuretoken",
                                 OAuth2Token.of("all your tokens are belong to us"), AUTHORIZATION))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
        }
    }
}
 
Example #10
Source File: OAuth2TokenTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void testEquals() {
    assertThat(OAuth2Token.of("a")).isEqualTo(OAuth2Token.of("a"));
    assertThat(OAuth2Token.of("a")).isNotEqualTo(OAuth2Token.of("x"));
    assertThat(OAuth2Token.of("b")).isNotEqualTo(OAuth2Token.of("bb"));
    assertThat(OAuth2Token.of("bb")).isNotEqualTo(OAuth2Token.of("b"));
}
 
Example #11
Source File: EurekaUpdatingListenerBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
public EurekaUpdatingListenerBuilder auth(OAuth2Token token) {
    return (EurekaUpdatingListenerBuilder) super.auth(token);
}
 
Example #12
Source File: EurekaEndpointGroupBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
public EurekaEndpointGroupBuilder auth(OAuth2Token token) {
    return (EurekaEndpointGroupBuilder) super.auth(token);
}
 
Example #13
Source File: AuthServiceTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
private static HttpRequestBase oauth2GetRequest(String path, OAuth2Token oAuth2Token, AsciiString header) {
    final HttpGet request = new HttpGet(server.httpUri().resolve(path));
    request.addHeader(header.toString(), "Bearer " + oAuth2Token.accessToken());
    return request;
}
 
Example #14
Source File: AuthServiceTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void testCompositeAuth() throws Exception {
    try (CloseableHttpClient hc = HttpClients.createMinimal()) {
        try (CloseableHttpResponse res = hc.execute(
                getRequest("/composite", "unit test"))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
        }
        try (CloseableHttpResponse res = hc.execute(
                basicGetRequest("/composite", BasicToken.of("brown", "cony"),
                                AUTHORIZATION))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
        }
        final Map<String, String> passToken = ImmutableMap.<String, String>builder()
                .put("realm", "dummy_realm")
                .put("oauth_consumer_key", "dummy_consumer_key@#$!")
                .put("oauth_token", "dummy_oauth1a_token")
                .put("oauth_signature_method", "dummy")
                .put("oauth_signature", "dummy_signature")
                .put("oauth_timestamp", "0")
                .put("oauth_nonce", "dummy_nonce")
                .put("version", "1.0")
                .build();
        final OAuth1aToken oAuth1aToken = OAuth1aToken.builder().putAll(passToken).build();
        try (CloseableHttpResponse res = hc.execute(
                oauth1aGetRequest("/composite", oAuth1aToken, AUTHORIZATION))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
        }
        try (CloseableHttpResponse res = hc.execute(
                oauth2GetRequest("/composite", OAuth2Token.of("dummy_oauth2_token"), AUTHORIZATION))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 200 OK");
        }
        try (CloseableHttpResponse res = hc.execute(new HttpGet(server.httpUri() + "/composite"))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 401 Unauthorized");
        }
        try (CloseableHttpResponse res = hc.execute(
                basicGetRequest("/composite",
                                BasicToken.of("choco", "pangyo"), AUTHORIZATION))) {
            assertThat(res.getStatusLine().toString()).isEqualTo("HTTP/1.1 401 Unauthorized");
        }
    }
}
 
Example #15
Source File: AuthServiceBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Adds an OAuth2 {@link Authorizer} for the given {@code header}.
 */
public AuthServiceBuilder addOAuth2(Authorizer<? super OAuth2Token> authorizer, CharSequence header) {
    return addTokenAuthorizer(new OAuth2TokenExtractor(requireNonNull(header, "header")),
                              requireNonNull(authorizer, "authorizer"));
}
 
Example #16
Source File: AuthServiceBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Adds an OAuth2 {@link Authorizer}.
 */
public AuthServiceBuilder addOAuth2(Authorizer<? super OAuth2Token> authorizer) {
    return addTokenAuthorizer(AuthTokenExtractors.oAuth2(), requireNonNull(authorizer, "authorizer"));
}
 
Example #17
Source File: AuthTokenExtractors.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Returns an {@link OAuth2Token} extractor function.
 */
public static Function<? super RequestHeaders, OAuth2Token> oAuth2() {
    return OAUTH2;
}
 
Example #18
Source File: ClientBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
public ClientBuilder auth(OAuth2Token token) {
    return (ClientBuilder) super.auth(token);
}
 
Example #19
Source File: WebClientBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
public WebClientBuilder auth(OAuth2Token token) {
    return (WebClientBuilder) super.auth(token);
}
 
Example #20
Source File: AbstractClientOptionsBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
/**
 * Sets the <a href="https://www.oauth.com/">OAuth 2.0</a> header using
 * {@link HttpHeaderNames#AUTHORIZATION}.
 */
public AbstractClientOptionsBuilder auth(OAuth2Token token) {
    requireNonNull(token, "token");
    httpHeaders.set(HttpHeaderNames.AUTHORIZATION, token.toHeaderValue());
    return this;
}
 
Example #21
Source File: ClientOptionsBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
public ClientOptionsBuilder auth(OAuth2Token token) {
    return (ClientOptionsBuilder) super.auth(token);
}
 
Example #22
Source File: ArmeriaRetrofitBuilder.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
public ArmeriaRetrofitBuilder auth(OAuth2Token token) {
    return (ArmeriaRetrofitBuilder) super.auth(token);
}
 
Example #23
Source File: ServerModule.java    From curiostack with MIT License 4 votes vote down vote up
private static HttpService decorateService(
    HttpService service,
    Tracing tracing,
    Lazy<FirebaseAuthorizer> firebaseAuthorizer,
    Lazy<JwtAuthorizer.Factory> jwtAuthorizer,
    Optional<SslCommonNamesProvider> sslCommonNamesProvider,
    ServerConfig serverConfig,
    FirebaseAuthConfig authConfig) {
  if (sslCommonNamesProvider.isPresent() && !serverConfig.isDisableSslAuthorization()) {
    AuthServiceBuilder authServiceBuilder = AuthService.builder();
    authServiceBuilder.add(new SslAuthorizer(sslCommonNamesProvider.get()));
    service = service.decorate(authServiceBuilder.newDecorator());
  }
  if (serverConfig.isEnableIapAuthorization()) {
    service =
        service
            .decorate(
                (delegate, ctx, req) -> {
                  DecodedJWT jwt = ctx.attr(JwtAuthorizer.DECODED_JWT);
                  String loggedInUserEmail =
                      jwt != null ? jwt.getClaim("email").asString() : "unknown";
                  RequestLoggingContext.put(ctx, "logged_in_user", loggedInUserEmail);
                  return delegate.serve(ctx, req);
                })
            .decorate(
                AuthService.builder()
                    .addTokenAuthorizer(
                        headers ->
                            OAuth2Token.of(
                                headers.get(HttpHeaderNames.of("x-goog-iap-jwt-assertion"))),
                        jwtAuthorizer
                            .get()
                            .create(
                                Algorithm.ES256, "https://www.gstatic.com/iap/verify/public_key"))
                    .newDecorator());
  }
  if (!authConfig.getServiceAccountBase64().isEmpty()) {
    FirebaseAuthorizer authorizer = firebaseAuthorizer.get();
    service =
        service.decorate(
            AuthService.builder().addOAuth2(authorizer).onFailure(authorizer).newDecorator());
  }

  service =
      service
          .decorate(
              MetricCollectingService.newDecorator(
                  RpcMetricLabels.grpcRequestLabeler("grpc_services")))
          .decorate(BraveService.newDecorator(tracing))
          .decorate(
              (delegate, ctx, req) -> {
                TraceContext traceCtx = tracing.currentTraceContext().get();
                if (traceCtx != null) {
                  RequestLoggingContext.put(ctx, "traceId", traceCtx.traceIdString());
                  RequestLoggingContext.put(ctx, "spanId", traceCtx.spanIdString());
                }
                return delegate.serve(ctx, req);
              });
  return service;
}
 
Example #24
Source File: IamAuthorizer.java    From curiostack with MIT License 4 votes vote down vote up
@Override
public CompletionStage<Boolean> authorize(ServiceRequestContext ctx, OAuth2Token data) {
  return checker.test(data.accessToken(), serviceAccount, PERMISSIONS);
}