Search in sources :

Example 1 with UserInfoEndpointException

use of org.wso2.carbon.identity.oauth.user.UserInfoEndpointException in project identity-inbound-auth-oauth by wso2-extensions.

the class OpenIDConnectUserEndpointTest method testGetUserClaims.

/**
 * Here handleError & setServiceProviderTenantId private methods also covered by this method.
 *
 * @param authResponse
 * @param errorMessage
 * @param errorCode
 * @param expectedStatus
 * @throws Exception
 */
@Test(dataProvider = "provideDataForGetUserClaims")
public void testGetUserClaims(String authResponse, String errorMessage, String errorCode, int expectedStatus) throws Exception {
    String clientID = "rgfKVdnMQnJlSSr_pKFTxj3apiwYa";
    UserInfoEndpointException ex = new UserInfoEndpointException(errorCode, errorMessage);
    Class<?> clazz = OpenIDConnectUserEndpoint.class;
    Object setHandleError = clazz.newInstance();
    Method handleError = setHandleError.getClass().getDeclaredMethod("handleError", UserInfoEndpointException.class);
    handleError.setAccessible(true);
    Response errorResponse = (Response) handleError.invoke(setHandleError, ex);
    assertEquals(errorResponse.getStatus(), expectedStatus, "Error response values are not same");
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(oauthServerConfigurationMock);
    when(oauthServerConfigurationMock.getTimeStampSkewInSeconds()).thenReturn(3600L);
    when(userInfoResponseBuilder.getResponseString(tokenResponse)).thenReturn(authResponse);
    when(userInfoEndpointConfig.getUserInfoResponseBuilder()).thenReturn(userInfoResponseBuilder);
    mockStatic(OAuth2Util.class);
    when(OAuth2Util.getTenantDomainOfOauthApp(appDO)).thenReturn("test");
    when(OAuth2Util.getTenantId(anyString())).thenReturn(-1234);
    when(OAuth2Util.getAppInformationByClientId(anyString())).thenReturn(appDO);
    when(OAuth2Util.getClientIdForAccessToken(anyString())).thenReturn(clientID);
    when(tokenValidator.validateToken(anyString(), anyObject())).thenReturn(tokenResponse);
    when(userInfoEndpointConfig.getUserInfoAccessTokenValidator()).thenReturn(tokenValidator);
    when(userInfoEndpointConfig.getUserInfoRequestValidator()).thenReturn(requestValidator);
    mockStatic(UserInfoEndpointConfig.class);
    when(UserInfoEndpointConfig.getInstance()).thenReturn(userInfoEndpointConfig);
    Response response = openIDConnectUserEndpoint.getUserClaims(httpServletRequest);
    assertNotNull(response.getStatus());
    assertEquals(response.getStatus(), HttpServletResponse.SC_OK);
    MultivaluedMap<String, Object> metadata = response.getMetadata();
    String metadataValue1 = metadata.get(OAuthConstants.HTTP_RESP_HEADER_CACHE_CONTROL).toString();
    String metadataValue2 = metadata.get(OAuthConstants.HTTP_RESP_HEADER_PRAGMA).toString();
    assertEquals(metadataValue1, "[no-store]", "Values are not equal");
    assertEquals(metadataValue2, "[no-cache]", "Values are not equal");
    assertNotNull(response);
    assertEquals(response.getEntity().toString(), authResponse, "Response values are not same");
    when(httpServletRequest.getParameterNames()).thenReturn(new Enumeration<String>() {

        @Override
        public boolean hasMoreElements() {
            return false;
        }

        @Override
        public String nextElement() {
            return null;
        }
    });
    openIDConnectUserEndpoint.getUserClaimsPost(httpServletRequest, paramMap);
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) OAuthASResponse(org.apache.oltu.oauth2.as.response.OAuthASResponse) Response(javax.ws.rs.core.Response) UserInfoEndpointException(org.wso2.carbon.identity.oauth.user.UserInfoEndpointException) Matchers.anyObject(org.mockito.Matchers.anyObject) Matchers.anyString(org.mockito.Matchers.anyString) Method(java.lang.reflect.Method) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)

Example 2 with UserInfoEndpointException

