use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse in project carbon-apimgt by wso2.
the class BasicAuthAuthenticatorTest method testAuthenticateWithoutBasicHeaderSegment.
@Test
public void testAuthenticateWithoutBasicHeaderSegment() {
TreeMap transportHeaders = new TreeMap();
transportHeaders.put(APIMgtGatewayConstants.AUTHORIZATION, "gsu64r874tcin7ry8oe");
Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(transportHeaders);
AuthenticationResponse authenticationResponse = basicAuthAuthenticator.authenticate(messageContext);
Assert.assertFalse(authenticationResponse.isAuthenticated());
Assert.assertEquals(authenticationResponse.getErrorCode(), APISecurityConstants.API_AUTH_MISSING_CREDENTIALS);
}
use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse in project carbon-apimgt by wso2.
the class BasicAuthAuthenticatorTest method testAuthenticateWithInvalidBasicHeader_1.
@Test
public void testAuthenticateWithInvalidBasicHeader_1() {
TreeMap transportHeaders = new TreeMap();
// Throw Decode64 exception
transportHeaders.put(CUSTOM_AUTH_HEADER, "Basic xxxxxxx");
Mockito.when(axis2MsgCntxt.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)).thenReturn(transportHeaders);
AuthenticationResponse authenticationResponse = basicAuthAuthenticator.authenticate(messageContext);
Assert.assertFalse(authenticationResponse.isAuthenticated());
Assert.assertEquals(authenticationResponse.getErrorCode(), APISecurityConstants.API_AUTH_INVALID_CREDENTIALS);
}
use of org.wso2.carbon.apimgt.gateway.handlers.security.AuthenticationResponse in project carbon-apimgt by wso2.
the class InternalAPIKeyAuthenticator method authenticate.
@Override
public AuthenticationResponse authenticate(MessageContext synCtx) {
API retrievedApi = GatewayUtils.getAPI(synCtx);
if (retrievedApi != null) {
if (log.isDebugEnabled()) {
log.info("Internal Key Authentication initialized");
}
try {
// Extract internal from the request while removing it from the msg context.
String internalKey = extractInternalKey(synCtx);
if (StringUtils.isEmpty(internalKey)) {
return new AuthenticationResponse(false, false, true, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
}
OpenAPI openAPI = (OpenAPI) synCtx.getProperty(APIMgtGatewayConstants.OPEN_API_OBJECT);
if (openAPI == null && !APIConstants.GRAPHQL_API.equals(synCtx.getProperty(APIConstants.API_TYPE))) {
log.error("Swagger is missing in the gateway. " + "Therefore, Internal Key authentication cannot be performed.");
return new AuthenticationResponse(false, true, false, APISecurityConstants.API_AUTH_MISSING_OPEN_API_DEF, APISecurityConstants.API_AUTH_MISSING_OPEN_API_DEF_ERROR_MESSAGE);
}
JWTTokenPayloadInfo payloadInfo = null;
String[] splitToken = internalKey.split("\\.");
JWTClaimsSet payload;
SignedJWT signedJWT;
String tokenIdentifier;
JWSHeader jwsHeader;
String alias;
if (splitToken.length != 3) {
log.error("Internal Key does not have the format {header}.{payload}.{signature} ");
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
}
signedJWT = SignedJWT.parse(internalKey);
payload = signedJWT.getJWTClaimsSet();
tokenIdentifier = payload.getJWTID();
jwsHeader = signedJWT.getHeader();
if (jwsHeader != null && StringUtils.isNotEmpty(jwsHeader.getKeyID())) {
alias = jwsHeader.getKeyID();
} else {
alias = APIUtil.getInternalApiKeyAlias();
}
// Check if the decoded header contains type as 'InternalKey'.
if (!GatewayUtils.isInternalKey(payload)) {
if (log.isDebugEnabled()) {
log.debug("Invalid Internal Key token type. Internal Key: " + GatewayUtils.getMaskedToken(splitToken[0]));
}
log.error("Invalid Internal Key token type.");
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
}
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);
String resourceCacheKey = APIUtil.getResourceInfoDTOCacheKey(apiContext, apiVersion, matchingResource, httpMethod);
VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
verbInfoDTO.setHttpVerb(httpMethod);
// Not doing resource level authentication
verbInfoDTO.setAuthType(APIConstants.AUTH_NO_AUTHENTICATION);
verbInfoDTO.setRequestKey(resourceCacheKey);
verbInfoDTO.setThrottling(OpenAPIUtils.getResourceThrottlingTier(openAPI, synCtx));
List<VerbInfoDTO> verbInfoList = new ArrayList<>();
verbInfoList.add(verbInfoDTO);
synCtx.setProperty(APIConstants.VERB_INFO_DTO, verbInfoList);
String cacheKey = GatewayUtils.getAccessTokenCacheKey(tokenIdentifier, apiContext, apiVersion, matchingResource, httpMethod);
String tenantDomain = GatewayUtils.getTenantDomain();
boolean isVerified = false;
String cacheToken = (String) getGatewayInternalKeyCache().get(tokenIdentifier);
if (cacheToken != null) {
if (log.isDebugEnabled()) {
log.debug("Internal Key retrieved from the Internal Key cache.");
}
if (getGatewayInternalKeyDataCache().get(cacheKey) != null) {
// Token is found in the key cache
payloadInfo = (JWTTokenPayloadInfo) getGatewayInternalKeyDataCache().get(cacheKey);
String accessToken = payloadInfo.getAccessToken();
isVerified = accessToken.equals(internalKey);
}
} else if (getInvalidGatewayInternalKeyCache().get(tokenIdentifier) != null) {
if (log.isDebugEnabled()) {
log.debug("Internal Key retrieved from the invalid Internal Key cache. Internal Key: " + GatewayUtils.getMaskedToken(splitToken[0]));
}
log.error("Invalid Internal Key." + GatewayUtils.getMaskedToken(splitToken[0]));
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
}
// Not found in cache or caching disabled
if (!isVerified) {
if (log.isDebugEnabled()) {
log.debug("Internal Key not found in the cache.");
}
isVerified = GatewayUtils.verifyTokenSignature(signedJWT, alias) && !GatewayUtils.isJwtTokenExpired(payload);
// Add token to tenant token cache
if (isVerified) {
getGatewayInternalKeyCache().put(tokenIdentifier, tenantDomain);
} else {
getInvalidGatewayInternalKeyCache().put(tokenIdentifier, tenantDomain);
}
if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
try {
// Start super tenant flow
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME, true);
// Add token to super tenant token cache
if (isVerified) {
getGatewayInternalKeyCache().put(tokenIdentifier, tenantDomain);
}
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
// If Internal Key signature is verified
if (isVerified) {
if (log.isDebugEnabled()) {
log.debug("Internal Key signature is verified.");
}
if (payloadInfo != null) {
// Internal Key is found in the key cache
payload = payloadInfo.getPayload();
if (GatewayUtils.isJwtTokenExpired(payload)) {
getGatewayInternalKeyCache().remove(tokenIdentifier);
getInvalidGatewayInternalKeyCache().put(tokenIdentifier, tenantDomain);
log.error("Internal Key is expired");
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
}
} else {
// Retrieve payload from InternalKey
if (log.isDebugEnabled()) {
log.debug("InternalKey payload not found in the cache.");
}
JWTTokenPayloadInfo jwtTokenPayloadInfo = new JWTTokenPayloadInfo();
jwtTokenPayloadInfo.setPayload(payload);
jwtTokenPayloadInfo.setAccessToken(internalKey);
getGatewayInternalKeyDataCache().put(cacheKey, jwtTokenPayloadInfo);
}
JSONObject api = GatewayUtils.validateAPISubscription(apiContext, apiVersion, payload, splitToken, false);
if (log.isDebugEnabled()) {
log.debug("Internal Key authentication successful.");
}
AuthenticationContext authenticationContext = GatewayUtils.generateAuthenticationContext(tokenIdentifier, payload, api, retrievedApi.getApiTier());
APISecurityUtils.setAuthenticationContext(synCtx, authenticationContext);
if (log.isDebugEnabled()) {
log.debug("User is authorized to access the resource using Internal Key.");
}
return new AuthenticationResponse(true, true, false, 0, null);
}
if (log.isDebugEnabled()) {
log.debug("Internal Key signature verification failure. Internal Key: " + GatewayUtils.getMaskedToken(splitToken[0]));
}
log.error("Invalid Internal Key. Signature verification failed.");
throw new APISecurityException(APISecurityConstants.API_AUTH_INVALID_CREDENTIALS, APISecurityConstants.API_AUTH_INVALID_CREDENTIALS_MESSAGE);
} catch (APISecurityException e) {
return new AuthenticationResponse(false, true, false, e.getErrorCode(), e.getMessage());
} catch (ParseException e) {
log.error("Error while parsing Internal Key", e);
return new AuthenticationResponse(false, true, false, APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
}
}
return new AuthenticationResponse(false, true, false, APISecurityConstants.API_AUTH_GENERAL_ERROR, APISecurityConstants.API_AUTH_GENERAL_ERROR_MESSAGE);
}
Aggregations