Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.oauth2.OAuth2AuthManager;
import org.apache.cloudstack.oauth2.api.response.OauthProviderResponse;
import org.apache.cloudstack.oauth2.forgerock.ForgeRockOAuth2Provider;
import org.apache.cloudstack.oauth2.keycloak.KeycloakOAuth2Provider;
import org.apache.cloudstack.oauth2.vo.OauthProviderVO;
import org.apache.commons.collections.MapUtils;
Expand Down Expand Up @@ -59,10 +60,10 @@ public class RegisterOAuthProviderCmd extends BaseCmd {
@Parameter(name = ApiConstants.REDIRECT_URI, type = CommandType.STRING, description = "Redirect URI pre-registered in the specific OAuth provider", required = true)
private String redirectUri;

@Parameter(name = ApiConstants.AUTHORIZE_URL, type = CommandType.STRING, description = "Authorize URL for OAuth initialization (only required for keycloak provider)")
@Parameter(name = ApiConstants.AUTHORIZE_URL, type = CommandType.STRING, description = "Authorize URL for OAuth initialization (only required for OIDC providers)")
private String authorizeUrl;

@Parameter(name = ApiConstants.TOKEN_URL, type = CommandType.STRING, description = "Token URL for OAuth finalization (only required for keycloak provider)")
@Parameter(name = ApiConstants.TOKEN_URL, type = CommandType.STRING, description = "Token URL for OAuth finalization (only required for OIDC providers)")
private String tokenUrl;

@Parameter(name = ApiConstants.DETAILS, type = CommandType.MAP,
Expand Down Expand Up @@ -115,12 +116,12 @@ public Map getDetails() {

@Override
public void execute() throws ServerApiException, ConcurrentOperationException, EntityExistsException {
if (StringUtils.equals(KeycloakOAuth2Provider.KEYCLOAK_PROVIDER, getProvider())) {
if (StringUtils.equalsAny(getProvider(), KeycloakOAuth2Provider.KEYCLOAK_PROVIDER, ForgeRockOAuth2Provider.FORGEROCK_PROVIDER)) {
if (StringUtils.isBlank(getAuthorizeUrl())) {
throw new ServerApiException(ApiErrorCode.BAD_REQUEST, "Parameter authorizeurl is mandatory for keycloak OAuth Provider");
throw new ServerApiException(ApiErrorCode.BAD_REQUEST, String.format("Parameter authorizeurl is mandatory for %s OAuth Provider", getProvider()));
}
if (StringUtils.isBlank(getTokenUrl())) {
throw new ServerApiException(ApiErrorCode.BAD_REQUEST, "Parameter tokenurl is mandatory for keycloak OAuth Provider");
throw new ServerApiException(ApiErrorCode.BAD_REQUEST, String.format("Parameter tokenurl is mandatory for %s OAuth Provider", getProvider()));
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
package org.apache.cloudstack.oauth2.forgerock;

import org.apache.cloudstack.oauth2.oidc.AbstractOIDCOAuth2Provider;

public class ForgeRockOAuth2Provider extends AbstractOIDCOAuth2Provider {

public static final String FORGEROCK_PROVIDER = "forgerock";

@Override
public String getName() {
return FORGEROCK_PROVIDER;
}

@Override
public String getDescription() {
return "ForgeRock OAuth2 Provider Plugin";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,57 +18,12 @@
//
package org.apache.cloudstack.oauth2.keycloak;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import org.apache.cloudstack.oauth2.oidc.AbstractOIDCOAuth2Provider;

import javax.inject.Inject;
import javax.ws.rs.core.HttpHeaders;

import org.apache.cloudstack.auth.UserOAuth2Authenticator;
import org.apache.cloudstack.oauth2.dao.OauthProviderDao;
import org.apache.cloudstack.oauth2.vo.OauthProviderVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer;
import org.apache.cxf.rs.security.jose.jwt.JwtClaims;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.cloud.exception.CloudAuthenticationException;
import com.cloud.utils.component.AdapterBase;
import com.cloud.utils.exception.CloudRuntimeException;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class KeycloakOAuth2Provider extends AdapterBase implements UserOAuth2Authenticator {
public class KeycloakOAuth2Provider extends AbstractOIDCOAuth2Provider {

public static final String KEYCLOAK_PROVIDER = "keycloak";

protected String idToken = null;

@Inject
OauthProviderDao oauthProviderDao;

private CloseableHttpClient httpClient;

public KeycloakOAuth2Provider() {
this(HttpClientBuilder.create().build());
}

public KeycloakOAuth2Provider(CloseableHttpClient httpClient) {
this.httpClient = httpClient;
}

@Override
public String getName() {
return KEYCLOAK_PROVIDER;
Expand All @@ -78,107 +33,4 @@ public String getName() {
public String getDescription() {
return "Keycloak OAuth2 Provider Plugin";
}

@Override
public boolean verifyUser(String email, String secretCode) {
if (StringUtils.isAnyEmpty(email, secretCode)) {
throw new CloudAuthenticationException("Either email or secret code should not be null/empty");
}

OauthProviderVO providerVO = oauthProviderDao.findByProvider(getName());
if (providerVO == null) {
throw new CloudAuthenticationException("Keycloak provider is not registered, so user cannot be verified");
}

String verifiedEmail = verifyCodeAndFetchEmail(secretCode);
if (StringUtils.isBlank(verifiedEmail) || !email.equals(verifiedEmail)) {
throw new CloudRuntimeException("Unable to verify the email address with the provided secret");
}
clearIdToken();

return true;
}

@Override
public String verifyCodeAndFetchEmail(String secretCode) {
OauthProviderVO provider = oauthProviderDao.findByProvider(getName());
if (provider == null) {
throw new CloudAuthenticationException("Keycloak provider is not registered, so user cannot be verified");
}

if (StringUtils.isBlank(idToken)) {
String auth = provider.getClientId() + ":" + provider.getSecretKey();
String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));

List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("grant_type", "authorization_code"));
params.add(new BasicNameValuePair("code", secretCode));
params.add(new BasicNameValuePair("redirect_uri", provider.getRedirectUri()));

HttpPost post = new HttpPost(provider.getTokenUrl());
post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth);

try {
post.setEntity(new UrlEncodedFormEntity(params));
} catch (UnsupportedEncodingException e) {
throw new CloudRuntimeException("Unable to generate URL parameters: " + e.getMessage());
}

try (CloseableHttpResponse response = httpClient.execute(post)) {
String body = EntityUtils.toString(response.getEntity());

if (response.getStatusLine().getStatusCode() != 200) {
throw new CloudRuntimeException("Keycloak error during token generation: " + body);
}

JsonObject json = JsonParser.parseString(body).getAsJsonObject();
JsonElement fetchedIdToken = json.get("id_token");
if (fetchedIdToken == null) {
throw new CloudRuntimeException("No id_token found in token");
}
String idTokenAsString = fetchedIdToken.getAsString();
validateIdToken(idTokenAsString , provider);

this.idToken = idTokenAsString ;
} catch (IOException e) {
throw new CloudRuntimeException("Unable to connect to Keycloak server", e);
}
}

return obtainEmail(idToken, provider);
}

@Override
public String getUserEmailAddress() throws CloudRuntimeException {
return null;
}

private void validateIdToken(String idTokenStr, OauthProviderVO provider) {
JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idTokenStr);
JwtClaims claims = jwtConsumer.getJwtToken().getClaims();

if (!claims.getAudiences().contains(provider.getClientId())) {
throw new CloudAuthenticationException("Audience mismatch");
}
}

private String obtainEmail(String idTokenStr, OauthProviderVO provider) {
JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idTokenStr);
JwtClaims claims = jwtConsumer.getJwtToken().getClaims();

if (!claims.getAudiences().contains(provider.getClientId())) {
throw new CloudAuthenticationException("Audience mismatch");
}

return (String) claims.getClaim("email");
}

protected void clearIdToken() {
idToken = null;
}

public void setHttpClient(CloseableHttpClient httpClient) {
this.httpClient = httpClient;
}

}
Loading
Loading