use of org.wso2.carbon.identity.oauth.user.UserInfoEndpointException in project identity-inbound-auth-oauth by wso2-extensions.

the class ClaimUtil method getServiceProvider.

private static ServiceProvider getServiceProvider(String clientId, String spTenantDomain) throws IdentityApplicationManagementException, UserInfoEndpointException {
    ApplicationManagementService applicationMgtService = OAuth2ServiceComponentHolder.getApplicationMgtService();
    String spName = applicationMgtService.getServiceProviderNameByClientId(clientId, INBOUND_AUTH2_TYPE, spTenantDomain);
    ServiceProvider serviceProvider = applicationMgtService.getApplicationExcludingFileBasedSPs(spName, spTenantDomain);
    if (serviceProvider == null) {
        throw new UserInfoEndpointException("Cannot retrieve service provider: " + spName + " in " + "tenantDomain: " + spTenantDomain);
    }
    return serviceProvider;
}
Also used : UserInfoEndpointException(org.wso2.carbon.identity.oauth.user.UserInfoEndpointException) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) ApplicationManagementService(org.wso2.carbon.identity.application.mgt.ApplicationManagementService)

Example 3 with UserInfoEndpointException

use of org.wso2.carbon.identity.oauth.user.UserInfoEndpointException in project identity-inbound-auth-oauth by wso2-extensions.

the class ClaimUtil method getUserClaimsUsingTokenResponse.

public static Map<String, Object> getUserClaimsUsingTokenResponse(OAuth2TokenValidationResponseDTO tokenResponse) throws UserInfoEndpointException {
    Map<ClaimMapping, String> userAttributes = getUserAttributesFromCache(tokenResponse);
    Map<String, Object> userClaimsInOIDCDialect;
    if (isEmpty(userAttributes)) {
        if (log.isDebugEnabled()) {
            log.debug("User attributes not found in cache against the token. Retrieved claims from user store.");
        }
        userClaimsInOIDCDialect = getClaimsFromUserStore(tokenResponse);
    } else {
        UserInfoClaimRetriever retriever = UserInfoEndpointConfig.getInstance().getUserInfoClaimRetriever();
        userClaimsInOIDCDialect = retriever.getClaimsMap(userAttributes);
    }
    if (isEmpty(userClaimsInOIDCDialect)) {
        userClaimsInOIDCDialect = new HashMap<>();
    }
    return userClaimsInOIDCDialect;
}
Also used : ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) UserInfoClaimRetriever(org.wso2.carbon.identity.oauth.user.UserInfoClaimRetriever)

Example 4 with UserInfoEndpointException

use of org.wso2.carbon.identity.oauth.user.UserInfoEndpointException in project identity-inbound-auth-oauth by wso2-extensions.

the class UserInfoISAccessTokenValidator method validateToken.

@Override
public OAuth2TokenValidationResponseDTO validateToken(String accessTokenIdentifier, HttpServletRequest request) throws UserInfoEndpointException {
    OAuth2TokenValidationRequestDTO dto = new OAuth2TokenValidationRequestDTO();
    OAuth2TokenValidationRequestDTO.OAuth2AccessToken accessToken = dto.new OAuth2AccessToken();
    accessToken.setTokenType("bearer");
    accessToken.setIdentifier(accessTokenIdentifier);
    dto.setAccessToken(accessToken);
    OAuth2TokenValidationResponseDTO response = EndpointUtil.getOAuth2TokenValidationService().validate(dto);
    AccessTokenDO accessTokenDO;
    // invalid access token
    if (!response.isValid()) {
        throw new UserInfoEndpointException(OAuthError.ResourceResponse.INVALID_TOKEN, "Access token validation failed");
    }
    // check the scope
    boolean hasOpenIDScope = false;
    String[] scopes = response.getScope();
    if (ArrayUtils.isNotEmpty(scopes)) {
        hasOpenIDScope = Arrays.asList(scopes).contains("openid");
    }
    try {
        accessTokenDO = OAuth2Util.findAccessToken(accessTokenIdentifier, false);
    } catch (IdentityOAuth2Exception e) {
        throw new UserInfoEndpointException("Error in getting AccessTokenDO", e);
    }
    if (!hasOpenIDScope) {
        throw new UserInfoEndpointException(OAuthError.ResourceResponse.INSUFFICIENT_SCOPE, "Access token does not have the openid scope");
    }
    if (response.getAuthorizedUser() == null) {
        throw new UserInfoEndpointException(OAuthError.ResourceResponse.INVALID_TOKEN, "Access token is not valid. No authorized user found. Invalid grant");
    }
    try {
        if (accessTokenDO != null && request != null && OAuth2Util.getAppInformationByClientId(accessTokenDO.getConsumerKey()).isTokenBindingValidationEnabled() && !isValidTokenBinding(response.getTokenBinding(), request)) {
            throw new UserInfoEndpointException(OAuthError.ResourceResponse.INVALID_REQUEST, "Valid token binding value not present in the request.");
        }
    } catch (InvalidOAuthClientException | IdentityOAuth2Exception e) {
        throw new UserInfoEndpointException("Error in getting information of the client : " + accessTokenDO.getConsumerKey(), e);
    }
    OAuth2TokenValidationResponseDTO.AuthorizationContextToken authorizationContextToken = response.new AuthorizationContextToken(accessToken.getTokenType(), accessToken.getIdentifier());
    response.setAuthorizationContextToken(authorizationContextToken);
    return response;
}
Also used : OAuth2TokenValidationResponseDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) UserInfoEndpointException(org.wso2.carbon.identity.oauth.user.UserInfoEndpointException) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuth2TokenValidationRequestDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Example 5 with UserInfoEndpointException

