use of org.wso2.carbon.apimgt.rest.api.util.MethodStats in project carbon-apimgt by wso2.
the class AbstractOAuthAuthenticator method validateScopes.
/**
* @param message CXF message to be validate
* @param tokenInfo Token information associated with incoming request
* @return return true if we found matching scope in resource and token information
* else false(means scope validation failed).
*/
@MethodStats
public boolean validateScopes(Message message, OAuthTokenInfo tokenInfo) {
String basePath = (String) message.get(Message.BASE_PATH);
// path is obtained from Message.REQUEST_URI instead of Message.PATH_INFO, as Message.PATH_INFO contains
// decoded values of request parameters
String path = (String) message.get(Message.REQUEST_URI);
String verb = (String) message.get(Message.HTTP_REQUEST_METHOD);
String resource = path.substring(basePath.length() - 1);
String[] scopes = tokenInfo.getScopes();
String version = (String) message.get(RestApiConstants.API_VERSION);
// get all the URI templates of the REST API from the base path
Set<URITemplate> uriTemplates = RestApiUtil.getURITemplatesForBasePath(basePath + version);
if (uriTemplates.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("No matching scopes found for request with path: " + basePath + ". Skipping scope validation.");
}
return true;
}
for (Object template : uriTemplates.toArray()) {
org.wso2.uri.template.URITemplate templateToValidate = null;
Map<String, String> var = new HashMap<String, String>();
// check scopes with what we have
String templateString = ((URITemplate) template).getUriTemplate();
try {
templateToValidate = new org.wso2.uri.template.URITemplate(templateString);
} catch (URITemplateException e) {
log.error("Error while creating URI Template object to validate request. Template pattern: " + templateString, e);
}
if (templateToValidate != null && templateToValidate.matches(resource, var) && scopes != null && verb != null && verb.equalsIgnoreCase(((URITemplate) template).getHTTPVerb())) {
for (String scope : scopes) {
Scope scp = ((URITemplate) template).getScope();
if (scp != null) {
if (scope.equalsIgnoreCase(scp.getKey())) {
// we found scopes matches
if (log.isDebugEnabled()) {
log.debug("Scope validation successful for access token: " + message.get(RestApiConstants.MASKED_TOKEN) + " with scope: " + scp.getKey() + " for resource path: " + path + " and verb " + verb);
}
return true;
}
} else if (!((URITemplate) template).retrieveAllScopes().isEmpty()) {
List<Scope> scopesList = ((URITemplate) template).retrieveAllScopes();
for (Scope scpObj : scopesList) {
if (scope.equalsIgnoreCase(scpObj.getKey())) {
// we found scopes matches
if (log.isDebugEnabled()) {
log.debug("Scope validation successful for access token: " + message.get(RestApiConstants.MASKED_TOKEN) + " with scope: " + scpObj.getKey() + " for resource path: " + path + " and verb " + verb);
}
return true;
}
}
} else {
if (log.isDebugEnabled()) {
log.debug("Scope not defined in swagger for matching resource " + resource + " and verb " + verb + " . So consider as anonymous permission and let request to continue.");
}
return true;
}
}
}
}
return false;
}
use of org.wso2.carbon.apimgt.rest.api.util.MethodStats in project carbon-apimgt by wso2.
the class OAuthOpaqueAuthenticatorImpl method getTokenMetaData.
@MethodStats
public OAuthTokenInfo getTokenMetaData(String accessToken) throws APIManagementException {
OAuthTokenInfo tokenInfo = new OAuthTokenInfo();
OAuth2TokenValidationRequestDTO requestDTO = new OAuth2TokenValidationRequestDTO();
OAuth2TokenValidationRequestDTO.OAuth2AccessToken token = requestDTO.new OAuth2AccessToken();
token.setIdentifier(accessToken);
token.setTokenType("bearer");
requestDTO.setAccessToken(token);
OAuth2TokenValidationRequestDTO.TokenValidationContextParam[] contextParams = new OAuth2TokenValidationRequestDTO.TokenValidationContextParam[1];
requestDTO.setContext(contextParams);
OAuth2ClientApplicationDTO clientApplicationDTO = findOAuthConsumerIfTokenIsValid(requestDTO);
OAuth2TokenValidationResponseDTO responseDTO = clientApplicationDTO.getAccessTokenValidationResponse();
if (!responseDTO.isValid()) {
tokenInfo.setTokenValid(responseDTO.isValid());
log.error("Invalid OAuth Token : " + responseDTO.getErrorMsg());
return tokenInfo;
}
tokenInfo.setTokenValid(responseDTO.isValid());
tokenInfo.setEndUserName(responseDTO.getAuthorizedUser());
tokenInfo.setConsumerKey(clientApplicationDTO.getConsumerKey());
// Convert Expiry Time to milliseconds.
if (responseDTO.getExpiryTime() == Long.MAX_VALUE) {
tokenInfo.setValidityPeriod(Long.MAX_VALUE);
} else {
tokenInfo.setValidityPeriod(responseDTO.getExpiryTime() * 1000L);
}
tokenInfo.setIssuedTime(System.currentTimeMillis());
tokenInfo.setScopes(responseDTO.getScope());
return tokenInfo;
}
use of org.wso2.carbon.apimgt.rest.api.util.MethodStats in project carbon-apimgt by wso2.
the class ValidationInInterceptor method handleMessage.
@MethodStats
public void handleMessage(Message message) {
final OperationResourceInfo operationResource = message.getExchange().get(OperationResourceInfo.class);
if (operationResource == null) {
log.info("OperationResourceInfo is not available, skipping validation");
return;
}
final ClassResourceInfo classResource = operationResource.getClassResourceInfo();
if (classResource == null) {
log.info("ClassResourceInfo is not available, skipping validation");
return;
}
final ResourceProvider resourceProvider = classResource.getResourceProvider();
if (resourceProvider == null) {
log.info("ResourceProvider is not available, skipping validation");
return;
}
final List<Object> arguments = MessageContentsList.getContentsList(message);
final Method method = operationResource.getAnnotatedMethod();
final Object instance = resourceProvider.getInstance(message);
if (method != null && arguments != null) {
// validate the parameters(arguments) over the invoked method
validate(method, arguments.toArray(), instance);
// validate the fields of each argument
for (Object arg : arguments) {
if (arg != null)
validate(arg);
}
}
}
use of org.wso2.carbon.apimgt.rest.api.util.MethodStats in project carbon-apimgt by wso2.
the class OAuthJwtAuthenticatorImpl method getSignedJwt.
/**
* Get signed jwt info.
*
* @param accessToken JWT token
* @return SignedJWTInfo : Signed token info
*/
@MethodStats
private SignedJWTInfo getSignedJwt(String accessToken) throws ParseException {
SignedJWT signedJWT = SignedJWT.parse(accessToken);
JWTClaimsSet jwtClaimsSet = signedJWT.getJWTClaimsSet();
return new SignedJWTInfo(accessToken, signedJWT, jwtClaimsSet);
}
use of org.wso2.carbon.apimgt.rest.api.util.MethodStats 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;
}
Aggregations