All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.clouway.oauth2.BasicAuthenticationCredentialsRequest Maven / Gradle / Ivy

package com.clouway.oauth2;

import com.clouway.friendlyserve.Request;
import com.clouway.friendlyserve.Response;
import com.clouway.friendlyserve.RsBadRequest;

import static com.google.common.io.BaseEncoding.base64;

/**
 * BasicAuthenticationCredentialsRequest is using basic authentication scheme to decode {@link ClientCredentials} from
 * the Basic Authorization header.
 *
 *
 * @see OAuth2 Client Authentication
 * @see Basic Authentication Scheme
 *
 * @author Miroslav Genov ([email protected])
 */
class BasicAuthenticationCredentialsRequest implements InstantaneousRequest {

  private final ClientRequest clientRequest;

  BasicAuthenticationCredentialsRequest(ClientRequest clientRequest) {
    this.clientRequest = clientRequest;
  }

  @Override
  public Response handleAsOf(Request request, DateTime instantTime) {
    String authHeader = request.header("Authorization");
    if (!authHeader.startsWith("Basic")) {
      return new RsBadRequest();
    }
    String credentialsString = trimLeadingBasicText(authHeader);

    try {
      String decoded = new String(base64().decode(credentialsString));

      ClientCredentials clientCredentials = parseCredentials(decoded);
      return clientRequest.handleAsOf(request, clientCredentials, instantTime);

    } catch (IllegalArgumentException e) {
      return new RsBadRequest();
    }

  }

  private ClientCredentials parseCredentials(String decodedHeader) {
    if (!decodedHeader.contains(":")) {
      throw new IllegalArgumentException("Credentials are not separated with ':'");
    }

    String[] credentials = decodedHeader.split(":");

    String clientId = credentials[0];
    String clientSecret = credentials[1];

    return new ClientCredentials(clientId, clientSecret);
  }

  private String trimLeadingBasicText(String authHeader) {
    return authHeader.substring(6);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy