use of org.wso2.carbon.apimgt.api.OAuthTokenInfo in project carbon-apimgt by wso2.
the class OAuthJwtAuthenticatorImpl method handleScopeValidation.
/**
* Handle scope validation
*
* @param accessToken JWT token
* @param signedJWTInfo : Signed token info
* @param message : cxf Message
*/
private boolean handleScopeValidation(Message message, SignedJWTInfo signedJWTInfo, String accessToken) throws APIManagementException, ParseException {
String maskedToken = message.get(RestApiConstants.MASKED_TOKEN).toString();
OAuthTokenInfo oauthTokenInfo = new OAuthTokenInfo();
oauthTokenInfo.setAccessToken(accessToken);
oauthTokenInfo.setEndUserName(signedJWTInfo.getJwtClaimsSet().getSubject());
String scopeClaim = signedJWTInfo.getJwtClaimsSet().getStringClaim(JwtTokenConstants.SCOPE);
if (scopeClaim != null) {
String orgId = RestApiUtil.resolveOrganization(message);
String[] scopes = scopeClaim.split(JwtTokenConstants.SCOPE_DELIMITER);
scopes = java.util.Arrays.stream(scopes).filter(s -> s.contains(orgId)).map(s -> s.replace(APIConstants.URN_CHOREO + orgId + ":", "")).toArray(size -> new String[size]);
oauthTokenInfo.setScopes(scopes);
if (validateScopes(message, oauthTokenInfo)) {
// Add the user scopes list extracted from token to the cxf message
message.getExchange().put(RestApiConstants.USER_REST_API_SCOPES, oauthTokenInfo.getScopes());
// If scope validation successful then set tenant name and user name to current context
String tenantDomain = MultitenantUtils.getTenantDomain(oauthTokenInfo.getEndUserName());
int tenantId;
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class, null);
try {
String username = oauthTokenInfo.getEndUserName();
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
// when the username is an email in supertenant, it has at least 2 occurrences of '@'
long count = username.chars().filter(ch -> ch == '@').count();
// in the case of email, there will be more than one '@'
boolean isEmailUsernameEnabled = Boolean.parseBoolean(CarbonUtils.getServerConfiguration().getFirstProperty("EnableEmailUserName"));
if (isEmailUsernameEnabled || (username.endsWith(SUPER_TENANT_SUFFIX) && count <= 1)) {
username = MultitenantUtils.getTenantAwareUsername(username);
}
}
if (log.isDebugEnabled()) {
log.debug("username = " + username + "masked token " + maskedToken);
}
tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
carbonContext.setTenantDomain(tenantDomain);
carbonContext.setTenantId(tenantId);
carbonContext.setUsername(username);
message.put(RestApiConstants.SUB_ORGANIZATION, orgId);
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
APIUtil.loadTenantConfigBlockingMode(tenantDomain);
}
return true;
} catch (UserStoreException e) {
log.error("Error while retrieving tenant id for tenant domain: " + tenantDomain, e);
}
log.debug("Scope validation success for the token " + maskedToken);
return true;
}
log.error("scopes validation failed for the token" + maskedToken);
return false;
}
log.error("scopes validation failed for the token" + maskedToken);
return false;
}
use of org.wso2.carbon.apimgt.api.OAuthTokenInfo in project carbon-apimgt by wso2.
the class OAuthOpaqueAuthenticatorImpl method authenticate.
/**
* @param message cxf message to be authenticated
* @return true if authentication was successful else false
* @throws APIManagementException when error in authentication process
*/
@Override
public boolean authenticate(Message message) throws APIManagementException {
boolean retrievedFromInvalidTokenCache = false;
boolean retrievedFromTokenCache = false;
String accessToken = RestApiUtil.extractOAuthAccessTokenFromMessage(message, RestApiConstants.REGEX_BEARER_PATTERN, RestApiConstants.AUTH_HEADER_NAME);
OAuthTokenInfo tokenInfo = null;
RESTAPICacheConfiguration cacheConfiguration = APIUtil.getRESTAPICacheConfig();
// validate the token from cache if it is enabled
if (cacheConfiguration.isTokenCacheEnabled()) {
tokenInfo = (OAuthTokenInfo) getRESTAPITokenCache().get(accessToken);
if (tokenInfo != null) {
if (isAccessTokenExpired(tokenInfo)) {
tokenInfo.setTokenValid(false);
// remove the token from token cache and put the token into invalid token cache
// when the access token is expired
getRESTAPIInvalidTokenCache().put(accessToken, tokenInfo);
getRESTAPITokenCache().remove(accessToken);
log.error(RestApiConstants.ERROR_TOKEN_EXPIRED);
return false;
} else {
retrievedFromTokenCache = true;
}
} else {
// if the token doesn't exist in the valid token cache, then check it in the invalid token cache
tokenInfo = (OAuthTokenInfo) getRESTAPIInvalidTokenCache().get(accessToken);
if (tokenInfo != null) {
retrievedFromInvalidTokenCache = true;
}
}
}
// if the tokenInfo is null, then only retrieve the token information from the database
try {
if (tokenInfo == null) {
tokenInfo = getTokenMetaData(accessToken);
}
} catch (APIManagementException e) {
log.error("Error while retrieving token information for token: " + accessToken, e);
}
// if we got valid access token we will proceed with next
if (tokenInfo != null && tokenInfo.isTokenValid()) {
if (cacheConfiguration.isTokenCacheEnabled() && !retrievedFromTokenCache) {
// put the token info into token cache
getRESTAPITokenCache().put(accessToken, tokenInfo);
}
// If access token is valid then we will perform scope check for given resource.
if (validateScopes(message, tokenInfo)) {
// Add the user scopes list extracted from token to the cxf message
message.getExchange().put(RestApiConstants.USER_REST_API_SCOPES, tokenInfo.getScopes());
// If scope validation successful then set tenant name and user name to current context
String tenantDomain = MultitenantUtils.getTenantDomain(tokenInfo.getEndUserName());
int tenantId;
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class, null);
try {
String username = tokenInfo.getEndUserName();
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
// when the username is an email in supertenant, it has at least 2 occurrences of '@'
long count = username.chars().filter(ch -> ch == '@').count();
// in the case of email, there will be more than one '@'
boolean isEmailUsernameEnabled = Boolean.parseBoolean(CarbonUtils.getServerConfiguration().getFirstProperty("EnableEmailUserName"));
if (isEmailUsernameEnabled || (username.endsWith(SUPER_TENANT_SUFFIX) && count <= 1)) {
username = MultitenantUtils.getTenantAwareUsername(username);
}
}
if (log.isDebugEnabled()) {
log.debug("username = " + username);
}
tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
carbonContext.setTenantDomain(tenantDomain);
carbonContext.setTenantId(tenantId);
carbonContext.setUsername(username);
message.put(RestApiConstants.SUB_ORGANIZATION, tenantDomain);
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
APIUtil.loadTenantConfigBlockingMode(tenantDomain);
}
return true;
} catch (UserStoreException e) {
log.error("Error while retrieving tenant id for tenant domain: " + tenantDomain, e);
}
} else {
log.error(RestApiConstants.ERROR_SCOPE_VALIDATION_FAILED);
}
} else {
log.error(RestApiConstants.ERROR_TOKEN_INVALID);
if (cacheConfiguration.isTokenCacheEnabled() && !retrievedFromInvalidTokenCache) {
getRESTAPIInvalidTokenCache().put(accessToken, tokenInfo);
}
}
return false;
}
use of org.wso2.carbon.apimgt.api.OAuthTokenInfo 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.api.OAuthTokenInfo in project carbon-apimgt by wso2.
the class JWTUtil method handleScopeValidation.
/**
* Handle scope validation
*
* @param accessToken JWT token
* @param signedJWTInfo : Signed token info
* @param message : inbound message context
*/
public static boolean handleScopeValidation(HashMap<String, Object> message, SignedJWTInfo signedJWTInfo, String accessToken) throws APIManagementException, ParseException {
String maskedToken = message.get(RestApiConstants.MASKED_TOKEN).toString();
OAuthTokenInfo oauthTokenInfo = new OAuthTokenInfo();
oauthTokenInfo.setAccessToken(accessToken);
oauthTokenInfo.setEndUserName(signedJWTInfo.getJwtClaimsSet().getSubject());
String scopeClaim = signedJWTInfo.getJwtClaimsSet().getStringClaim(APIConstants.JwtTokenConstants.SCOPE);
if (scopeClaim != null) {
String orgId = (String) message.get(RestApiConstants.ORG_ID);
String[] scopes = scopeClaim.split(APIConstants.JwtTokenConstants.SCOPE_DELIMITER);
scopes = java.util.Arrays.stream(scopes).filter(s -> s.contains(orgId)).map(s -> s.replace(APIConstants.URN_CHOREO + orgId + ":", "")).toArray(size -> new String[size]);
oauthTokenInfo.setScopes(scopes);
if (validateScopes(message, oauthTokenInfo)) {
// Add the user scopes list extracted from token to the cxf message
message.put(RestApiConstants.USER_REST_API_SCOPES, oauthTokenInfo.getScopes());
// If scope validation successful then set tenant name and user name to current context
String tenantDomain = MultitenantUtils.getTenantDomain(oauthTokenInfo.getEndUserName());
int tenantId;
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
RealmService realmService = (RealmService) carbonContext.getOSGiService(RealmService.class, null);
try {
String username = oauthTokenInfo.getEndUserName();
if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
// when the username is an email in supertenant, it has at least 2 occurrences of '@'
long count = username.chars().filter(ch -> ch == '@').count();
// in the case of email, there will be more than one '@'
boolean isEmailUsernameEnabled = Boolean.parseBoolean(CarbonUtils.getServerConfiguration().getFirstProperty("EnableEmailUserName"));
if (isEmailUsernameEnabled || (username.endsWith(SUPER_TENANT_SUFFIX) && count <= 1)) {
username = MultitenantUtils.getTenantAwareUsername(username);
}
}
if (log.isDebugEnabled()) {
log.debug("username = " + username + "masked token " + maskedToken);
}
tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
carbonContext.setTenantDomain(tenantDomain);
carbonContext.setTenantId(tenantId);
carbonContext.setUsername(username);
if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
APIUtil.loadTenantConfigBlockingMode(tenantDomain);
}
return true;
} catch (UserStoreException e) {
log.error("Error while retrieving tenant id for tenant domain: " + tenantDomain, e);
}
log.debug("Scope validation success for the token " + maskedToken);
return true;
}
log.error("scopes validation failed for the token" + maskedToken);
return false;
}
log.error("scopes validation failed for the token" + maskedToken);
return false;
}
use of org.wso2.carbon.apimgt.api.OAuthTokenInfo 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;
}
Aggregations