use of org.wso2.carbon.apimgt.core.models.AccessTokenInfo in project product-apim by wso2.
the class TestUtil method generateToken.
private static void generateToken(String username, String password, String scopes) throws APIManagementException {
if (StringUtils.isEmpty(clientId) | StringUtils.isEmpty(clientSecret)) {
generateClient();
}
OAuth2ServiceStubs.TokenServiceStub tokenServiceStub = getOauth2Client();
Response response = tokenServiceStub.generatePasswordGrantAccessToken(username, password, scopes, -1, clientId, clientSecret);
if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_200_OK) {
// 200 - Success
logger.debug("A new access token is successfully generated.");
try {
OAuth2TokenInfo oAuth2TokenInfo = (OAuth2TokenInfo) new GsonDecoder().decode(response, OAuth2TokenInfo.class);
accessTokenInfo = new TokenInfo(oAuth2TokenInfo.getAccessToken(), System.currentTimeMillis() + oAuth2TokenInfo.getExpiresIn());
} catch (IOException e) {
throw new KeyManagementException("Error occurred while parsing token response", e, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
}
}
}
use of org.wso2.carbon.apimgt.core.models.AccessTokenInfo in project carbon-apimgt by wso2.
the class DefaultKeyManagerImpl method getTokenMetaData.
@Override
public AccessTokenInfo getTokenMetaData(String accessToken) throws KeyManagementException {
log.debug("Token introspection request is being sent.");
Response response;
try {
response = oAuth2ServiceStubs.getIntrospectionServiceStub().introspectToken(accessToken);
} catch (APIManagementException e) {
throw new KeyManagementException("Error occurred while introspecting access token.", e, ExceptionCodes.TOKEN_INTROSPECTION_FAILED);
}
if (response == null) {
throw new KeyManagementException("Error occurred while introspecting access token. " + "Response is null", ExceptionCodes.TOKEN_INTROSPECTION_FAILED);
}
if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_200_OK) {
log.debug("Token introspection is successful");
try {
OAuth2IntrospectionResponse introspectResponse = (OAuth2IntrospectionResponse) new GsonDecoder().decode(response, OAuth2IntrospectionResponse.class);
AccessTokenInfo tokenInfo = new AccessTokenInfo();
boolean active = introspectResponse.isActive();
if (active) {
tokenInfo.setTokenValid(true);
tokenInfo.setAccessToken(accessToken);
tokenInfo.setScopes(introspectResponse.getScope());
tokenInfo.setConsumerKey(introspectResponse.getClientId());
tokenInfo.setIssuedTime(introspectResponse.getIat());
tokenInfo.setExpiryTime(introspectResponse.getExp());
if (StringUtils.isNotEmpty(introspectResponse.getUsername())) {
tokenInfo.setEndUserName(introspectResponse.getUsername());
}
long validityPeriod = introspectResponse.getExp() - introspectResponse.getIat();
tokenInfo.setValidityPeriod(validityPeriod);
} else {
tokenInfo.setTokenValid(false);
log.error("Invalid or expired access token received.");
tokenInfo.setErrorCode(KeyManagerConstants.KeyValidationStatus.API_AUTH_INVALID_CREDENTIALS);
}
return tokenInfo;
} catch (IOException e) {
throw new KeyManagementException("Error occurred while parsing token introspection response", e, ExceptionCodes.TOKEN_INTROSPECTION_FAILED);
}
} else {
throw new KeyManagementException("Token introspection request failed. HTTP error code: " + response.status() + " Error Response Body: " + response.body().toString(), ExceptionCodes.TOKEN_INTROSPECTION_FAILED);
}
}
use of org.wso2.carbon.apimgt.core.models.AccessTokenInfo in project carbon-apimgt by wso2.
the class DefaultKeyManagerImpl method getNewAccessToken.
@Override
public AccessTokenInfo getNewAccessToken(AccessTokenRequest tokenRequest) throws KeyManagementException {
if (tokenRequest == null) {
throw new KeyManagementException("No information available to generate Token. AccessTokenRequest is null", ExceptionCodes.INVALID_TOKEN_REQUEST);
}
// Call the /revoke only if there's a token to be revoked.
if (!StringUtils.isEmpty(tokenRequest.getTokenToRevoke())) {
this.revokeAccessToken(tokenRequest.getTokenToRevoke(), tokenRequest.getClientId(), tokenRequest.getClientSecret());
}
// When validity time set to a negative value, a token is considered never to expire.
if (tokenRequest.getValidityPeriod() == -1L) {
// Setting a different negative value if the set value is -1 (-1 will be ignored by TokenValidator)
tokenRequest.setValidityPeriod(-2L);
}
Response response;
try {
if (KeyManagerConstants.CLIENT_CREDENTIALS_GRANT_TYPE.equals(tokenRequest.getGrantType())) {
response = oAuth2ServiceStubs.getTokenServiceStub().generateClientCredentialsGrantAccessToken(tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret());
} else if (KeyManagerConstants.PASSWORD_GRANT_TYPE.equals(tokenRequest.getGrantType())) {
response = oAuth2ServiceStubs.getTokenServiceStub().generatePasswordGrantAccessToken(tokenRequest.getResourceOwnerUsername(), tokenRequest.getResourceOwnerPassword(), tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret());
} else if (KeyManagerConstants.AUTHORIZATION_CODE_GRANT_TYPE.equals(tokenRequest.getGrantType())) {
response = oAuth2ServiceStubs.getTokenServiceStub().generateAuthCodeGrantAccessToken(tokenRequest.getAuthorizationCode(), tokenRequest.getCallbackURI(), tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret());
} else if (KeyManagerConstants.REFRESH_GRANT_TYPE.equals(tokenRequest.getGrantType())) {
response = oAuth2ServiceStubs.getTokenServiceStub().generateRefreshGrantAccessToken(tokenRequest.getRefreshToken(), tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret());
} else if (KeyManagerConstants.JWT_GRANT_TYPE.equals(tokenRequest.getGrantType())) {
response = oAuth2ServiceStubs.getTokenServiceStub().generateJWTGrantAccessToken(tokenRequest.getAssertion(), KeyManagerConstants.JWT_GRANT_TYPE, tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret());
} else {
throw new KeyManagementException("Invalid access token request. Unsupported grant type: " + tokenRequest.getGrantType(), ExceptionCodes.INVALID_TOKEN_REQUEST);
}
} catch (APIManagementException ex) {
throw new KeyManagementException("Token generation request failed. Error: " + ex.getMessage(), ex, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
}
if (response == null) {
throw new KeyManagementException("Error occurred while generating an access token. " + "Response is null", ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
}
if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_200_OK) {
// 200 - Success
log.debug("A new access token is successfully generated.");
try {
OAuth2TokenInfo oAuth2TokenInfo = (OAuth2TokenInfo) new GsonDecoder().decode(response, OAuth2TokenInfo.class);
AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
accessTokenInfo.setAccessToken(oAuth2TokenInfo.getAccessToken());
accessTokenInfo.setScopes(oAuth2TokenInfo.getScope());
accessTokenInfo.setRefreshToken(oAuth2TokenInfo.getRefreshToken());
accessTokenInfo.setIdToken(oAuth2TokenInfo.getIdToken());
accessTokenInfo.setValidityPeriod(oAuth2TokenInfo.getExpiresIn());
return accessTokenInfo;
} catch (IOException e) {
throw new KeyManagementException("Error occurred while parsing token response", e, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
}
} else {
// Error case
throw new KeyManagementException("Token generation request failed. HTTP error code: " + response.status() + " Error Response Body: " + response.body().toString(), ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
}
}
use of org.wso2.carbon.apimgt.core.models.AccessTokenInfo in project carbon-apimgt by wso2.
the class AuthenticatorService method getTokens.
/**
* This method returns the access tokens for a given application.
*
* @param appName Name of the application which needs to get tokens
* @param grantType Grant type of the application
* @param userName User name of the user
* @param password Password of the user
* @param refreshToken Refresh token
* @param validityPeriod Validity period of tokens
* @param authorizationCode Authorization Code
* @return AccessTokenInfo - An object with the generated access token information
* @throws APIManagementException When receiving access tokens fails
*/
public AccessTokenInfo getTokens(String appName, String grantType, String userName, String password, String refreshToken, long validityPeriod, String authorizationCode, String assertion, IdentityProvider identityProvider) throws APIManagementException {
AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
MultiEnvironmentOverview multiEnvironmentOverviewConfigs = apimConfigurationService.getEnvironmentConfigurations().getMultiEnvironmentOverview();
boolean isMultiEnvironmentOverviewEnabled = multiEnvironmentOverviewConfigs.isEnabled();
// Get scopes of the application
String scopes = getApplicationScopes(appName);
log.debug("Set scopes for {} application using swagger definition.", appName);
// TODO: Get Consumer Key & Secret without creating a new app, from the IS side
Map<String, String> consumerKeySecretMap = getConsumerKeySecret(appName);
log.debug("Received consumer key & secret for {} application.", appName);
try {
if (KeyManagerConstants.AUTHORIZATION_CODE_GRANT_TYPE.equals(grantType)) {
// Access token for authorization code grant type
APIMAppConfigurations appConfigs = apimAppConfigurationService.getApimAppConfigurations();
String callBackURL = appConfigs.getApimBaseUrl() + AuthenticatorConstants.AUTHORIZATION_CODE_CALLBACK_URL + appName;
if (authorizationCode != null) {
// Get Access & Refresh Tokens
accessTokenRequest.setClientId(consumerKeySecretMap.get("CONSUMER_KEY"));
accessTokenRequest.setClientSecret(consumerKeySecretMap.get("CONSUMER_SECRET"));
accessTokenRequest.setGrantType(grantType);
accessTokenRequest.setAuthorizationCode(authorizationCode);
accessTokenRequest.setScopes(scopes);
accessTokenRequest.setValidityPeriod(validityPeriod);
accessTokenRequest.setCallbackURI(callBackURL);
accessTokenInfo = getKeyManager().getNewAccessToken(accessTokenRequest);
} else {
String errorMsg = "No Authorization Code available.";
log.error(errorMsg, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
throw new APIManagementException(errorMsg, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
}
} else if (KeyManagerConstants.PASSWORD_GRANT_TYPE.equals(grantType)) {
// Access token for password code grant type
accessTokenRequest = AuthUtil.createAccessTokenRequest(userName, password, grantType, refreshToken, null, validityPeriod, scopes, consumerKeySecretMap.get("CONSUMER_KEY"), consumerKeySecretMap.get("CONSUMER_SECRET"));
accessTokenInfo = getKeyManager().getNewAccessToken(accessTokenRequest);
} else if (KeyManagerConstants.REFRESH_GRANT_TYPE.equals(grantType)) {
accessTokenRequest = AuthUtil.createAccessTokenRequest(userName, password, grantType, refreshToken, null, validityPeriod, scopes, consumerKeySecretMap.get("CONSUMER_KEY"), consumerKeySecretMap.get("CONSUMER_SECRET"));
accessTokenInfo = getKeyManager().getNewAccessToken(accessTokenRequest);
} else if (isMultiEnvironmentOverviewEnabled) {
// JWT or Custom grant type
accessTokenRequest.setClientId(consumerKeySecretMap.get("CONSUMER_KEY"));
accessTokenRequest.setClientSecret(consumerKeySecretMap.get("CONSUMER_SECRET"));
accessTokenRequest.setAssertion(assertion);
// Pass grant type to extend a custom grant instead of JWT grant in the future
accessTokenRequest.setGrantType(KeyManagerConstants.JWT_GRANT_TYPE);
accessTokenRequest.setScopes(scopes);
accessTokenRequest.setValidityPeriod(validityPeriod);
accessTokenInfo = getKeyManager().getNewAccessToken(accessTokenRequest);
String usernameFromJWT = getUsernameFromJWT(accessTokenInfo.getIdToken());
try {
identityProvider.getIdOfUser(usernameFromJWT);
} catch (IdentityProviderException e) {
String errorMsg = "User " + usernameFromJWT + " does not exists in this environment.";
throw new APIManagementException(errorMsg, e, ExceptionCodes.USER_NOT_AUTHENTICATED);
}
}
} catch (KeyManagementException e) {
String errorMsg = "Error while receiving tokens for OAuth application : " + appName;
log.error(errorMsg, e, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
throw new APIManagementException(errorMsg, e, ExceptionCodes.ACCESS_TOKEN_GENERATION_FAILED);
}
log.debug("Received access token for {} application.", appName);
return accessTokenInfo;
}
use of org.wso2.carbon.apimgt.core.models.AccessTokenInfo in project carbon-apimgt by wso2.
the class DefaultKeyManagerImplTestCase method createExpectedKeyManagerResponse.
private AccessTokenInfo createExpectedKeyManagerResponse(OAuth2TokenInfo oAuth2TokenInfo) {
AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
accessTokenInfo.setAccessToken(oAuth2TokenInfo.getAccessToken());
accessTokenInfo.setScopes(oAuth2TokenInfo.getScope());
accessTokenInfo.setRefreshToken(oAuth2TokenInfo.getRefreshToken());
accessTokenInfo.setIdToken(oAuth2TokenInfo.getIdToken());
accessTokenInfo.setValidityPeriod(oAuth2TokenInfo.getExpiresIn());
return accessTokenInfo;
}
Aggregations