use of org.wso2.carbon.identity.oauth.user.UserInfoEndpointException in project identity-inbound-auth-oauth by wso2-extensions.

the class UserInfoJWTResponse method buildJWTResponse.

private String buildJWTResponse(OAuth2TokenValidationResponseDTO tokenResponse, String spTenantDomain, JWTClaimsSet jwtClaimsSet) throws UserInfoEndpointException {
    JWSAlgorithm signatureAlgorithm = getJWTSignatureAlgorithm();
    if (JWSAlgorithm.NONE.equals(signatureAlgorithm)) {
        if (log.isDebugEnabled()) {
            log.debug("User Info JWT Signature algorithm is not defined. Returning unsigned JWT.");
        }
        return new PlainJWT(jwtClaimsSet).serialize();
    }
    // Tenant domain to which the signing key belongs to.
    String signingTenantDomain = getSigningTenantDomain(tokenResponse, spTenantDomain);
    try {
        return OAuth2Util.signJWT(jwtClaimsSet, signatureAlgorithm, signingTenantDomain).serialize();
    } catch (IdentityOAuth2Exception e) {
        throw new UserInfoEndpointException("Error occurred while signing JWT", e);
    }
}
Also used : PlainJWT(com.nimbusds.jwt.PlainJWT) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) UserInfoEndpointException(org.wso2.carbon.identity.oauth.user.UserInfoEndpointException) JWSAlgorithm(com.nimbusds.jose.JWSAlgorithm)

Aggregations

UserInfoEndpointException (org.wso2.carbon.identity.oauth.user.UserInfoEndpointException)11 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)5 HashMap (java.util.HashMap)3 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)3 ClaimMapping (org.wso2.carbon.identity.application.common.model.ClaimMapping)3 ServiceProvider (org.wso2.carbon.identity.application.common.model.ServiceProvider)3 InvalidOAuthClientException (org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)3 AccessTokenDO (org.wso2.carbon.identity.oauth2.model.AccessTokenDO)3 JWSAlgorithm (com.nimbusds.jose.JWSAlgorithm)2 ArrayList (java.util.ArrayList)2 Matchers.anyString (org.mockito.Matchers.anyString)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 BeforeTest (org.testng.annotations.BeforeTest)2 Test (org.testng.annotations.Test)2 IdentityApplicationManagementException (org.wso2.carbon.identity.application.common.IdentityApplicationManagementException)2 ApplicationManagementService (org.wso2.carbon.identity.application.mgt.ApplicationManagementService)2 AuthorizationGrantCacheEntry (org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry)2 AuthorizationGrantCacheKey (org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheKey)2 OAuthAppDO (org.wso2.carbon.identity.oauth.dao.OAuthAppDO)2 OAuth2TokenValidationResponseDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO)2