use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.
the class OpenIDConnectUserEndpoint method getUserClaims.
@GET
@Path("/")
@Consumes("application/x-www-form-urlencoded")
public Response getUserClaims(@Context HttpServletRequest request) throws OAuthSystemException {
String userInfoResponse;
String userInfoResponseContentType;
try {
// validate the request
UserInfoRequestValidator requestValidator = UserInfoEndpointConfig.getInstance().getUserInfoRequestValidator();
String accessToken = requestValidator.validateRequest(request);
// validate the access token
UserInfoAccessTokenValidator tokenValidator = UserInfoEndpointConfig.getInstance().getUserInfoAccessTokenValidator();
OAuth2TokenValidationResponseDTO tokenResponse = tokenValidator.validateToken(accessToken, request);
// build the claims
// ToDO - Validate the grant type to be implicit or authorization_code before retrieving claims
UserInfoResponseBuilder userInfoResponseBuilder = UserInfoEndpointConfig.getInstance().getUserInfoResponseBuilder();
userInfoResponse = userInfoResponseBuilder.getResponseString(tokenResponse);
userInfoResponseContentType = getUserInfoResponseMediaType(userInfoResponseBuilder);
} catch (UserInfoEndpointException e) {
return handleError(e);
} catch (OAuthSystemException e) {
log.error("UserInfoEndpoint Failed", e);
throw new OAuthSystemException("UserInfoEndpoint Failed");
}
ResponseBuilder respBuilder = getResponseBuilderWithCacheControlHeaders();
if (userInfoResponse != null) {
return respBuilder.type(userInfoResponseContentType).entity(userInfoResponse).build();
}
return respBuilder.build();
}
use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.
the class EndpointUtil method setConsentRequiredScopesToOAuthParams.
private static void setConsentRequiredScopesToOAuthParams(AuthenticatedUser user, OAuth2Parameters params) throws OAuthSystemException {
try {
String consentRequiredScopes = StringUtils.EMPTY;
List<String> allowedOAuthScopes = getAllowedOAuthScopes(params);
if (user != null && !isPromptContainsConsent(params)) {
String userId = getUserIdOfAuthenticatedUser(user);
String appId = getAppIdFromClientId(params.getClientId());
OAuth2ScopeConsentResponse existingUserConsent = oAuth2ScopeService.getUserConsentForApp(userId, appId, IdentityTenantUtil.getTenantId(user.getTenantDomain()));
if (existingUserConsent != null) {
if (CollectionUtils.isNotEmpty(existingUserConsent.getApprovedScopes())) {
allowedOAuthScopes.removeAll(existingUserConsent.getApprovedScopes());
}
}
}
if (CollectionUtils.isNotEmpty(allowedOAuthScopes)) {
// Filter out internal scopes to be validated.
String[] requestedScopes = Oauth2ScopeUtils.getRequestedScopes(allowedOAuthScopes.toArray(new String[0]));
if (ArrayUtils.isNotEmpty(requestedScopes)) {
// Remove the filtered internal scopes from the allowedOAuthScopes list.
allowedOAuthScopes.removeAll(Arrays.asList(requestedScopes));
JDBCPermissionBasedInternalScopeValidator scopeValidator = new JDBCPermissionBasedInternalScopeValidator();
String[] validatedScope = scopeValidator.validateScope(requestedScopes, user, params.getClientId());
// Filter out requested scopes from the validated scope array.
for (String scope : requestedScopes) {
if (ArrayUtils.contains(validatedScope, scope)) {
allowedOAuthScopes.add(scope);
}
}
}
params.setConsentRequiredScopes(new HashSet<>(allowedOAuthScopes));
consentRequiredScopes = String.join(" ", allowedOAuthScopes).trim();
}
if (log.isDebugEnabled()) {
log.debug("Consent required scopes : " + consentRequiredScopes + " for request from client : " + params.getClientId());
}
} catch (IdentityOAuth2ScopeException e) {
throw new OAuthSystemException("Error occurred while retrieving user consents OAuth scopes.");
}
}
use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.
the class EndpointUtilTest method testGetErrorRedirectURL.
@Test(dataProvider = "provideErrorRedirectData")
public void testGetErrorRedirectURL(boolean isImplicitResponse, boolean isImplicitFragment, Object oAuth2ParamObject, Object exeObject, String expected, boolean isDebugOn) throws Exception {
setMockedLog(isDebugOn);
OAuth2Parameters parameters = (OAuth2Parameters) oAuth2ParamObject;
OAuthProblemException exception = OAuthProblemException.error("OAuthProblemExceptionErrorMessage");
mockStatic(OAuthServerConfiguration.class);
when(OAuthServerConfiguration.getInstance()).thenReturn(mockedOAuthServerConfiguration);
when(mockedOAuthServerConfiguration.isImplicitErrorFragment()).thenReturn(isImplicitFragment);
mockStatic(OAuth2Util.class);
when(OAuth2Util.isImplicitResponseType(anyString())).thenReturn(isImplicitResponse);
mockStatic(OAuth2Util.OAuthURL.class);
when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);
mockStatic(OAuthResponse.OAuthErrorResponseBuilder.class);
whenNew(OAuthResponse.OAuthErrorResponseBuilder.class).withArguments(anyInt()).thenReturn(mockedOAuthErrorResponseBuilder);
when(mockedOAuthErrorResponseBuilder.error(any(OAuthProblemException.class))).thenReturn(mockedOAuthErrorResponseBuilder);
when(mockedOAuthErrorResponseBuilder.location(anyString())).thenReturn(mockedOAuthErrorResponseBuilder);
when(mockedOAuthErrorResponseBuilder.setState(anyString())).thenReturn(mockedOAuthErrorResponseBuilder);
when(mockedOAuthErrorResponseBuilder.setParam(anyString(), anyString())).thenReturn(mockedOAuthErrorResponseBuilder);
if (exeObject != null) {
OAuthSystemException oAuthSystemException = (OAuthSystemException) exeObject;
when(mockedOAuthErrorResponseBuilder.buildQueryMessage()).thenThrow(oAuthSystemException);
} else {
when(mockedOAuthErrorResponseBuilder.buildQueryMessage()).thenReturn(mockedOAuthResponse);
}
when(mockedOAuthResponse.getLocationUri()).thenReturn("http://localhost:8080/location");
String url = EndpointUtil.getErrorRedirectURL(exception, parameters);
Assert.assertTrue(url.contains(expected), "Expected error redirect url not returned");
}
use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.
the class EndpointUtilTest method testGetUserConsentURL.
@Test(dataProvider = "provideDataForUserConsentURL")
public void testGetUserConsentURL(Object oAuth2ParamObject, boolean isOIDC, boolean cacheEntryExists, boolean throwError, String queryString, boolean isDebugEnabled) throws Exception {
setMockedLog(isDebugEnabled);
OAuth2Parameters parameters = (OAuth2Parameters) oAuth2ParamObject;
mockStatic(OAuthServerConfiguration.class);
when(OAuthServerConfiguration.getInstance()).thenReturn(mockedOAuthServerConfiguration);
EndpointUtil.setOauthServerConfiguration(mockedOAuthServerConfiguration);
when(mockedOAuthServerConfiguration.isDropUnregisteredScopes()).thenReturn(false);
EndpointUtil.setOAuth2ScopeService(oAuth2ScopeService);
when(oAuth2ScopeService.getUserConsentForApp(anyString(), anyString(), anyInt())).thenReturn(oAuth2ScopeConsentResponse);
mockStatic(OAuth2Util.class);
mockStatic(OAuth2Util.OAuthURL.class);
when(OAuth2Util.OAuthURL.getOIDCConsentPageUrl()).thenReturn(OIDC_CONSENT_PAGE_URL);
when(OAuth2Util.OAuthURL.getOAuth2ConsentPageUrl()).thenReturn(OAUTH2_CONSENT_PAGE_URL);
mockStatic(IdentityTenantUtil.class);
when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
mockStatic(FrameworkUtils.class);
when(FrameworkUtils.resolveUserIdFromUsername(anyInt(), anyString(), anyString())).thenReturn("sample");
when(FrameworkUtils.getRedirectURLWithFilteredParams(anyString(), anyMap())).then(i -> i.getArgumentAt(0, String.class));
mockStatic(OAuth2Util.class);
spy(EndpointUtil.class);
doReturn("sampleId").when(EndpointUtil.class, "getAppIdFromClientId", anyString());
mockStatic(SessionDataCache.class);
when(SessionDataCache.getInstance()).thenReturn(mockedSessionDataCache);
if (cacheEntryExists) {
when(mockedSessionDataCache.getValueFromCache(any(SessionDataCacheKey.class))).thenReturn(mockedSessionDataCacheEntry);
when(mockedSessionDataCacheEntry.getQueryString()).thenReturn(queryString);
when(mockedSessionDataCacheEntry.getLoggedInUser()).thenReturn(user);
when(mockedSessionDataCacheEntry.getEndpointParams()).thenReturn(new HashMap<>());
} else {
when(mockedSessionDataCache.getValueFromCache(any(SessionDataCacheKey.class))).thenReturn(null);
}
EndpointUtil.setOAuthAdminService(mockedOAuthAdminService);
when(mockedOAuthAdminService.getScopeNames()).thenReturn(new String[0]);
JDBCPermissionBasedInternalScopeValidator scopeValidatorSpy = PowerMockito.spy(new JDBCPermissionBasedInternalScopeValidator());
doNothing().when(scopeValidatorSpy, method(JDBCPermissionBasedInternalScopeValidator.class, "endTenantFlow")).withNoArguments();
when(scopeValidatorSpy, method(JDBCPermissionBasedInternalScopeValidator.class, "getUserAllowedScopes", AuthenticatedUser.class, String[].class, String.class)).withArguments(any(AuthenticatedUser.class), any(), anyString()).thenReturn(getScopeList());
PowerMockito.whenNew(JDBCPermissionBasedInternalScopeValidator.class).withNoArguments().thenReturn(scopeValidatorSpy);
String consentUrl;
try {
consentUrl = EndpointUtil.getUserConsentURL(parameters, username, sessionDataKey, isOIDC);
if (isOIDC) {
Assert.assertTrue(consentUrl.contains(OIDC_CONSENT_PAGE_URL), "Incorrect consent page url for OIDC");
} else {
Assert.assertTrue(consentUrl.contains(OAUTH2_CONSENT_PAGE_URL), "Incorrect consent page url for OAuth");
}
Assert.assertTrue(consentUrl.contains(URLEncoder.encode(username, "UTF-8")), "loggedInUser parameter value is not found in url");
Assert.assertTrue(consentUrl.contains(URLEncoder.encode("TestApplication", "ISO-8859-1")), "application parameter value is not found in url");
List<NameValuePair> nameValuePairList = URLEncodedUtils.parse(consentUrl, StandardCharsets.UTF_8);
Optional<NameValuePair> optionalScope = nameValuePairList.stream().filter(nameValuePair -> nameValuePair.getName().equals("scope")).findAny();
Assert.assertTrue(optionalScope.isPresent());
NameValuePair scopeNameValuePair = optionalScope.get();
String[] scopeArray = scopeNameValuePair.getValue().split(" ");
Assert.assertTrue(ArrayUtils.contains(scopeArray, "scope2"), "scope parameter value " + "is not found in url");
Assert.assertTrue(ArrayUtils.contains(scopeArray, "internal_login"), "internal_login " + "scope parameter value is not found in url");
Assert.assertFalse(ArrayUtils.contains(scopeArray, "SYSTEM"), "SYSTEM scope" + "parameter should not contain in the url.");
if (queryString != null && cacheEntryExists) {
Assert.assertTrue(consentUrl.contains(queryString), "spQueryParams value is not found in url");
}
} catch (OAuthSystemException e) {
Assert.assertTrue(e.getMessage().contains("Error while retrieving the application name"));
}
}
use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.
the class OpenIDConnectUserRPStoreTest method testPutUserRPToStore.
@Test(dataProvider = "provideStoreDataToPut")
public void testPutUserRPToStore(String usernameValue, String consumerKey) throws Exception {
mockStatic(IdentityTenantUtil.class);
when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
mockStatic(IdentityDatabaseUtil.class);
when(IdentityDatabaseUtil.getDBConnection()).thenAnswer(invocationOnMock -> dataSource.getConnection());
when(IdentityDatabaseUtil.getDBConnection(false)).thenAnswer(invocationOnMock -> dataSource.getConnection());
mockStatic(OAuthServerConfiguration.class);
when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfiguration);
when(oAuthServerConfiguration.getPersistenceProcessor()).thenReturn(tokenPersistenceProcessor);
when(tokenPersistenceProcessor.getProcessedClientId(anyString())).thenAnswer(invocation -> invocation.getArguments()[0]);
user.setUserName(usernameValue);
try {
store.putUserRPToStore(user, appName, true, consumerKey);
} catch (OAuthSystemException e) {
// Exception thrown because the app does not exist
assertTrue(!clientId.equals(consumerKey), "Unexpected exception thrown: " + e.getMessage());
}
PreparedStatement statement = null;
ResultSet rs = null;
String name = null;
try {
statement = connection.prepareStatement(RETRIEVE_PERSISTED_USER_SQL);
rs = statement.executeQuery();
if (rs.next()) {
name = rs.getString(1);
}
} finally {
if (statement != null) {
statement.close();
}
if (rs != null) {
rs.close();
}
}
assertEquals(name, username, "Data not added to the store");
}
Aggregations