use of org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext in project carbon-apimgt by wso2.
the class TokenGenTest method testAbstractJWTGenerator.
@Test
@Ignore
public void testAbstractJWTGenerator() throws Exception {
JWTGenerator jwtGen = new JWTGenerator() {
@Override
protected Map<String, String> convertClaimMap(Map<ClaimMapping, String> userAttributes, String username) {
return new HashMap<>();
}
};
APIKeyValidationInfoDTO dto = new APIKeyValidationInfoDTO();
TokenValidationContext validationContext = new TokenValidationContext();
validationContext.setValidationInfoDTO(dto);
validationContext.setContext("testAPI");
validationContext.setVersion("1.5.0");
validationContext.setAccessToken("DUMMY_TOKEN_STRING");
dto.setSubscriber("sanjeewa");
dto.setApplicationName("sanjeewa-app");
dto.setApplicationId("1");
dto.setApplicationTier("UNLIMITED");
dto.setEndUserName("malalgoda");
dto.setSubscriberTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
dto.setUserType(APIConstants.ACCESS_TOKEN_USER_TYPE_APPLICATION);
// Here we will call generate token method with 4 argument.
String token = jwtGen.generateToken(validationContext);
System.out.println("Generated Token: " + token);
String header = token.split("\\.")[0];
String decodedHeader = new String(Base64Utils.decode(header));
System.out.println("Header: " + decodedHeader);
String body = token.split("\\.")[1];
String decodedBody = new String(Base64Utils.decode(body));
System.out.println("Body: " + decodedBody);
// With end user name not included
token = jwtGen.generateToken(validationContext);
System.out.println("Generated Token: " + token);
header = token.split("\\.")[0];
decodedHeader = new String(Base64Utils.decode(header));
System.out.println("Header: " + decodedHeader);
body = token.split("\\.")[1];
decodedBody = new String(Base64Utils.decode(body));
System.out.println("Body: " + decodedBody);
dto.setUserType(APIConstants.SUBSCRIPTION_USER_TYPE);
token = jwtGen.generateToken(validationContext);
System.out.println("Generated Token: " + token);
header = token.split("\\.")[0];
decodedHeader = new String(Base64Utils.decode(header));
System.out.println("Header: " + decodedHeader);
body = token.split("\\.")[1];
decodedBody = new String(Base64Utils.decode(body));
System.out.println("Body: " + decodedBody);
token = jwtGen.generateToken(validationContext);
System.out.println("Generated Token: " + token);
header = token.split("\\.")[0];
decodedHeader = new String(Base64Utils.decode(header));
System.out.println("Header: " + decodedHeader);
body = token.split("\\.")[1];
decodedBody = new String(Base64Utils.decode(body));
System.out.println("Body: " + decodedBody);
}
use of org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext in project carbon-apimgt by wso2.
the class APIKeyValidationService method validateKeyForHandshake.
/**
* Validate access token for websocket handshake
*
* @param context context of the API
* @param version version of the API
* @param accessToken access token of the request
* @param tenantDomain
* @param keyManagers
* @return
* @throws APIKeyMgtException
* @throws APIManagementException
*/
public APIKeyValidationInfoDTO validateKeyForHandshake(String context, String version, String accessToken, String tenantDomain, List<String> keyManagers) throws APIKeyMgtException, APIManagementException {
APIKeyValidationInfoDTO info = new APIKeyValidationInfoDTO();
info.setAuthorized(false);
TokenValidationContext validationContext = new TokenValidationContext();
validationContext.setAccessToken(accessToken);
validationContext.setContext(context);
validationContext.setValidationInfoDTO(new APIKeyValidationInfoDTO());
validationContext.setVersion(version);
validationContext.setTenantDomain(tenantDomain);
validationContext.setRequiredAuthenticationLevel("Any");
validationContext.setKeyManagers(keyManagers);
KeyValidationHandler keyValidationHandler = ServiceReferenceHolder.getInstance().getKeyValidationHandler(tenantDomain);
boolean state = keyValidationHandler.validateToken(validationContext);
if (state) {
state = keyValidationHandler.validateSubscription(validationContext);
if (state) {
if (APIKeyMgtDataHolder.isJwtGenerationEnabled() && validationContext.getValidationInfoDTO().getEndUserName() != null && !validationContext.isCacheHit()) {
Application application = APIUtil.getApplicationByClientId(validationContext.getValidationInfoDTO().getConsumerKey());
validationContext.getValidationInfoDTO().setApplicationId(String.valueOf(application.getId()));
validationContext.getValidationInfoDTO().setApplicationTier(application.getTier());
keyValidationHandler.generateConsumerToken(validationContext);
info.setEndUserToken(validationContext.getValidationInfoDTO().getEndUserToken());
}
}
return validationContext.getValidationInfoDTO();
}
return info;
}
use of org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext in project carbon-apimgt by wso2.
the class DefaultKeyValidationHandlerTest method testValidateScopes.
@Test
public void testValidateScopes() throws APIKeyMgtException {
API api = new API();
api.setApiId(1);
api.setApiProvider(USER_NAME);
api.setApiName(API_NAME);
api.setApiVersion(API_VERSION);
api.setContext(API_CONTEXT);
URLMapping urlMapping = new URLMapping();
urlMapping.addScope(SCOPES);
urlMapping.setHttpMethod(HTTP_VERB);
urlMapping.setUrlPattern(RESOURCE);
api.addResource(urlMapping);
Map<String, API> apiMap = new HashMap<>();
String key = API_CONTEXT + ":" + API_VERSION;
apiMap.put(key, api);
APIKeyValidationInfoDTO dto = new APIKeyValidationInfoDTO();
dto.setSubscriber(SUBSCRIBER);
dto.setApplicationName(APPLICATION_NAME);
dto.setApplicationId(APPLICATION_ID);
dto.setApplicationTier(TIER);
Set<String> scopeSet = new HashSet<>();
scopeSet.add(SCOPES);
dto.setScopes(scopeSet);
dto.setSubscriberTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
dto.setUserType(APIConstants.ACCESS_TOKEN_USER_TYPE_APPLICATION);
// TokenValidationContext for non default API
TokenValidationContext param1 = new TokenValidationContext();
param1.setValidationInfoDTO(dto);
param1.setContext(API_CONTEXT);
param1.setVersion(API_VERSION);
param1.setAccessToken(ACCESS_TOKEN);
param1.setMatchingResource(RESOURCE);
param1.setHttpVerb(HTTP_VERB);
// TokenValidationContext for default API version
TokenValidationContext param2 = new TokenValidationContext();
param2.setValidationInfoDTO(dto);
param2.setContext(API_CONTEXT);
param2.setVersion(DEFAULT_API_VERSION);
param2.setAccessToken(ACCESS_TOKEN);
param2.setMatchingResource(RESOURCE);
param2.setHttpVerb(HTTP_VERB);
Mockito.when(SubscriptionDataHolder.getInstance()).thenReturn(subscriptionDataHolder);
Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN);
Mockito.when(subscriptionDataHolder.getTenantSubscriptionStore(eq(TENANT_DOMAIN))).thenReturn(tenantSubscriptionStore);
Mockito.when(tenantSubscriptionStore.getApiByContextAndVersion(eq(API_CONTEXT), eq(API_VERSION))).thenReturn(api);
DefaultKeyValidationHandler defaultKeyValidationHandler = new DefaultKeyValidationHandler();
boolean isScopeValidated = defaultKeyValidationHandler.validateScopes(param1);
boolean isScopeValidated_default = defaultKeyValidationHandler.validateScopes(param2);
Assert.assertTrue("Scope validation fails for API " + API_NAME, isScopeValidated);
Assert.assertTrue("Scope validation fails for default API " + API_NAME, isScopeValidated_default);
}
use of org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext in project carbon-apimgt by wso2.
the class JWTGenerator method populateCustomClaims.
@Override
public Map<String, String> populateCustomClaims(TokenValidationContext validationContext) throws APIManagementException {
APIManagerConfiguration apiManagerConfiguration = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration();
JWTConfigurationDto jwtConfigurationDto = apiManagerConfiguration.getJwtConfigurationDto();
Map<String, String> customClaims = new HashMap<>();
Map<String, Object> properties = new HashMap<>();
String username = validationContext.getValidationInfoDTO().getEndUserName();
int tenantId = APIUtil.getTenantId(username);
if (jwtConfigurationDto.isEnableUserClaims()) {
String accessToken = validationContext.getAccessToken();
if (accessToken != null) {
properties.put(APIConstants.KeyManager.ACCESS_TOKEN, accessToken);
}
String dialectURI = jwtConfigurationDto.getConsumerDialectUri();
if (!StringUtils.isEmpty(dialectURI)) {
properties.put(APIConstants.KeyManager.CLAIM_DIALECT, dialectURI);
String keymanagerName = validationContext.getValidationInfoDTO().getKeyManager();
KeyManager keymanager = KeyManagerHolder.getKeyManagerInstance(APIUtil.getTenantDomainFromTenantId(tenantId), keymanagerName);
if (keymanager != null) {
customClaims = keymanager.getUserClaims(username, properties);
if (log.isDebugEnabled()) {
log.debug("Retrieved claims :" + customClaims);
}
}
}
}
ClaimsRetriever claimsRetriever = getClaimsRetriever();
if (claimsRetriever != null) {
customClaims.putAll(claimsRetriever.getClaims(username));
}
return customClaims;
}
use of org.wso2.carbon.apimgt.keymgt.service.TokenValidationContext in project carbon-apimgt by wso2.
the class JWTGenerator method populateStandardClaims.
@Override
public Map<String, String> populateStandardClaims(TokenValidationContext validationContext) throws APIManagementException {
// generating expiring timestamp
long currentTime = System.currentTimeMillis();
long expireIn = currentTime + getTTL() * 1000;
String dialect;
ClaimsRetriever claimsRetriever = getClaimsRetriever();
if (claimsRetriever != null) {
dialect = claimsRetriever.getDialectURI(validationContext.getValidationInfoDTO().getEndUserName());
} else {
dialect = getDialectURI();
}
// dialect is either empty or '/' do not append a backslash. otherwise append a backslash '/'
if (!"".equals(dialect) && !"/".equals(dialect)) {
dialect = dialect + "/";
}
String subscriber = validationContext.getValidationInfoDTO().getSubscriber();
String applicationName = validationContext.getValidationInfoDTO().getApplicationName();
String applicationId = validationContext.getValidationInfoDTO().getApplicationId();
String tier = validationContext.getValidationInfoDTO().getTier();
String endUserName = validationContext.getValidationInfoDTO().getEndUserName();
String keyType = validationContext.getValidationInfoDTO().getType();
String userType = validationContext.getValidationInfoDTO().getUserType();
String applicationTier = validationContext.getValidationInfoDTO().getApplicationTier();
String enduserTenantId = String.valueOf(APIUtil.getTenantId(endUserName));
String apiName = validationContext.getValidationInfoDTO().getApiName();
Application application = getApplicationById(validationContext.getValidationInfoDTO().getSubscriberTenantDomain(), Integer.parseInt(applicationId));
String uuid = null;
Map<String, String> appAttributes = null;
if (application != null) {
appAttributes = application.getAttributes();
uuid = application.getUUID();
}
Map<String, String> claims = new LinkedHashMap<String, String>(20);
claims.put("iss", API_GATEWAY_ID);
claims.put("exp", String.valueOf(expireIn));
claims.put(dialect + "subscriber", subscriber);
claims.put(dialect + "applicationid", applicationId);
claims.put(dialect + "applicationname", applicationName);
claims.put(dialect + "applicationtier", applicationTier);
claims.put(dialect + "apiname", apiName);
claims.put(dialect + "apicontext", validationContext.getContext());
claims.put(dialect + "version", validationContext.getVersion());
claims.put(dialect + "tier", tier);
claims.put(dialect + "keytype", keyType);
claims.put(dialect + "usertype", userType);
claims.put(dialect + "enduser", APIUtil.getUserNameWithTenantSuffix(endUserName));
claims.put(dialect + "enduserTenantId", enduserTenantId);
claims.put(dialect + "applicationUUId", uuid);
try {
if (appAttributes != null && !appAttributes.isEmpty()) {
String stringAppAttributes = new ObjectMapper().writeValueAsString(appAttributes);
claims.put(dialect + "applicationAttributes", stringAppAttributes);
}
} catch (JsonProcessingException e) {
log.error("Error in converting Map to String");
}
return claims;
}
Aggregations