private Authentication handleTokenRequest()

in token-service/src/main/java/com/google/solutions/tokenservice/web/OAuthResource.java [71:124]


  private Authentication handleTokenRequest(
    String grantType,
    MultivaluedMap<String, String> parameters
  ) throws Exception {
    if (Strings.isNullOrEmpty(grantType))
    {
      throw new IllegalArgumentException("A grant type is required");
    }

    //
    // Find a flow that:
    // - is enabled (in the configuration)
    // - supports the requested grant type
    // - supports the presented set of request parameters
    //
    var request = new AuthenticationRequest(grantType, parameters);
    var flow = this.flows
      .stream()
      .filter(f -> this.configuration.authenticationFlows().contains(f.name()))
      .filter(f -> f.grantType().equals(grantType) && f.canAuthenticate(request))
      .findFirst();

    if (!flow.isPresent()) {
      this.logAdapter
        .newWarningEntry(
          LogEvents.API_TOKEN,
          String.format(
            "No suitable flow found for grant type '%s' (enabled flows: %s)",
            grantType,
            String.join(", ", this.configuration.authenticationFlows())))
        .write();

      throw new IllegalArgumentException(
        String.format("No suitable flow found for grant type '%s'", grantType)
      );
    }

    //
    // Run flow to authenticate the user or client.
    //
    try {
      return flow.get().authenticate(request);
    }
    catch (Exception e)
    {
      this.logAdapter
        .newErrorEntry(
          LogEvents.API_TOKEN,
          String.format("Authentication failed: %s", Exceptions.getFullMessage(e)))
        .write();

      throw (Exception) e.fillInStackTrace();
    }
  }