use of org.wso2.carbon.identity.secret.mgt.core.model.Secret in project product-apim by wso2.
the class ApiClient method configureAuthorizationFlow.
/**
* Helper method to configure the oauth accessCode/implicit flow parameters
*
* @param clientId Client ID
* @param clientSecret Client secret
* @param redirectURI Redirect URI
*/
public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) {
for (RequestInterceptor apiAuthorization : apiAuthorizations.values()) {
if (apiAuthorization instanceof OAuth) {
OAuth oauth = (OAuth) apiAuthorization;
oauth.getTokenRequestBuilder().setClientId(clientId).setClientSecret(clientSecret).setRedirectURI(redirectURI);
oauth.getAuthenticationRequestBuilder().setClientId(clientId).setRedirectURI(redirectURI);
return;
}
}
}
use of org.wso2.carbon.identity.secret.mgt.core.model.Secret in project carbon-apimgt by wso2.
the class AuthenticatorService method getConsumerKeySecret.
/**
* This method returns the consumer key & secret of a DCR application.
*
* @param appName Name of the DCR application
* @return Map with consumer key & secret
* @throws APIManagementException When creating DCR application fails
*/
private Map<String, String> getConsumerKeySecret(String appName) throws APIManagementException {
HashMap<String, String> consumerKeySecretMap;
if (!AuthUtil.getConsumerKeySecretMap().containsKey(appName)) {
consumerKeySecretMap = new HashMap<>();
List<String> grantTypes = new ArrayList<>();
grantTypes.add(KeyManagerConstants.PASSWORD_GRANT_TYPE);
grantTypes.add(KeyManagerConstants.REFRESH_GRANT_TYPE);
OAuthApplicationInfo oAuthApplicationInfo;
oAuthApplicationInfo = createDCRApplication(appName, "http://temporary.callback/url", grantTypes);
consumerKeySecretMap.put(AuthenticatorConstants.CONSUMER_KEY, oAuthApplicationInfo.getClientId());
consumerKeySecretMap.put(AuthenticatorConstants.CONSUMER_SECRET, oAuthApplicationInfo.getClientSecret());
AuthUtil.getConsumerKeySecretMap().put(appName, consumerKeySecretMap);
return consumerKeySecretMap;
} else {
return AuthUtil.getConsumerKeySecretMap().get(appName);
}
}
use of org.wso2.carbon.identity.secret.mgt.core.model.Secret in project carbon-apimgt by wso2.
the class AuthenticatorService method getTokens.
/**
* This method returns the access tokens for a given application.
*
* @param appName Name of the application which needs to get tokens
* @param grantType Grant type of the application
* @param userName User name of the user
* @param password Password of the user
* @param refreshToken Refresh token
* @param validityPeriod Validity period of tokens
* @param authorizationCode Authorization Code
* @return AccessTokenInfo - An object with the generated access token information
* @throws APIManagementException When receiving access tokens fails
*/
public AccessTokenInfo getTokens(String appName, String grantType, String userName, String password, String refreshToken, long validityPeriod, String authorizationCode, String assertion, IdentityProvider identityProvider) throws APIManagementException {
AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
MultiEnvironmentOverview multiEnvironmentOverviewConfigs = apimConfigurationService.getEnvironmentConfigurations().getMultiEnvironmentOverview();
boolean isMultiEnvironmentOverviewEnabled = multiEnvironmentOverviewConfigs.isEnabled();
// Get scopes of the application
String scopes = getApplicationScopes(appName);
log.debug("Set scopes for {} application using swagger definition.", appName);
// TODO: Get Consumer Key & Secret without creating a new app, from the IS side
Map<String, String> consumerKeySecretMap = getConsumerKeySecret(appName);
log.debug("Received consumer key & secret for {} application.", appName);
try {
if (KeyManagerConstants.AUTHORIZATION_CODE_GRANT_TYPE.equals(grantType)) {
// Access token for authorization code grant type
APIMAppConfigurations appConfigs = apimAppConfigurationService.getApimAppConfigurations();
String callBackURL = appConfigs.getApimBaseUrl() + AuthenticatorConstants.AUTHORIZATION_CODE_CALLBACK_URL + appName;
if (authorizationCode != null) {
// Get Access & Refresh Tokens
accessTokenRequest.setClientId(consumerKeySecretMap.get("CONSUMER_KEY"));
accessTokenRequest.setClientSecret(consumerKeySecretMap.get("CONSUMER_SECRET"));
accessTokenRequest.setGrantType(grantType);
accessTokenRequest.setAuthorizationCode(authorizationCode);
accessTokenRequest.setScopes(scopes);
accessTokenRequest.setValidityPeriod(validityPeriod);
accessTokenRequest.setCallbackURI(callBackURL);
accessTokenInfo = getKeyManager().getNewAccessToken(accessTokenRequest);
} else {
String errorMsg = "No Authorization Code available.";
log.error(errorMsg, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
throw new APIManagementException(errorMsg, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
}
} else if (KeyManagerConstants.PASSWORD_GRANT_TYPE.equals(grantType)) {
// Access token for password code grant type
accessTokenRequest = AuthUtil.createAccessTokenRequest(userName, password, grantType, refreshToken, null, validityPeriod, scopes, consumerKeySecretMap.get("CONSUMER_KEY"), consumerKeySecretMap.get("CONSUMER_SECRET"));
accessTokenInfo = getKeyManager().getNewAccessToken(accessTokenRequest);
} else if (KeyManagerConstants.REFRESH_GRANT_TYPE.equals(grantType)) {
accessTokenRequest = AuthUtil.createAccessTokenRequest(userName, password, grantType, refreshToken, null, validityPeriod, scopes, consumerKeySecretMap.get("CONSUMER_KEY"), consumerKeySecretMap.get("CONSUMER_SECRET"));
accessTokenInfo = getKeyManager().getNewAccessToken(accessTokenRequest);
} else if (isMultiEnvironmentOverviewEnabled) {
// JWT or Custom grant type
accessTokenRequest.setClientId(consumerKeySecretMap.get("CONSUMER_KEY"));
accessTokenRequest.setClientSecret(consumerKeySecretMap.get("CONSUMER_SECRET"));
accessTokenRequest.setAssertion(assertion);
// Pass grant type to extend a custom grant instead of JWT grant in the future
accessTokenRequest.setGrantType(KeyManagerConstants.JWT_GRANT_TYPE);
accessTokenRequest.setScopes(scopes);
accessTokenRequest.setValidityPeriod(validityPeriod);
accessTokenInfo = getKeyManager().getNewAccessToken(accessTokenRequest);
String usernameFromJWT = getUsernameFromJWT(accessTokenInfo.getIdToken());
try {
identityProvider.getIdOfUser(usernameFromJWT);
} catch (IdentityProviderException e) {
String errorMsg = "User " + usernameFromJWT + " does not exists in this environment.";
throw new APIManagementException(errorMsg, e, ExceptionCodes.USER_NOT_AUTHENTICATED);
}
}
} catch (KeyManagementException e) {
String errorMsg = "Error while receiving tokens for OAuth application : " + appName;
log.error(errorMsg, e, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
throw new APIManagementException(errorMsg, e, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
}
log.debug("Received access token for {} application.", appName);
return accessTokenInfo;
}
use of org.wso2.carbon.identity.secret.mgt.core.model.Secret in project carbon-apimgt by wso2.
the class AbstractKeyManager method buildFromJSON.
/**
* This method will accept json String and will do the json parse will set oAuth application properties to OAuthApplicationInfo object.
*
* @param jsonInput this jsonInput will contain set of oAuth application properties.
* @return OAuthApplicationInfo object will be return.
* @throws APIManagementException
*/
public OAuthApplicationInfo buildFromJSON(OAuthApplicationInfo oAuthApplicationInfo, String jsonInput) throws APIManagementException {
// initiate json parser.
JSONParser parser = new JSONParser();
JSONObject jsonObject;
try {
// parse json String
jsonObject = (JSONObject) parser.parse(jsonInput);
if (jsonObject != null) {
// create a map to hold json parsed objects.
Map<String, Object> params = (Map) jsonObject;
if (params.get(APIConstants.JSON_CALLBACK_URL) != null) {
oAuthApplicationInfo.setCallBackURL((String) params.get(APIConstants.JSON_CALLBACK_URL));
}
if (params.get(APIConstants.JSON_GRANT_TYPES) != null) {
String grantTypeString = params.get(APIConstants.JSON_GRANT_TYPES).toString();
if (StringUtils.isEmpty(oAuthApplicationInfo.getCallBackURL()) && (grantTypeString.contains("implicit") || grantTypeString.contains("authorization_code"))) {
throw new EmptyCallbackURLForCodeGrantsException("The callback url must have at least one URI " + "value when using Authorization code or implicit grant types.");
}
}
// set client Id
if (params.get(APIConstants.JSON_CLIENT_ID) != null) {
oAuthApplicationInfo.setClientId((String) params.get(APIConstants.JSON_CLIENT_ID));
}
// set client secret
if (params.get(APIConstants.JSON_CLIENT_SECRET) != null) {
oAuthApplicationInfo.setClientSecret((String) params.get(APIConstants.JSON_CLIENT_SECRET));
}
// copy all params map in to OAuthApplicationInfo's Map object.
oAuthApplicationInfo.putAll(params);
validateOAuthAppCreationProperties(oAuthApplicationInfo);
return oAuthApplicationInfo;
}
} catch (ParseException e) {
handleException("Error occurred while parsing JSON String", e);
}
return null;
}
use of org.wso2.carbon.identity.secret.mgt.core.model.Secret in project carbon-apimgt by wso2.
the class APIStateChangeWSWorkflowExecutor method setOAuthApplicationInfo.
/**
* set information that are needed to invoke callback service
*/
private void setOAuthApplicationInfo(APIStateWorkflowDTO apiStateWorkFlowDTO) throws WorkflowException {
// if credentials are not defined in the workflow-extension.xml file call dcr endpoint and generate a
// oauth application and pass the client id and secret
WorkflowProperties workflowProperties = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getWorkflowProperties();
if (clientId == null || clientSecret == null) {
String dcrUsername = workflowProperties.getdCREndpointUser();
String dcrPassword = workflowProperties.getdCREndpointPassword();
byte[] encodedAuth = Base64.encodeBase64((dcrUsername + ":" + dcrPassword).getBytes(Charset.forName("ISO-8859-1")));
JSONObject payload = new JSONObject();
payload.put(PayloadConstants.KEY_OAUTH_APPNAME, WorkflowConstants.WORKFLOW_OAUTH_APP_NAME);
payload.put(PayloadConstants.KEY_OAUTH_OWNER, dcrUsername);
payload.put(PayloadConstants.KEY_OAUTH_SAASAPP, "true");
payload.put(PayloadConstants.KEY_OAUTH_GRANT_TYPES, WorkflowConstants.WORKFLOW_OAUTH_APP_GRANT_TYPES);
URL serviceEndpointURL = new URL(workflowProperties.getdCREndPoint());
HttpClient httpClient = APIUtil.getHttpClient(serviceEndpointURL.getPort(), serviceEndpointURL.getProtocol());
HttpPost httpPost = new HttpPost(workflowProperties.getdCREndPoint());
String authHeader = "Basic " + new String(encodedAuth);
httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
StringEntity requestEntity = new StringEntity(payload.toJSONString(), ContentType.APPLICATION_JSON);
httpPost.setEntity(requestEntity);
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
String responseStr = EntityUtils.toString(entity);
if (log.isDebugEnabled()) {
log.debug("Workflow oauth app created: " + responseStr);
}
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse(responseStr);
clientId = (String) obj.get(PayloadConstants.VARIABLE_CLIENTID);
clientSecret = (String) obj.get(PayloadConstants.VARIABLE_CLIENTSECRET);
} else {
String error = "Error while starting the process: " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase();
log.error(error);
throw new WorkflowException(error);
}
} catch (ClientProtocolException e) {
String errorMsg = "Error while creating the http client";
log.error(errorMsg, e);
throw new WorkflowException(errorMsg, e);
} catch (IOException e) {
String errorMsg = "Error while connecting to dcr endpoint";
log.error(errorMsg, e);
throw new WorkflowException(errorMsg, e);
} catch (ParseException e) {
String errorMsg = "Error while parsing response from DCR endpoint";
log.error(errorMsg, e);
throw new WorkflowException(errorMsg, e);
} finally {
httpPost.reset();
}
}
apiStateWorkFlowDTO.setClientId(clientId);
apiStateWorkFlowDTO.setClientSecret(clientSecret);
apiStateWorkFlowDTO.setScope(WorkflowConstants.API_WF_SCOPE);
apiStateWorkFlowDTO.setTokenAPI(workflowProperties.getTokenEndPoint());
}
Aggregations