use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.
the class AccessTokenGenerator method generateNewAccessToken.
private AccessTokenInfo generateNewAccessToken(String[] scopes) {
try {
String tokenEndpoint;
int serverPort;
URL oauthURL;
if (StringUtils.isNotEmpty(this.tokenEndpoint)) {
tokenEndpoint = this.tokenEndpoint;
oauthURL = new URL(tokenEndpoint);
serverPort = oauthURL.getPort();
} else {
oauthURL = new URL(oauthUrl);
serverPort = oauthURL.getPort();
tokenEndpoint = oauthUrl.concat("/token");
}
String serverProtocol = oauthURL.getProtocol();
HttpPost request = new HttpPost(tokenEndpoint);
HttpClient httpClient = APIUtil.getHttpClient(serverPort, serverProtocol);
byte[] credentials = org.apache.commons.codec.binary.Base64.encodeBase64((consumerKey + ":" + consumerSecret).getBytes(StandardCharsets.UTF_8));
request.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BASIC + new String(credentials, StandardCharsets.UTF_8));
request.setHeader(APIConstants.CONTENT_TYPE_HEADER, APIConstants.CONTENT_TYPE_APPLICATION_FORM);
List<BasicNameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair(APIConstants.TOKEN_GRANT_TYPE_KEY, APIConstants.GRANT_TYPE_VALUE));
if (scopes != null && scopes.length > 0) {
urlParameters.add(new BasicNameValuePair(APIConstants.OAUTH_RESPONSE_TOKEN_SCOPE, String.join(" ", scopes)));
}
request.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse httpResponse = httpClient.execute(request);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String payload = EntityUtils.toString(httpResponse.getEntity());
JSONObject response = new JSONObject(payload);
String accessToken = (String) response.get(APIConstants.OAUTH_RESPONSE_ACCESSTOKEN);
int validityPeriod = (Integer) response.get(APIConstants.OAUTH_RESPONSE_EXPIRY_TIME) * 1000;
long expiryTime = System.currentTimeMillis() + validityPeriod;
if (log.isDebugEnabled()) {
log.debug("Successfully received an access token which expires in " + expiryTime);
}
AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
accessTokenInfo.setAccessToken(accessToken);
accessTokenInfo.setIssuedTime(System.currentTimeMillis());
accessTokenInfo.setValidityPeriod(validityPeriod);
return accessTokenInfo;
} else {
log.error("Error occurred when generating a new Access token. Server responded with " + httpResponse.getStatusLine().getStatusCode());
}
} catch (IOException e) {
log.error("Error occurred when generating a new Access token", e);
}
return null;
}
use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.
the class BasicAuthAuthenticator method authenticate.
/**
* Authenticates the given request to see if an API consumer is allowed to access
* a particular API or not.
*
* @param synCtx The message to be authenticated
* @return an AuthenticationResponse object which contains the authentication status
*/
@MethodStats
public AuthenticationResponse authenticate(MessageContext synCtx) {
if (log.isDebugEnabled()) {
log.info("Basic Authentication initialized");
}
openAPI = (OpenAPI) synCtx.getProperty(APIMgtGatewayConstants.OPEN_API_OBJECT);
if (openAPI == null && !APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
log.error("OpenAPI definition is missing in the gateway. Basic authentication cannot be performed.");
return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_MISSING_OPEN_API_DEF, "Basic authentication cannot be performed.");
}
// Extract basic authorization header while removing it from the authorization header
String basicAuthHeader = extractBasicAuthHeader(synCtx);
String apiContext = (String) synCtx.getProperty(RESTConstants.REST_API_CONTEXT);
String apiVersion = (String) synCtx.getProperty(RESTConstants.SYNAPSE_REST_API_VERSION);
String httpMethod = (String) ((Axis2MessageContext) synCtx).getAxis2MessageContext().getProperty(Constants.Configuration.HTTP_METHOD);
String matchingResource = (String) synCtx.getProperty(APIConstants.API_ELECTED_RESOURCE);
// Check for resource level authentication
String authenticationScheme;
List<VerbInfoDTO> verbInfoList;
if (APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
HashMap<String, Boolean> operationAuthSchemeMappingList = (HashMap<String, Boolean>) synCtx.getProperty(APIConstants.OPERATION_AUTH_SCHEME_MAPPING);
HashMap<String, String> operationThrottlingMappingList = (HashMap<String, String>) synCtx.getProperty(APIConstants.OPERATION_THROTTLING_MAPPING);
String[] operationList = matchingResource.split(",");
verbInfoList = new ArrayList<>(1);
authenticationScheme = APIConstants.AUTH_NO_AUTHENTICATION;
for (String operation : operationList) {
boolean operationAuthSchemeEnabled = operationAuthSchemeMappingList.get(operation);
VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
if (operationAuthSchemeEnabled) {
verbInfoDTO.setAuthType(APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN);
authenticationScheme = APIConstants.AUTH_APPLICATION_OR_USER_LEVEL_TOKEN;
} else {
verbInfoDTO.setAuthType(APIConstants.AUTH_NO_AUTHENTICATION);
}
verbInfoDTO.setThrottling(operationThrottlingMappingList.get(operation));
verbInfoDTO.setRequestKey(apiContext + "/" + apiVersion + operation + ":" + httpMethod);
verbInfoList.add(verbInfoDTO);
}
} else {
authenticationScheme = OpenAPIUtils.getResourceAuthenticationScheme(openAPI, synCtx);
verbInfoList = new ArrayList<>(1);
VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
verbInfoDTO.setAuthType(authenticationScheme);
verbInfoDTO.setThrottling(OpenAPIUtils.getResourceThrottlingTier(openAPI, synCtx));
verbInfoDTO.setRequestKey(apiContext + "/" + apiVersion + matchingResource + ":" + httpMethod);
verbInfoList.add(verbInfoDTO);
}
String[] credentials;
try {
credentials = extractBasicAuthCredentials(basicAuthHeader);
} catch (APISecurityException ex) {
return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
}
String username = getEndUserName(credentials[0]);
String password = credentials[1];
// If end user tenant domain does not match the API publisher's tenant domain, return error
if (!MultitenantUtils.getTenantDomain(username).equals(synCtx.getProperty(PUBLISHER_TENANT_DOMAIN))) {
log.error("Basic Authentication failure: tenant domain mismatch for user :" + username);
return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_FORBIDDEN, APISecurityConstants.API_AUTH_FORBIDDEN_MESSAGE);
}
BasicAuthValidationInfoDTO basicAuthValidationInfoObj;
try {
if (basicAuthCredentialValidator == null) {
basicAuthCredentialValidator = new BasicAuthCredentialValidator();
}
basicAuthValidationInfoObj = basicAuthCredentialValidator.validate(username, password);
} catch (APISecurityException ex) {
return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
}
if (!basicAuthValidationInfoObj.isAuthenticated()) {
log.error("Basic Authentication failure: Username and Password mismatch");
return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
} else {
// username password matches
if (log.isDebugEnabled()) {
log.debug("Basic Authentication: Username and Password authenticated");
}
// scope validation
boolean scopesValid = false;
try {
scopesValid = basicAuthCredentialValidator.validateScopes(username, openAPI, synCtx, basicAuthValidationInfoObj);
} catch (APISecurityException ex) {
return new AuthenticationResponse(false, isMandatory, true, ex.getErrorCode(), ex.getMessage());
}
String domainQualifiedUserName = basicAuthValidationInfoObj.getDomainQualifiedUsername();
if (scopesValid) {
if (APISecurityUtils.getAuthenticationContext(synCtx) == null) {
// Create a dummy AuthenticationContext object with hard coded values for
// Tier and KeyType. This is because we cannot determine the Tier nor Key
// Type without subscription information..
AuthenticationContext authContext = new AuthenticationContext();
authContext.setAuthenticated(true);
authContext.setTier(APIConstants.UNAUTHENTICATED_TIER);
authContext.setStopOnQuotaReach(// Since we don't have details on unauthenticated tier we setting stop on quota reach true
true);
synCtx.setProperty(APIConstants.VERB_INFO_DTO, verbInfoList);
// In basic authentication scenario, we will use the username for throttling.
authContext.setApiKey(domainQualifiedUserName);
authContext.setKeyType(APIConstants.API_KEY_TYPE_PRODUCTION);
authContext.setUsername(domainQualifiedUserName);
authContext.setCallerToken(null);
authContext.setApplicationName(APIConstants.BASIC_AUTH_APPLICATION_NAME);
// Set username as application ID in basic auth scenario
authContext.setApplicationId(domainQualifiedUserName);
// Set username as application ID in basic auth scenario
authContext.setApplicationUUID(domainQualifiedUserName);
// Set application owner in basic auth scenario
authContext.setSubscriber(APIConstants.BASIC_AUTH_APPLICATION_OWNER);
authContext.setConsumerKey(null);
authContext.setApiTier(apiLevelPolicy);
APISecurityUtils.setAuthenticationContext(synCtx, authContext, null);
}
log.debug("Basic Authentication: Scope validation passed");
return new AuthenticationResponse(true, isMandatory, false, 0, null);
}
return new AuthenticationResponse(false, isMandatory, true, APISecurityConstants.INVALID_SCOPE, "Scope validation failed");
}
}
use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.
the class WSO2APIPublisherTestCase method testPublishToStoreWithNullStoreArguments.
@Test
public void testPublishToStoreWithNullStoreArguments() {
// Error path - When username or password or endpoint is not defined
APIStore nullStore = new APIStore();
nullStore.setDisplayName(storeName);
try {
wso2APIPublisher.publishToStore(api, nullStore);
Assert.fail("APIManagement exception not thrown for error scenario");
} catch (APIManagementException e) {
String msg = "External APIStore endpoint URL or credentials are not defined. " + "Cannot proceed with publishing API to the APIStore - " + nullStore.getDisplayName();
Assert.assertEquals(msg, e.getMessage());
}
}
use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.
the class OAuthJwtAuthenticatorImpl method validateJWTToken.
/**
* Validate the JWT token.
*
* @param jti jwtTokenIdentifier
* @param signedJWTInfo signed jwt info object
* @return JWTValidationInfo : token validated info
*/
@MethodStats
private JWTValidationInfo validateJWTToken(SignedJWTInfo signedJWTInfo, String jti, String accessToken, String maskedToken, URL basePath) throws APIManagementException {
JWTValidationInfo jwtValidationInfo;
String issuer = signedJWTInfo.getJwtClaimsSet().getIssuer();
if (StringUtils.isNotEmpty(issuer)) {
// validate Issuer
List<String> tokenAudiences = signedJWTInfo.getJwtClaimsSet().getAudience();
if (tokenIssuers != null && tokenIssuers.containsKey(issuer)) {
// validate audience
if (audiencesMap != null && audiencesMap.get(basePath.getPath()) != null && tokenAudiences.stream().anyMatch(audiencesMap.get(basePath.getPath())::contains)) {
if (isRESTApiTokenCacheEnabled) {
JWTValidationInfo tempJWTValidationInfo = (JWTValidationInfo) getRESTAPITokenCache().get(jti);
if (tempJWTValidationInfo != null) {
Boolean isExpired = checkTokenExpiration(new Date(tempJWTValidationInfo.getExpiryTime()));
if (isExpired) {
tempJWTValidationInfo.setValid(false);
getRESTAPITokenCache().remove(jti);
getRESTAPIInvalidTokenCache().put(jti, tempJWTValidationInfo);
log.error("JWT token validation failed. Reason: Expired Token. " + maskedToken);
return tempJWTValidationInfo;
}
// check accessToken
if (!tempJWTValidationInfo.getRawPayload().equals(accessToken)) {
tempJWTValidationInfo.setValid(false);
getRESTAPITokenCache().remove(jti);
getRESTAPIInvalidTokenCache().put(jti, tempJWTValidationInfo);
log.error("JWT token validation failed. Reason: Invalid Token. " + maskedToken);
return tempJWTValidationInfo;
}
return tempJWTValidationInfo;
} else if (getRESTAPIInvalidTokenCache().get(jti) != null) {
if (log.isDebugEnabled()) {
log.debug("Token retrieved from the invalid token cache. Token: " + maskedToken);
}
return (JWTValidationInfo) getRESTAPIInvalidTokenCache().get(jti);
}
}
// info not in cache. validate signature and exp
JWTValidator jwtValidator = APIMConfigUtil.getJWTValidatorMap().get(issuer);
jwtValidationInfo = jwtValidator.validateToken(signedJWTInfo);
if (jwtValidationInfo.isValid()) {
// valid token
if (isRESTApiTokenCacheEnabled) {
getRESTAPITokenCache().put(jti, jwtValidationInfo);
}
} else {
// put in invalid cache
if (isRESTApiTokenCacheEnabled) {
getRESTAPIInvalidTokenCache().put(jti, jwtValidationInfo);
}
// invalid credentials : 900901 error code
log.error("JWT token validation failed. Reason: Invalid Credentials. " + "Make sure you have provided the correct security credentials in the token :" + maskedToken);
}
} else {
if (audiencesMap == null) {
log.error("JWT token audience validation failed. Reason: No audiences registered " + "in the server");
} else if (audiencesMap.get(basePath.getPath()) == null) {
log.error("JWT token audience validation failed. Reason: No audiences registered " + "in the server for the base path (" + basePath.getPath() + ")");
} else {
log.error("JWT token audience validation failed. Reason: None of the aud present " + "in the JWT (" + tokenAudiences.toString() + ") matches the intended audience (" + audiencesMap.get(basePath.getPath()).toString() + ") for base path ( " + basePath.getPath() + " ).");
}
return null;
}
} else {
// invalid issuer. invalid token
log.error("JWT token issuer validation failed. Reason: Issuer present in the JWT (" + issuer + ") does not match with the token issuer (" + tokenIssuers.keySet().toString() + ")");
return null;
}
} else {
log.error("Issuer is not found in the token " + maskedToken);
return null;
}
return jwtValidationInfo;
}
use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.
the class PolicyRetriever method invokeService.
private CloseableHttpResponse invokeService(String endpoint, String tenantDomain) throws IOException, ThrottlePolicyDeployerException {
HttpGet method = new HttpGet(endpoint);
URL url = new URL(endpoint);
String username = eventHubConfigurationDto.getUsername();
String password = eventHubConfigurationDto.getPassword();
byte[] credentials = Base64.encodeBase64((username + APIConstants.DELEM_COLON + password).getBytes(APIConstants.DigestAuthConstants.CHARSET));
int port = url.getPort();
String protocol = url.getProtocol();
method.setHeader(APIConstants.HEADER_TENANT, tenantDomain);
method.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BASIC + new String(credentials, APIConstants.DigestAuthConstants.CHARSET));
HttpClient httpClient = APIUtil.getHttpClient(port, protocol);
try {
return APIUtil.executeHTTPRequest(method, httpClient);
} catch (APIManagementException e) {
throw new ThrottlePolicyDeployerException(e);
}
}
Aggregations