use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class OAuthAuthenticationInterceptor method handleMessage.
@Override
@MethodStats
public void handleMessage(Message inMessage) {
// by-passes the interceptor if user calls an anonymous api
if (RestApiUtil.checkIfAnonymousAPI(inMessage)) {
return;
}
HashMap<String, Object> authContext = JWTAuthenticationUtils.addToJWTAuthenticationContext(inMessage);
RestAPIAuthenticator authenticator = RestAPIAuthenticationManager.getAuthenticator(authContext);
if (authenticator != null) {
try {
String authenticationType = authenticator.getAuthenticationType();
inMessage.put(RestApiConstants.REQUEST_AUTHENTICATION_SCHEME, authenticator.getAuthenticationType());
String basePath = (String) inMessage.get(RestApiConstants.BASE_PATH);
String version = (String) inMessage.get(RestApiConstants.API_VERSION);
authContext.put(RestApiConstants.URI_TEMPLATES, RestApiUtil.getURITemplatesForBasePath(basePath + version));
authContext.put(RestApiConstants.ORG_ID, RestApiUtil.resolveOrganization(inMessage));
if (authenticator.authenticate(authContext)) {
inMessage = JWTAuthenticationUtils.addToMessageContext(inMessage, authContext);
if (logger.isDebugEnabled()) {
logger.debug("Request has been Authenticated , authentication type : " + authenticationType);
}
} else {
logger.error("Failed to Authenticate , authentication type : " + authenticationType);
throw new AuthenticationException("Unauthenticated request");
}
} catch (APIManagementException e) {
logger.error("Authentication Failure " + e.getMessage());
return;
}
}
// Following logic will be moved to separate class in near future
if (authenticator == null) {
String accessToken = RestApiUtil.extractOAuthAccessTokenFromMessage(inMessage, RestApiConstants.REGEX_BEARER_PATTERN, RestApiConstants.AUTH_HEADER_NAME);
// add masked token to the Message
inMessage.put(RestApiConstants.MASKED_TOKEN, APIUtil.getMaskedToken(accessToken));
if (accessToken == null) {
return;
}
if (accessToken.contains(RestApiConstants.DOT)) {
inMessage.put(RestApiConstants.REQUEST_AUTHENTICATION_SCHEME, RestApiConstants.JWT_AUTHENTICATION);
} else {
inMessage.put(RestApiConstants.REQUEST_AUTHENTICATION_SCHEME, RestApiConstants.OPAQUE_AUTHENTICATION);
}
try {
if (logger.isDebugEnabled()) {
logger.debug(String.format("Authenticating request with : " + inMessage.get(RestApiConstants.REQUEST_AUTHENTICATION_SCHEME)) + "Authentication");
}
AbstractOAuthAuthenticator abstractOAuthAuthenticator = authenticatorMap.get(inMessage.get(RestApiConstants.REQUEST_AUTHENTICATION_SCHEME));
logger.debug("Selected Authenticator for the token validation " + abstractOAuthAuthenticator);
if (abstractOAuthAuthenticator.authenticate(inMessage)) {
if (logger.isDebugEnabled()) {
logger.debug("User logged into Web app using OAuth Authentication");
}
} else {
throw new AuthenticationException("Unauthenticated request");
}
} catch (APIManagementException e) {
logger.error("Error while authenticating incoming request to API Manager REST API", e);
}
}
}
use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class InboundWebsocketProcessorUtil method isAuthenticated.
/**
* Authenticate inbound websocket request handshake.
*
* @param inboundMessageContext InboundMessageContext
* @return whether authenticated or not
* @throws APIManagementException if an internal error occurs
* @throws APISecurityException if authentication fails
*/
public static boolean isAuthenticated(InboundMessageContext inboundMessageContext) throws APISecurityException, APIManagementException {
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(inboundMessageContext.getTenantDomain(), true);
APIKeyValidationInfoDTO info;
String authorizationHeader = inboundMessageContext.getRequestHeaders().get(HttpHeaders.AUTHORIZATION);
inboundMessageContext.getRequestHeaders().put(HttpHeaders.AUTHORIZATION, authorizationHeader);
String[] auth = authorizationHeader.split(StringUtils.SPACE);
List<String> keyManagerList = DataHolder.getInstance().getKeyManagersFromUUID(inboundMessageContext.getElectedAPI().getUuid());
if (APIConstants.CONSUMER_KEY_SEGMENT.equals(auth[0])) {
String cacheKey;
boolean isJwtToken = false;
String apiKey = auth[1];
if (WebsocketUtil.isRemoveOAuthHeadersFromOutMessage()) {
inboundMessageContext.getRequestHeaders().remove(HttpHeaders.AUTHORIZATION);
}
// Initial guess of a JWT token using the presence of a DOT.
if (StringUtils.isNotEmpty(apiKey) && apiKey.contains(APIConstants.DOT)) {
try {
// Check if the header part is decoded
if (StringUtils.countMatches(apiKey, APIConstants.DOT) != 2) {
log.debug("Invalid JWT token. The expected token format is <header.payload.signature>");
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, "Invalid JWT token");
}
inboundMessageContext.setSignedJWTInfo(getSignedJwtInfo(apiKey));
String keyManager = ServiceReferenceHolder.getInstance().getJwtValidationService().getKeyManagerNameIfJwtValidatorExist(inboundMessageContext.getSignedJWTInfo());
if (StringUtils.isNotEmpty(keyManager)) {
if (log.isDebugEnabled()) {
log.debug("KeyManager " + keyManager + "found for authenticate token " + GatewayUtils.getMaskedToken(apiKey));
}
if (keyManagerList.contains(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS) || keyManagerList.contains(keyManager)) {
if (log.isDebugEnabled()) {
log.debug("Elected KeyManager " + keyManager + "found in API level list " + String.join(",", keyManagerList));
}
isJwtToken = true;
} else {
if (log.isDebugEnabled()) {
log.debug("Elected KeyManager " + keyManager + " not found in API level list " + String.join(",", keyManagerList));
}
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, "Invalid JWT token");
}
} else {
if (log.isDebugEnabled()) {
log.debug("KeyManager not found for accessToken " + GatewayUtils.getMaskedToken(apiKey));
}
}
} catch (ParseException e) {
log.debug("Not a JWT token. Failed to decode the token header.", e);
} catch (APIManagementException e) {
log.error("Error while checking validation of JWT", e);
throw new APISecurityException(APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
}
}
// Find the authentication scheme based on the token type
if (isJwtToken) {
log.debug("The token was identified as a JWT token");
if (APIConstants.GRAPHQL_API.equals(inboundMessageContext.getElectedAPI().getApiType())) {
return InboundWebsocketProcessorUtil.authenticateGraphQLJWTToken(inboundMessageContext);
} else {
return InboundWebsocketProcessorUtil.authenticateWSJWTToken(inboundMessageContext);
}
} else {
log.debug("The token was identified as an OAuth token");
// If the key have already been validated
if (WebsocketUtil.isGatewayTokenCacheEnabled()) {
cacheKey = WebsocketUtil.getAccessTokenCacheKey(apiKey, inboundMessageContext.getApiContext(), inboundMessageContext.getMatchingResource());
info = WebsocketUtil.validateCache(apiKey, cacheKey);
if (info != null) {
inboundMessageContext.setKeyType(info.getType());
inboundMessageContext.setInfoDTO(info);
return info.isAuthorized();
}
}
info = getApiKeyDataForWSClient(apiKey, inboundMessageContext.getTenantDomain(), inboundMessageContext.getApiContext(), inboundMessageContext.getVersion(), keyManagerList);
if (info == null || !info.isAuthorized()) {
return false;
}
if (WebsocketUtil.isGatewayTokenCacheEnabled()) {
cacheKey = WebsocketUtil.getAccessTokenCacheKey(apiKey, inboundMessageContext.getApiContext(), inboundMessageContext.getMatchingResource());
WebsocketUtil.putCache(info, apiKey, cacheKey);
}
inboundMessageContext.setKeyType(info.getType());
inboundMessageContext.setToken(info.getEndUserToken());
inboundMessageContext.setInfoDTO(info);
return true;
}
} else {
return false;
}
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class OAS3Parser method getScopes.
/**
* This method returns the oauth scopes according to the given swagger
*
* @param resourceConfigsJSON resource json
* @return scope set
* @throws APIManagementException
*/
@Override
public Set<Scope> getScopes(String resourceConfigsJSON) throws APIManagementException {
OpenAPI openAPI = getOpenAPI(resourceConfigsJSON);
Map<String, SecurityScheme> securitySchemes;
SecurityScheme securityScheme;
OAuthFlows oAuthFlows;
OAuthFlow oAuthFlow;
Scopes scopes;
if (openAPI.getComponents() != null && (securitySchemes = openAPI.getComponents().getSecuritySchemes()) != null) {
Set<Scope> scopeSet = new HashSet<>();
if ((securityScheme = securitySchemes.get(OPENAPI_SECURITY_SCHEMA_KEY)) != null && (oAuthFlows = securityScheme.getFlows()) != null && (oAuthFlow = oAuthFlows.getImplicit()) != null && (scopes = oAuthFlow.getScopes()) != null) {
for (Map.Entry<String, String> entry : scopes.entrySet()) {
Scope scope = new Scope();
scope.setKey(entry.getKey());
scope.setName(entry.getKey());
scope.setDescription(entry.getValue());
Map<String, String> scopeBindings;
if (oAuthFlow.getExtensions() != null && (scopeBindings = (Map<String, String>) oAuthFlow.getExtensions().get(APIConstants.SWAGGER_X_SCOPES_BINDINGS)) != null) {
if (scopeBindings.get(scope.getKey()) != null) {
scope.setRoles(scopeBindings.get(scope.getKey()));
}
}
scopeSet.add(scope);
}
} else if ((securityScheme = securitySchemes.get("OAuth2Security")) != null && (oAuthFlows = securityScheme.getFlows()) != null && (oAuthFlow = oAuthFlows.getPassword()) != null && (scopes = oAuthFlow.getScopes()) != null) {
for (Map.Entry<String, String> entry : scopes.entrySet()) {
Scope scope = new Scope();
scope.setKey(entry.getKey());
scope.setName(entry.getKey());
scope.setDescription(entry.getValue());
Map<String, String> scopeBindings;
scopeSet.add(scope);
}
}
return OASParserUtil.sortScopes(scopeSet);
} else {
return OASParserUtil.sortScopes(getScopesFromExtensions(openAPI));
}
}
use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class APIDefinitionFromOpenAPISpec method getScopes.
/**
* This method returns the oauth scopes according to the given swagger
*
* @param resourceConfigsJSON resource json
* @return scope set
* @throws APIManagementException
*/
public Set<Scope> getScopes(String resourceConfigsJSON) throws APIManagementException {
Set<Scope> scopeList = new LinkedHashSet<Scope>();
JSONObject swaggerObject;
JSONParser parser = new JSONParser();
try {
swaggerObject = (JSONObject) parser.parse(resourceConfigsJSON);
// Check whether security definitions are defined or not
if (swaggerObject.get(APIConstants.SWAGGER_X_WSO2_SECURITY) != null) {
JSONObject securityDefinitionsObjects = (JSONObject) swaggerObject.get(APIConstants.SWAGGER_X_WSO2_SECURITY);
for (JSONObject securityDefinition : (Iterable<JSONObject>) securityDefinitionsObjects.values()) {
if (securityDefinition.get(APIConstants.SWAGGER_X_WSO2_SCOPES) != null) {
JSONArray oauthScope = (JSONArray) securityDefinition.get(APIConstants.SWAGGER_X_WSO2_SCOPES);
for (Object anOauthScope : oauthScope) {
Scope scope = new Scope();
JSONObject scopeObj = (JSONObject) anOauthScope;
scope.setKey((String) scopeObj.get(APIConstants.SWAGGER_SCOPE_KEY));
scope.setName((String) scopeObj.get(APIConstants.SWAGGER_NAME));
scope.setDescription((String) scopeObj.get(APIConstants.SWAGGER_DESCRIPTION));
scope.setRoles(scopeObj.get(APIConstants.SWAGGER_ROLES).toString());
scopeList.add(scope);
}
}
}
}
} catch (ParseException e) {
handleException("Invalid resource configuration ", e);
}
return scopeList;
}
use of org.wso2.carbon.apimgt.rest.integration.tests.store.auth.OAuth in project carbon-apimgt by wso2.
the class ApisApiServiceImpl method importOpenAPIDefinition.
/**
* Importing an OpenAPI definition and create an API
*
* @param fileInputStream InputStream for the provided file
* @param fileDetail File meta-data
* @param url URL of the OpenAPI definition
* @param additionalProperties API object (json) including additional properties like name, version, context
* @param inlineApiDefinition Swagger API definition String
* @param messageContext CXF message context
* @return API Import using OpenAPI definition response
* @throws APIManagementException when error occurs while importing the OpenAPI definition
*/
@Override
public Response importOpenAPIDefinition(InputStream fileInputStream, Attachment fileDetail, String url, String additionalProperties, String inlineApiDefinition, MessageContext messageContext) throws APIManagementException {
// validate 'additionalProperties' json
if (StringUtils.isBlank(additionalProperties)) {
RestApiUtil.handleBadRequest("'additionalProperties' is required and should not be null", log);
}
// Convert the 'additionalProperties' json into an APIDTO object
ObjectMapper objectMapper = new ObjectMapper();
APIDTO apiDTOFromProperties;
try {
apiDTOFromProperties = objectMapper.readValue(additionalProperties, APIDTO.class);
} catch (IOException e) {
throw RestApiUtil.buildBadRequestException("Error while parsing 'additionalProperties'", e);
}
// validate sandbox and production endpoints
if (!PublisherCommonUtils.validateEndpoints(apiDTOFromProperties)) {
throw new APIManagementException("Invalid/Malformed endpoint URL(s) detected", ExceptionCodes.INVALID_ENDPOINT_URL);
}
try {
LinkedHashMap endpointConfig = (LinkedHashMap) apiDTOFromProperties.getEndpointConfig();
// OAuth 2.0 backend protection: API Key and API Secret encryption
PublisherCommonUtils.encryptEndpointSecurityOAuthCredentials(endpointConfig, CryptoUtil.getDefaultCryptoUtil(), StringUtils.EMPTY, StringUtils.EMPTY, apiDTOFromProperties);
// Import the API and Definition
String organization = RestApiUtil.getValidatedOrganization(messageContext);
APIDTO createdApiDTO = importOpenAPIDefinition(fileInputStream, url, inlineApiDefinition, apiDTOFromProperties, fileDetail, null, organization);
if (createdApiDTO != null) {
// This URI used to set the location header of the POST response
URI createdApiUri = new URI(RestApiConstants.RESOURCE_PATH_APIS + "/" + createdApiDTO.getId());
return Response.created(createdApiUri).entity(createdApiDTO).build();
}
} catch (URISyntaxException e) {
String errorMessage = "Error while retrieving API location : " + apiDTOFromProperties.getProvider() + "-" + apiDTOFromProperties.getName() + "-" + apiDTOFromProperties.getVersion();
RestApiUtil.handleInternalServerError(errorMessage, e, log);
} catch (CryptoException e) {
String errorMessage = "Error while encrypting the secret key of API : " + apiDTOFromProperties.getProvider() + "-" + apiDTOFromProperties.getName() + "-" + apiDTOFromProperties.getVersion();
throw new APIManagementException(errorMessage, e);
}
return null;
}
Aggregations