use of org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO in project airavata by apache.
the class DefaultOAuthClient method validateAccessToken.
/**
* Validates the OAuth 2.0 access token
*
* @param accessToken
* @return
* @throws Exception
*/
public OAuth2TokenValidationResponseDTO validateAccessToken(String accessToken) throws AiravataSecurityException {
try {
OAuth2TokenValidationRequestDTO oauthReq = new OAuth2TokenValidationRequestDTO();
OAuth2TokenValidationRequestDTO_OAuth2AccessToken token = new OAuth2TokenValidationRequestDTO_OAuth2AccessToken();
token.setIdentifier(accessToken);
token.setTokenType(BEARER_TOKEN_TYPE);
oauthReq.setAccessToken(token);
return stub.validate(oauthReq);
} catch (RemoteException e) {
logger.error(e.getMessage(), e);
throw new AiravataSecurityException("Error in validating the OAuth access token.");
}
}
use of org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO in project airavata by apache.
the class DefaultAiravataSecurityManager method isUserAuthorized.
public boolean isUserAuthorized(AuthzToken authzToken, Map<String, String> metaData) throws AiravataSecurityException {
try {
String subject = authzToken.getClaimsMap().get(Constants.USER_NAME);
String accessToken = authzToken.getAccessToken();
String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
String action = metaData.get(Constants.API_METHOD_NAME);
// if the authz cache is enabled, check in the cache if the authz decision is cached and if so, what the status is
if (ServerSettings.isAuthzCacheEnabled()) {
// obtain an instance of AuthzCacheManager implementation.
AuthzCacheManager authzCacheManager = AuthzCacheManagerFactory.getAuthzCacheManager();
// check in the cache
AuthzCachedStatus authzCachedStatus = authzCacheManager.getAuthzCachedStatus(new AuthzCacheIndex(subject, gatewayId, accessToken, action));
if (AuthzCachedStatus.AUTHORIZED.equals(authzCachedStatus)) {
logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is retrieved from cache.");
return true;
} else if (AuthzCachedStatus.NOT_AUTHORIZED.equals(authzCachedStatus)) {
logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is retrieved from cache.");
return false;
} else if (AuthzCachedStatus.NOT_CACHED.equals(authzCachedStatus)) {
logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is not in the cache. " + "Obtaining it from the authorization server.");
CredentialStoreService.Client csClient = getCredentialStoreServiceClient();
GatewayResourceProfile gwrp = getRegistryServiceClient().getGatewayResourceProfile(gatewayId);
PasswordCredential credential = csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID());
String username = credential.getLoginUserName();
if (gwrp.getIdentityServerTenant() != null && !gwrp.getIdentityServerTenant().isEmpty())
username = username + "@" + gwrp.getIdentityServerTenant();
String password = credential.getPassword();
// talk to Authorization Server, obtain the decision, cache it and return the result.
ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
// initialize SSL context with the trust store that contains the public cert of WSO2 Identity Server.
TrustStoreManager trustStoreManager = new TrustStoreManager();
trustStoreManager.initializeTrustStoreManager(ServerSettings.getTrustStorePath(), ServerSettings.getTrustStorePassword());
DefaultOAuthClient oauthClient = new DefaultOAuthClient(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
OAuth2TokenValidationResponseDTO validationResponse = oauthClient.validateAccessToken(authzToken.getAccessToken());
if (validationResponse.getValid()) {
String authorizedUserName = validationResponse.getAuthorizedUser();
if (authorizedUserName.contains("@")) {
authorizedUserName = authorizedUserName.split("@")[0];
}
if (subject.contains("@")) {
subject = subject.split("@")[0];
}
// cannot impersonate users
if (!authorizedUserName.toLowerCase().equals(subject.toLowerCase()))
return false;
long expiryTimestamp = validationResponse.getExpiryTime();
// check for fine grained authorization for the API invocation, based on XACML.
DefaultXACMLPEP entitlementClient = new DefaultXACMLPEP(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
boolean authorizationDecision = entitlementClient.getAuthorizationDecision(authzToken, metaData);
// cache the authorization decision
authzCacheManager.addToAuthzCache(new AuthzCacheIndex(subject, gatewayId, accessToken, action), new AuthzCacheEntry(authorizationDecision, expiryTimestamp, System.currentTimeMillis()));
return authorizationDecision;
} else {
return false;
}
} else {
// undefined status returned from the authz cache manager
throw new AiravataSecurityException("Error in reading from the authorization cache.");
}
} else {
CredentialStoreService.Client csClient = getCredentialStoreServiceClient();
GatewayResourceProfile gwrp = getRegistryServiceClient().getGatewayResourceProfile(gatewayId);
PasswordCredential credential = csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID());
String username = credential.getLoginUserName();
if (gwrp.getIdentityServerTenant() != null && !gwrp.getIdentityServerTenant().isEmpty())
username = username + "@" + gwrp.getIdentityServerTenant();
String password = credential.getPassword();
// talk to Authorization Server, obtain the decision and return the result (authz cache is not enabled).
ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
// initialize SSL context with the trust store that contains the public cert of WSO2 Identity Server.
TrustStoreManager trustStoreManager = new TrustStoreManager();
trustStoreManager.initializeTrustStoreManager(ServerSettings.getTrustStorePath(), ServerSettings.getTrustStorePassword());
DefaultOAuthClient oauthClient = new DefaultOAuthClient(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
OAuth2TokenValidationResponseDTO validationResponse = oauthClient.validateAccessToken(authzToken.getAccessToken());
boolean isOAuthTokenValid = validationResponse.getValid();
// if XACML based authorization is enabled, check for role based authorization for the API invocation
DefaultXACMLPEP entitlementClient = new DefaultXACMLPEP(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
boolean authorizationDecision = entitlementClient.getAuthorizationDecision(authzToken, metaData);
return (isOAuthTokenValid && authorizationDecision);
}
} catch (AxisFault axisFault) {
logger.error(axisFault.getMessage(), axisFault);
throw new AiravataSecurityException("Error in initializing the configuration context for creating the OAuth validation client.");
} catch (ApplicationSettingsException e) {
logger.error(e.getMessage(), e);
throw new AiravataSecurityException("Error in reading OAuth server configuration.");
} catch (RegistryServiceException e) {
logger.error(e.getMessage(), e);
throw new AiravataSecurityException("Error in accessing AppCatalog.");
} catch (TException e) {
logger.error(e.getMessage(), e);
throw new AiravataSecurityException("Error in connecting to Credential Store Service.");
}
}
use of org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO in project airavata by apache.
the class AuthResponse method main.
public static void main(String[] args) throws AuthenticationException, AiravataSecurityException, AxisFault {
String accessToken = authenticate("master@master.airavata", "master").getAccess_token();
ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
DefaultOAuthClient defaultOAuthClient = new DefaultOAuthClient(hostName + "/services/", username, password, configContext);
OAuth2TokenValidationResponseDTO tokenValidationRequestDTO = defaultOAuthClient.validateAccessToken(accessToken);
String authorizedUser = tokenValidationRequestDTO.getAuthorizedUser();
AuthzToken authzToken = new AuthzToken();
authzToken.setAccessToken(accessToken);
Map<String, String> claimsMap = new HashMap<>();
claimsMap.put(Constants.USER_NAME, "scigap_admin");
claimsMap.put(Constants.API_METHOD_NAME, "/airavata/getAPIVersion");
authzToken.setClaimsMap(claimsMap);
DefaultXACMLPEP defaultXACMLPEP = new DefaultXACMLPEP(hostName + "/services/", username, password, configContext);
HashMap<String, String> metaDataMap = new HashMap();
boolean result = defaultXACMLPEP.getAuthorizationDecision(authzToken, metaDataMap);
System.out.println(result);
}
use of org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO in project carbon-apimgt by wso2.
the class SystemScopeIssuerImplTest method init.
@Before
public void init() throws IdentityOAuth2Exception {
systemScopesIssuer = Mockito.mock(SystemScopesIssuer.class);
oAuth2AuthorizeReqDTO = new OAuth2AuthorizeReqDTO();
String[] scopes = { "test", "test1" };
restAPIScopes.put("test", "test");
authenticatedUser = Mockito.mock(AuthenticatedUser.class);
Mockito.when(systemScopesIssuer.getAppScopes(Mockito.anyString(), Mockito.anyObject(), Mockito.anyList())).thenReturn(restAPIScopes);
Mockito.when(systemScopesIssuer.validateScope((OAuthAuthzReqMessageContext) Mockito.anyObject())).thenReturn(true);
oAuth2AuthorizeReqDTO.setScopes(scopes);
oAuth2AuthorizeReqDTO.setUser(authenticatedUser);
oAuthAuthzReqMessageContext = new OAuthAuthzReqMessageContext(oAuth2AuthorizeReqDTO);
oAuth2AccessTokenReqDTO = new OAuth2AccessTokenReqDTO();
oAuth2AccessTokenReqDTO.setScope(scopes);
oAuthTokenReqMessageContext = new OAuthTokenReqMessageContext(oAuth2AccessTokenReqDTO);
Mockito.when(systemScopesIssuer.validateScope((OAuthTokenReqMessageContext) Mockito.anyObject())).thenReturn(true);
oAuth2TokenValidationRequestDTO = new OAuth2TokenValidationRequestDTO();
oAuth2TokenValidationResponseDTO = new OAuth2TokenValidationResponseDTO();
oAuth2TokenValidationMessageContext = new OAuth2TokenValidationMessageContext(oAuth2TokenValidationRequestDTO, oAuth2TokenValidationResponseDTO);
Mockito.when(systemScopesIssuer.validateScope((OAuth2TokenValidationMessageContext) Mockito.anyObject())).thenReturn(true);
}
use of org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO 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