use of org.wso2.carbon.identity.oauth2.OAuth2Service in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuthRevocationEndpointTest method testRevokeAccessToken.
@Test(dataProvider = "testRevokeAccessTokenDataProvider")
public void testRevokeAccessToken(String authzHeader, boolean addReqParams, String token, String tokenHint, String callback, String clientId, String secret, String respError, Object headerObj, Exception e, int expectedStatus, String expectedErrorCode) throws Exception {
MultivaluedMap<String, String> parameterMap = new MultivaluedHashMap<String, String>();
ResponseHeader[] responseHeaders = (ResponseHeader[]) headerObj;
parameterMap.add(TOKEN_PARAM, token);
parameterMap.add(TOKEN_TYPE_HINT_PARAM, tokenHint);
parameterMap.add(CALLBACK_PARAM, callback);
Map<String, String[]> requestedParams = new HashMap<>();
if (addReqParams) {
requestedParams.put(TOKEN_PARAM, new String[] { "" });
requestedParams.put(TOKEN_TYPE_HINT_PARAM, new String[] { "" });
requestedParams.put(CALLBACK_PARAM, new String[] { "" });
}
mockStatic(LoggerUtils.class);
when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
mockStatic(IdentityTenantUtil.class);
when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(-1234);
HttpServletRequest request = mockHttpRequest(requestedParams, new HashMap<String, Object>());
when(request.getHeader(OAuthConstants.HTTP_REQ_HEADER_AUTHZ)).thenReturn(authzHeader);
spy(EndpointUtil.class);
doReturn(oAuth2Service).when(EndpointUtil.class, "getOAuth2Service");
final OAuthRevocationRequestDTO[] revokeReqDTO;
revokeReqDTO = new OAuthRevocationRequestDTO[1];
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
revokeReqDTO[0] = (OAuthRevocationRequestDTO) invocation.getArguments()[0];
return oAuthRevocationResponseDTO;
}
}).when(oAuth2Service).revokeTokenByOAuthClient(any(OAuthRevocationRequestDTO.class));
when(oAuthRevocationResponseDTO.getErrorCode()).thenReturn(respError);
when(oAuthRevocationResponseDTO.getErrorMsg()).thenReturn(respError);
when(oAuthRevocationResponseDTO.getResponseHeaders()).thenReturn(responseHeaders);
Response response;
try {
response = revocationEndpoint.revokeAccessToken(request, parameterMap);
} catch (InvalidRequestParentException ire) {
InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
response = invalidRequestExceptionMapper.toResponse(ire);
}
assertNotNull(response, "Token response is null");
assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
assertNotNull(response.getEntity(), "Response entity is null");
if (expectedErrorCode != null) {
assertTrue(response.getEntity().toString().contains(expectedErrorCode), "Expected error code not found");
if (StringUtils.isNotEmpty(callback)) {
assertTrue(response.getEntity().toString().contains(callback), "Callback is not added to the response");
}
}
}
use of org.wso2.carbon.identity.oauth2.OAuth2Service in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2TokenEndpointTest method testIssueAccessToken.
@Test(dataProvider = "testIssueAccessTokenDataProvider", groups = "testWithConnection")
public void testIssueAccessToken(String clientId, String authzHeader, Object paramMapObj, String grantType, String idToken, Object headerObj, Object customResponseParamObj, Exception e, int expectedStatus, String expectedErrorCode) throws Exception {
MultivaluedMap<String, String> paramMap = (MultivaluedMap<String, String>) paramMapObj;
ResponseHeader[] responseHeaders = (ResponseHeader[]) headerObj;
Map<String, String> customResponseParameters = (Map<String, String>) customResponseParamObj;
Map<String, String[]> requestParams = new HashMap<>();
if (clientId != null) {
requestParams.put(OAuth.OAUTH_CLIENT_ID, clientId.split(","));
}
requestParams.put(OAuth.OAUTH_GRANT_TYPE, new String[] { grantType });
requestParams.put(OAuth.OAUTH_SCOPE, new String[] { "scope1" });
requestParams.put(OAuth.OAUTH_REDIRECT_URI, new String[] { APP_REDIRECT_URL });
requestParams.put(OAuth.OAUTH_USERNAME, new String[] { USERNAME });
requestParams.put(OAuth.OAUTH_PASSWORD, new String[] { "password" });
mockStatic(LoggerUtils.class);
when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
mockStatic(IdentityTenantUtil.class);
when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(-1234);
HttpServletRequest request = mockHttpRequest(requestParams, new HashMap<String, Object>());
when(request.getHeader(OAuthConstants.HTTP_REQ_HEADER_AUTHZ)).thenReturn(authzHeader);
when(request.getHeaderNames()).thenReturn(Collections.enumeration(new ArrayList<String>() {
{
add(OAuthConstants.HTTP_REQ_HEADER_AUTHZ);
}
}));
spy(EndpointUtil.class);
doReturn(REALM).when(EndpointUtil.class, "getRealmInfo");
doReturn(oAuth2Service).when(EndpointUtil.class, "getOAuth2Service");
when(oAuth2Service.issueAccessToken(any(OAuth2AccessTokenReqDTO.class))).thenReturn(oAuth2AccessTokenRespDTO);
when(oAuth2AccessTokenRespDTO.getAccessToken()).thenReturn(ACCESS_TOKEN);
when(oAuth2AccessTokenRespDTO.getRefreshToken()).thenReturn(REFRESH_TOKEN);
when(oAuth2AccessTokenRespDTO.getExpiresIn()).thenReturn(3600L);
when(oAuth2AccessTokenRespDTO.getAuthorizedScopes()).thenReturn("scope1");
when(oAuth2AccessTokenRespDTO.getIDToken()).thenReturn(idToken);
when(oAuth2AccessTokenRespDTO.getResponseHeaders()).thenReturn(responseHeaders);
when(oAuth2AccessTokenRespDTO.getParameters()).thenReturn(customResponseParameters);
mockOAuthServerConfiguration();
mockStatic(IdentityDatabaseUtil.class);
when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
Map<String, Class<? extends OAuthValidator<HttpServletRequest>>> grantTypeValidators = new Hashtable<>();
grantTypeValidators.put(GrantType.PASSWORD.toString(), PasswordValidator.class);
when(oAuthServerConfiguration.getSupportedGrantTypeValidators()).thenReturn(grantTypeValidators);
when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
Response response;
try {
response = oAuth2TokenEndpoint.issueAccessToken(request, paramMap);
} catch (InvalidRequestParentException ire) {
InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
response = invalidRequestExceptionMapper.toResponse(ire);
}
assertNotNull(response, "Token response is null");
assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
assertNotNull(response.getEntity(), "Response entity is null");
final String responseBody = response.getEntity().toString();
if (customResponseParameters != null) {
customResponseParameters.forEach((key, value) -> assertTrue(responseBody.contains(key) && responseBody.contains(value), "Expected custom response parameter: " + key + " not found in token response."));
}
if (expectedErrorCode != null) {
assertTrue(responseBody.contains(expectedErrorCode), "Expected error code not found");
} else if (HttpServletResponse.SC_OK == expectedStatus) {
assertTrue(responseBody.contains(ACCESS_TOKEN), "Successful response should contain access token");
}
}
use of org.wso2.carbon.identity.oauth2.OAuth2Service in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2TokenEndpointTest method testGetAccessToken.
@Test(dataProvider = "testGetAccessTokenDataProvider")
public void testGetAccessToken(String grantType, String additionalParameters) throws Exception {
Map<String, String[]> requestParams = new HashMap<>();
requestParams.put(OAuth.OAUTH_CLIENT_ID, new String[] { CLIENT_ID_VALUE });
requestParams.put(OAuth.OAUTH_GRANT_TYPE, new String[] { grantType });
requestParams.put(OAuth.OAUTH_SCOPE, new String[] { "scope1" });
// Required params for authorization_code grant type
requestParams.put(OAuth.OAUTH_REDIRECT_URI, new String[] { APP_REDIRECT_URL });
requestParams.put(OAuth.OAUTH_CODE, new String[] { "auth_code" });
// Required params for password grant type
requestParams.put(OAuth.OAUTH_USERNAME, new String[] { USERNAME });
requestParams.put(OAuth.OAUTH_PASSWORD, new String[] { "password" });
// Required params for refresh token grant type
requestParams.put(OAuth.OAUTH_REFRESH_TOKEN, new String[] { REFRESH_TOKEN });
// Required params for saml2 bearer grant type
requestParams.put(OAuth.OAUTH_ASSERTION, new String[] { "dummyAssertion" });
// Required params for IWA_NLTM grant type
requestParams.put(OAuthConstants.WINDOWS_TOKEN, new String[] { "dummyWindowsToken" });
HttpServletRequest request = mockHttpRequest(requestParams, new HashMap<String, Object>());
when(request.getHeader(OAuthConstants.HTTP_REQ_HEADER_AUTHZ)).thenReturn(AUTHORIZATION_HEADER);
when(request.getHeaderNames()).thenReturn(Collections.enumeration(new ArrayList<String>() {
{
add(OAuthConstants.HTTP_REQ_HEADER_AUTHZ);
}
}));
Map<String, Class<? extends OAuthValidator<HttpServletRequest>>> grantTypeValidators = new Hashtable<>();
grantTypeValidators.put(GrantType.PASSWORD.toString(), PasswordValidator.class);
grantTypeValidators.put(GrantType.CLIENT_CREDENTIALS.toString(), ClientCredentialValidator.class);
grantTypeValidators.put(GrantType.AUTHORIZATION_CODE.toString(), AuthorizationCodeValidator.class);
grantTypeValidators.put(GrantType.REFRESH_TOKEN.toString(), RefreshTokenValidator.class);
grantTypeValidators.put(org.wso2.carbon.identity.oauth.common.GrantType.IWA_NTLM.toString(), NTLMAuthenticationValidator.class);
grantTypeValidators.put(org.wso2.carbon.identity.oauth.common.GrantType.SAML20_BEARER.toString(), SAML2GrantValidator.class);
mockOAuthServerConfiguration();
when(oAuthServerConfiguration.getSupportedGrantTypeValidators()).thenReturn(grantTypeValidators);
spy(EndpointUtil.class);
doReturn(oAuth2Service).when(EndpointUtil.class, "getOAuth2Service");
final Map<String, String> parametersSetToRequest = new HashMap<>();
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
OAuth2AccessTokenReqDTO request = (OAuth2AccessTokenReqDTO) invocation.getArguments()[0];
parametersSetToRequest.put(OAuth.OAUTH_CODE, request.getAuthorizationCode());
parametersSetToRequest.put(OAuth.OAUTH_USERNAME, request.getResourceOwnerUsername());
parametersSetToRequest.put(OAuth.OAUTH_PASSWORD, request.getResourceOwnerPassword());
parametersSetToRequest.put(OAuth.OAUTH_REFRESH_TOKEN, request.getRefreshToken());
parametersSetToRequest.put(OAuth.OAUTH_ASSERTION, request.getAssertion());
parametersSetToRequest.put(OAuthConstants.WINDOWS_TOKEN, request.getWindowsToken());
parametersSetToRequest.put(OAuth.OAUTH_GRANT_TYPE, request.getGrantType());
OAuth2AccessTokenRespDTO tokenRespDTO = new OAuth2AccessTokenRespDTO();
return tokenRespDTO;
}
}).when(oAuth2Service).issueAccessToken(any(OAuth2AccessTokenReqDTO.class));
CarbonOAuthTokenRequest oauthRequest = new CarbonOAuthTokenRequest(request);
HttpServletRequestWrapper httpServletRequestWrapper = new HttpServletRequestWrapper(request);
Class<?> clazz = OAuth2TokenEndpoint.class;
Object tokenEndpointObj = clazz.newInstance();
Method getAccessToken = tokenEndpointObj.getClass().getDeclaredMethod("issueAccessToken", CarbonOAuthTokenRequest.class, HttpServletRequestWrapper.class);
getAccessToken.setAccessible(true);
OAuth2AccessTokenRespDTO tokenRespDTO = (OAuth2AccessTokenRespDTO) getAccessToken.invoke(tokenEndpointObj, oauthRequest, httpServletRequestWrapper);
assertNotNull(tokenRespDTO, "ResponseDTO is null");
String[] paramsToCheck = additionalParameters.split(",");
for (String param : paramsToCheck) {
assertNotNull(parametersSetToRequest.get(param), "Required parameter " + param + " is not set for " + grantType + "grant type");
}
}
use of org.wso2.carbon.identity.oauth2.OAuth2Service in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuthServiceComponent method activate.
protected void activate(ComponentContext context) {
try {
// initialize the OAuth Server configuration
OAuthServerConfiguration oauthServerConfig = OAuthServerConfiguration.getInstance();
if (OAuthCache.getInstance().isEnabled()) {
log.debug("OAuth Caching is enabled. Initializing the cache.");
}
IdentityOathEventListener listener = new IdentityOathEventListener();
serviceRegistration = context.getBundleContext().registerService(UserOperationEventListener.class.getName(), listener, null);
log.debug("Identity Oath Event Listener is enabled");
context.getBundleContext().registerService(AbstractEventHandler.class.getName(), new IdentityOauthEventHandler(), null);
if (log.isDebugEnabled()) {
log.debug("Identity Oauth Event handler is enabled");
}
OAuth2Service oauth2Service = new OAuth2Service();
context.getBundleContext().registerService(OAuth2Service.class.getName(), oauth2Service, null);
OAuthComponentServiceHolder.getInstance().setOauth2Service(oauth2Service);
// We need to explicitly populate the OAuthTokenIssuerMap since it's used for token validation.
oauthServerConfig.populateOAuthTokenIssuerMap();
OAuthAdminServiceImpl oauthAdminService = new OAuthAdminServiceImpl();
OAuthComponentServiceHolder.getInstance().setOAuthAdminService(oauthAdminService);
OAuth2ServiceComponentHolder.getInstance().setOAuthAdminService(oauthAdminService);
context.getBundleContext().registerService(OAuthEventInterceptor.class, new OAuthTokenSessionMappingEventHandler(), null);
if (log.isDebugEnabled()) {
log.debug("OAuthTokenSessionMapping Event Handler is enabled");
}
context.getBundleContext().registerService(OAuthAdminServiceImpl.class.getName(), oauthAdminService, null);
if (log.isDebugEnabled()) {
log.debug("Identity OAuth bundle is activated");
}
} catch (Throwable e) {
String errMsg = "Error occurred while activating OAuth Service Component";
log.error(errMsg, e);
throw new RuntimeException(errMsg, e);
}
}
use of org.wso2.carbon.identity.oauth2.OAuth2Service in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2ServiceComponent method activate.
protected void activate(ComponentContext context) {
try {
if (OAuth2ServiceComponentHolder.getInstance().getScopeClaimMappingDAO() == null) {
OAuth2ServiceComponentHolder.getInstance().setScopeClaimMappingDAO(new ScopeClaimMappingDAOImpl());
}
loadScopeConfigFile();
loadOauthScopeBinding();
int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
boolean isRecordExist = OAuthTokenPersistenceFactory.getInstance().getScopeClaimMappingDAO().hasScopesPopulated(tenantId);
if (!isRecordExist) {
OAuth2Util.initiateOIDCScopes(tenantId);
}
TenantCreationEventListener scopeTenantMgtListener = new TenantCreationEventListener();
bundleContext = context.getBundleContext();
// Registering TenantCreationEventListener
ServiceRegistration scopeTenantMgtListenerSR = bundleContext.registerService(TenantMgtListener.class.getName(), scopeTenantMgtListener, null);
if (scopeTenantMgtListenerSR != null) {
if (log.isDebugEnabled()) {
log.debug(" TenantMgtListener is registered");
}
} else {
log.error("TenantMgtListener could not be registered");
}
// iniating oauth scopes
OAuth2Util.initiateOAuthScopePermissionsBindings(tenantId);
// exposing server configuration as a service
OAuthServerConfiguration oauthServerConfig = OAuthServerConfiguration.getInstance();
bundleContext.registerService(OAuthServerConfiguration.class.getName(), oauthServerConfig, null);
OAuth2TokenValidationService tokenValidationService = new OAuth2TokenValidationService();
bundleContext.registerService(OAuth2TokenValidationService.class.getName(), tokenValidationService, null);
OAuthClientAuthnService clientAuthnService = new OAuthClientAuthnService();
bundleContext.registerService(OAuthClientAuthnService.class.getName(), clientAuthnService, null);
BasicAuthClientAuthenticator basicAuthClientAuthenticator = new BasicAuthClientAuthenticator();
bundleContext.registerService(OAuthClientAuthenticator.class.getName(), basicAuthClientAuthenticator, null);
PublicClientAuthenticator publicClientAuthenticator = new PublicClientAuthenticator();
bundleContext.registerService(OAuthClientAuthenticator.class.getName(), publicClientAuthenticator, null);
// Register cookie based access token binder.
CookieBasedTokenBinder cookieBasedTokenBinder = new CookieBasedTokenBinder();
bundleContext.registerService(TokenBinderInfo.class.getName(), cookieBasedTokenBinder, null);
// SSO session based access token binder.
SSOSessionBasedTokenBinder ssoSessionBasedTokenBinder = new SSOSessionBasedTokenBinder();
bundleContext.registerService(TokenBinderInfo.class.getName(), ssoSessionBasedTokenBinder, null);
if (log.isDebugEnabled()) {
log.debug("Identity OAuth bundle is activated");
}
if (OAuth2ServiceComponentHolder.getKeyIDProvider() == null) {
KeyIDProvider defaultKeyIDProvider = new DefaultKeyIDProviderImpl();
OAuth2ServiceComponentHolder.setKeyIDProvider(defaultKeyIDProvider);
if (log.isDebugEnabled()) {
log.debug("Key ID Provider " + DefaultKeyIDProviderImpl.class.getSimpleName() + " registered as the default Key ID Provider implementation.");
}
}
ServiceRegistration tenantMgtListenerSR = bundleContext.registerService(TenantMgtListener.class.getName(), new OAuthTenantMgtListenerImpl(), null);
if (tenantMgtListenerSR != null) {
if (log.isDebugEnabled()) {
log.debug("OAuth - TenantMgtListener registered.");
}
} else {
log.error("OAuth - TenantMgtListener could not be registered.");
}
ServiceRegistration userStoreConfigEventSR = bundleContext.registerService(UserStoreConfigListener.class.getName(), new OAuthUserStoreConfigListenerImpl(), null);
if (userStoreConfigEventSR != null) {
if (log.isDebugEnabled()) {
log.debug("OAuth - UserStoreConfigListener registered.");
}
} else {
log.error("OAuth - UserStoreConfigListener could not be registered.");
}
ServiceRegistration oauthApplicationMgtListenerSR = bundleContext.registerService(ApplicationMgtListener.class.getName(), new OAuthApplicationMgtListener(), null);
if (oauthApplicationMgtListenerSR != null) {
if (log.isDebugEnabled()) {
log.debug("OAuth - ApplicationMgtListener registered.");
}
} else {
log.error("OAuth - ApplicationMgtListener could not be registered.");
}
// PKCE enabled by default.
OAuth2ServiceComponentHolder.setPkceEnabled(true);
// Register device auth service.
ServiceRegistration deviceAuthService = bundleContext.registerService(DeviceAuthService.class.getName(), new DeviceAuthServiceImpl(), null);
if (deviceAuthService != null) {
if (log.isDebugEnabled()) {
log.debug("DeviceAuthService registered.");
}
} else {
log.error("DeviceAuthService could not be registered.");
}
// Register the default OpenIDConnect claim filter
bundleContext.registerService(OpenIDConnectClaimFilter.class, new OpenIDConnectClaimFilterImpl(), null);
if (log.isDebugEnabled()) {
log.debug("Default OpenIDConnect Claim filter registered successfully.");
}
bundleContext.registerService(AbstractEventHandler.class.getName(), new TokenBindingExpiryEventHandler(), null);
if (log.isDebugEnabled()) {
log.debug("TokenBindingExpiryEventHandler is successfully registered.");
}
// Registering OAuth2Service as a OSGIService
bundleContext.registerService(OAuth2Service.class.getName(), new OAuth2Service(), null);
// Registering OAuth2ScopeService as a OSGIService
bundleContext.registerService(OAuth2ScopeService.class.getName(), new OAuth2ScopeService(), null);
// Note : DO NOT add any activation related code below this point,
// to make sure the server doesn't start up if any activation failures occur
} catch (Throwable e) {
String errMsg = "Error while activating OAuth2ServiceComponent.";
log.error(errMsg, e);
throw new RuntimeException(errMsg, e);
}
if (checkAudienceEnabled()) {
if (log.isDebugEnabled()) {
log.debug("OAuth - OIDC audiences enabled.");
}
OAuth2ServiceComponentHolder.setAudienceEnabled(true);
} else {
if (log.isDebugEnabled()) {
log.debug("OAuth - OIDC audiences disabled.");
}
OAuth2ServiceComponentHolder.setAudienceEnabled(false);
}
if (checkIDPIdColumnAvailable()) {
if (log.isDebugEnabled()) {
log.debug("IDP_ID column is available in all relevant tables. " + "Setting isIDPIdColumnEnabled to true.");
}
OAuth2ServiceComponentHolder.setIDPIdColumnEnabled(true);
} else {
if (log.isDebugEnabled()) {
log.debug("IDP_ID column is not available in all relevant tables. " + "Setting isIDPIdColumnEnabled to false.");
}
OAuth2ServiceComponentHolder.setIDPIdColumnEnabled(false);
}
}
Aggregations