Search in sources :

Example 41 with OAuth2AuthorizeRespDTO

use of org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpointTest method testHandleUserConsent.

@Test(dataProvider = "provideUserConsentData", groups = "testWithConnection")
public void testHandleUserConsent(boolean isRespDTONull, String consent, boolean skipConsent, String errorCode, String authCode, String accessToken, String idToken, String responseType, String responseMode, String authenticatedIdps, String state, int expectedStatus, String expectedLocation) throws Exception {
    Map<String, String[]> requestParams = new HashMap<>();
    Map<String, Object> requestAttributes = new HashMap<>();
    requestParams.put(OAuthConstants.SESSION_DATA_KEY_CONSENT, new String[] { SESSION_DATA_KEY_CONSENT_VALUE });
    requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
    requestParams.put(OAuthConstants.OAuth20Params.SCOPE, new String[] { OAuthConstants.Scope.OPENID });
    requestParams.put(OAuthConstants.Prompt.CONSENT, new String[] { consent });
    requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
    requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
    mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
    mockStatic(SessionDataCache.class);
    when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
    SessionDataCacheKey consentDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_CONSENT_VALUE);
    when(sessionDataCache.getValueFromCache(consentDataCacheKey)).thenReturn(consentCacheEntry);
    OAuth2Parameters oAuth2Params = setOAuth2Parameters(new HashSet<String>(), APP_NAME, responseMode, APP_REDIRECT_URL);
    oAuth2Params.setResponseType(responseType);
    oAuth2Params.setState(state);
    oAuth2Params.setClientId(CLIENT_ID_VALUE);
    when(consentCacheEntry.getoAuth2Parameters()).thenReturn(oAuth2Params);
    when(consentCacheEntry.getLoggedInUser()).thenReturn(new AuthenticatedUser());
    when(consentCacheEntry.getAuthenticatedIdPs()).thenReturn(authenticatedIdps);
    OAuth2AuthorizeRespDTO authzRespDTO = null;
    if (!isRespDTONull) {
        authzRespDTO = new OAuth2AuthorizeRespDTO();
        authzRespDTO.setAuthorizationCode(authCode);
        authzRespDTO.setCallbackURI(APP_REDIRECT_URL);
        authzRespDTO.setAccessToken(accessToken);
        authzRespDTO.setIdToken(idToken);
        authzRespDTO.setErrorCode(errorCode);
        if (OAuthConstants.ID_TOKEN.equals(responseType) && idToken == null) {
            authzRespDTO.setCallbackURI(APP_REDIRECT_URL + "?");
        }
    }
    mockEndpointUtil(false);
    when(oAuth2Service.authorize(any(OAuth2AuthorizeReqDTO.class))).thenReturn(authzRespDTO);
    when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
    mockStatic(OpenIDConnectUserRPStore.class);
    when(OpenIDConnectUserRPStore.getInstance()).thenReturn(openIDConnectUserRPStore);
    doNothing().when(openIDConnectUserRPStore).putUserRPToStore(any(AuthenticatedUser.class), anyString(), anyBoolean(), anyString());
    when(oAuthServerConfiguration.getOpenIDConnectSkipeUserConsentConfig()).thenReturn(skipConsent);
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfiguration);
    when(oAuthServerConfiguration.getAuthorizationCodeValidityPeriodInSeconds()).thenReturn(300L);
    mockStatic(OAuth2Util.class);
    when(OAuth2Util.getServiceProvider(CLIENT_ID_VALUE)).thenReturn(new ServiceProvider());
    mockApplicationManagementService();
    spy(FrameworkUtils.class);
    doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
    doNothing().when(FrameworkUtils.class, "endTenantFlow");
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
    Response response;
    try {
        response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
    } catch (InvalidRequestParentException ire) {
        InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
        response = invalidRequestExceptionMapper.toResponse(ire);
    }
    assertNotNull(response, "Authorization response is null");
    assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
    if (expectedLocation != null) {
        MultivaluedMap<String, Object> responseMetadata = response.getMetadata();
        assertNotNull(responseMetadata, "Response metadata is null");
        assertTrue(CollectionUtils.isNotEmpty(responseMetadata.get(HTTPConstants.HEADER_LOCATION)), "Location header not found in the response");
        String location = String.valueOf(responseMetadata.get(HTTPConstants.HEADER_LOCATION).get(0));
        assertTrue(location.contains(expectedLocation), "Unexpected redirect url in the response");
        if (errorCode != null) {
            assertTrue(location.contains(errorCode), "Expected error code not found in URL");
        }
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) Matchers.anyString(org.mockito.Matchers.anyString) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) OAuth2ScopeConsentResponse(org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse) Response(javax.ws.rs.core.Response) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) InvalidRequestParentException(org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException) InvalidRequestExceptionMapper(org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper) OAuth2AuthorizeRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 42 with OAuth2AuthorizeRespDTO

use of org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method handleSuccessAuthorization.

private OAuthResponse handleSuccessAuthorization(OAuthMessage oAuthMessage, OIDCSessionState sessionState, OAuth2Parameters oauth2Params, String responseType, OAuth2AuthorizeRespDTO authzRespDTO) throws OAuthSystemException {
    OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(oAuthMessage.getRequest(), HttpServletResponse.SC_FOUND);
    // all went okay
    if (isAuthorizationCodeExists(authzRespDTO)) {
        // Get token binder if it is enabled for the client.
        Optional<TokenBinder> tokenBinderOptional = getTokenBinder(oauth2Params.getClientId());
        String tokenBindingValue = null;
        if (tokenBinderOptional.isPresent()) {
            TokenBinder tokenBinder = tokenBinderOptional.get();
            tokenBindingValue = tokenBinder.getOrGenerateTokenBindingValue(oAuthMessage.getRequest());
            tokenBinder.setTokenBindingValueForResponse(oAuthMessage.getResponse(), tokenBindingValue);
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                Map<String, Object> params = new HashMap<>();
                params.put("clientId", oauth2Params.getClientId());
                params.put("tokenBindingValue", tokenBindingValue);
                Map<String, Object> configs = new HashMap<>();
                configs.put("tokenBinderType", tokenBinder.getBindingType());
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Successfully generated token binding value.", "generate-token-binding-value", configs);
            }
        }
        setAuthorizationCode(oAuthMessage, authzRespDTO, builder, tokenBindingValue);
    }
    if (isResponseTypeNotIdTokenOrNone(responseType, authzRespDTO)) {
        setAccessToken(authzRespDTO, builder);
        setScopes(authzRespDTO, builder);
    }
    if (isIdTokenExists(authzRespDTO)) {
        setIdToken(authzRespDTO, builder);
        oAuthMessage.setProperty(OIDC_SESSION_ID, authzRespDTO.getOidcSessionId());
    }
    if (StringUtils.isNotBlank(oauth2Params.getState())) {
        builder.setParam(OAuth.OAUTH_STATE, oauth2Params.getState());
    }
    String redirectURL = authzRespDTO.getCallbackURI();
    OAuthResponse oauthResponse;
    if (RESPONSE_MODE_FORM_POST.equals(oauth2Params.getResponseMode())) {
        oauthResponse = handleFormPostMode(oAuthMessage, builder, redirectURL);
    } else {
        oauthResponse = builder.location(redirectURL).buildQueryMessage();
    }
    if (LoggerUtils.isDiagnosticLogsEnabled()) {
        Map<String, Object> params = new HashMap<>();
        params.put("clientId", oauth2Params.getClientId());
        params.put("responseMode", oauth2Params.getResponseMode());
        params.put("redirectUrl", redirectURL);
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Successfully generated oauth response.", "generate-response", null);
    }
    sessionState.setAuthenticated(true);
    return oauthResponse;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) JSONObject(org.json.JSONObject) OAuthASResponse(org.apache.oltu.oauth2.as.response.OAuthASResponse) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) TokenBinder(org.wso2.carbon.identity.oauth2.token.bindings.TokenBinder)

Example 43 with OAuth2AuthorizeRespDTO

use of org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO in project identity-inbound-auth-oauth by wso2-extensions.

the class DefaultIDTokenBuilder method buildIDToken.

@Override
public String buildIDToken(OAuthAuthzReqMessageContext authzReqMessageContext, OAuth2AuthorizeRespDTO tokenRespDTO) throws IdentityOAuth2Exception {
    String accessToken = tokenRespDTO.getAccessToken();
    String clientId = authzReqMessageContext.getAuthorizationReqDTO().getConsumerKey();
    String spTenantDomain = getSpTenantDomain(authzReqMessageContext);
    String issuer = OAuth2Util.getIdTokenIssuer(spTenantDomain);
    // Get subject from Authenticated Subject Identifier
    AuthenticatedUser authorizedUser = authzReqMessageContext.getAuthorizationReqDTO().getUser();
    String subject = getSubjectClaim(authzReqMessageContext, tokenRespDTO, clientId, spTenantDomain, authorizedUser);
    String nonceValue = authzReqMessageContext.getAuthorizationReqDTO().getNonce();
    String acrValue = authzReqMessageContext.getAuthorizationReqDTO().getSelectedAcr();
    // TODO:
    List<String> amrValues = Collections.emptyList();
    String idpSessionKey = getIdpSessionKey(authzReqMessageContext);
    // Initialize OAuthAppDO using the client ID.
    OAuthAppDO oAuthAppDO;
    try {
        oAuthAppDO = OAuth2Util.getAppInformationByClientId(clientId);
    } catch (InvalidOAuthClientException e) {
        String error = "Error occurred while getting app information for client_id: " + clientId;
        throw new IdentityOAuth2Exception(error, e);
    }
    String[] amrValueArray = (String[]) (authzReqMessageContext.getAuthorizationReqDTO().getProperty(OAuthConstants.AMR));
    if (ArrayUtils.isNotEmpty(amrValueArray)) {
        amrValues = Arrays.asList(amrValueArray);
    }
    long idTokenLifeTimeInMillis = getIDTokenExpiryInMillis(oAuthAppDO);
    long currentTimeInMillis = Calendar.getInstance().getTimeInMillis();
    if (log.isDebugEnabled()) {
        log.debug(buildDebugMessage(issuer, subject, nonceValue, idTokenLifeTimeInMillis, currentTimeInMillis));
    }
    JWTClaimsSet.Builder jwtClaimsSetBuilder = new JWTClaimsSet.Builder();
    jwtClaimsSetBuilder.issuer(issuer);
    // Set the audience
    List<String> audience = OAuth2Util.getOIDCAudience(clientId, oAuthAppDO);
    jwtClaimsSetBuilder.audience(audience);
    jwtClaimsSetBuilder.claim(AZP, clientId);
    jwtClaimsSetBuilder.expirationTime(getIdTokenExpiryInMillis(idTokenLifeTimeInMillis, currentTimeInMillis));
    jwtClaimsSetBuilder.issueTime(new Date(currentTimeInMillis));
    long authTime = getAuthTime(authzReqMessageContext);
    if (authTime != 0) {
        jwtClaimsSetBuilder.claim(AUTH_TIME, authTime / 1000);
    }
    if (nonceValue != null) {
        jwtClaimsSetBuilder.claim(OAuthConstants.OIDCClaims.NONCE, nonceValue);
    }
    if (StringUtils.isNotEmpty(acrValue)) {
        jwtClaimsSetBuilder.claim("acr", acrValue);
    }
    if (amrValues != null) {
        jwtClaimsSetBuilder.claim("amr", translateAmrToResponse(amrValues));
    }
    if (idpSessionKey != null) {
        jwtClaimsSetBuilder.claim(IDP_SESSION_KEY, idpSessionKey);
    }
    setUserRealm(authorizedUser, jwtClaimsSetBuilder);
    setAdditionalClaims(authzReqMessageContext, tokenRespDTO, jwtClaimsSetBuilder);
    authzReqMessageContext.addProperty(OAuthConstants.ACCESS_TOKEN, accessToken);
    authzReqMessageContext.addProperty(MultitenantConstants.TENANT_DOMAIN, getSpTenantDomain(authzReqMessageContext));
    jwtClaimsSetBuilder.subject(subject);
    JWTClaimsSet jwtClaimsSet = handleCustomOIDCClaims(authzReqMessageContext, jwtClaimsSetBuilder);
    if (isUnsignedIDToken()) {
        return new PlainJWT(jwtClaimsSet).serialize();
    }
    return getIDToken(clientId, spTenantDomain, jwtClaimsSet, oAuthAppDO, getSigningTenantDomain(authzReqMessageContext));
}
Also used : PlainJWT(com.nimbusds.jwt.PlainJWT) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) Date(java.util.Date) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Example 44 with OAuth2AuthorizeRespDTO

use of org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO in project identity-inbound-auth-oauth by wso2-extensions.

the class CibaResponseTypeHandler method issue.

@Override
public OAuth2AuthorizeRespDTO issue(OAuthAuthzReqMessageContext oauthAuthzMsgCtx) throws IdentityOAuth2Exception {
    OAuth2AuthorizeRespDTO respDTO = new OAuth2AuthorizeRespDTO();
    OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
    try {
        // Assigning authenticated user for the request that to be persisted.
        AuthenticatedUser cibaAuthenticatedUser = authorizationReqDTO.getUser();
        // Assigning the authentication status that to be persisted.
        Enum authenticationStatus = AuthReqStatus.AUTHENTICATED;
        String authCodeKey = CibaDAOFactory.getInstance().getCibaAuthMgtDAO().getCibaAuthCodeKey(authorizationReqDTO.getNonce());
        // Update successful authentication.
        CibaDAOFactory.getInstance().getCibaAuthMgtDAO().persistAuthenticationSuccess(authCodeKey, cibaAuthenticatedUser);
        // Building custom CallBack URL.
        String callbackURL = authorizationReqDTO.getCallbackUrl() + "?authenticationStatus=" + authenticationStatus;
        respDTO.setCallbackURI(callbackURL);
        return respDTO;
    } catch (CibaCoreException e) {
        throw new IdentityOAuth2Exception("Error occurred in persisting authenticated user and authentication " + "status for the request made by client: " + authorizationReqDTO.getConsumerKey(), e);
    }
}
Also used : IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuth2AuthorizeRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO) OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) CibaCoreException(org.wso2.carbon.identity.oauth.ciba.exceptions.CibaCoreException)

Aggregations

OAuth2AuthorizeRespDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO)36 Test (org.testng.annotations.Test)22 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)18 Matchers.anyString (org.mockito.Matchers.anyString)13 IdentityBaseTest (org.wso2.carbon.identity.testutil.IdentityBaseTest)12 OAuth2AuthorizeReqDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO)10 HashMap (java.util.HashMap)7 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)6 OAuthAuthzReqMessageContext (org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext)6 AccessTokenDO (org.wso2.carbon.identity.oauth2.model.AccessTokenDO)6 OAuthAppDO (org.wso2.carbon.identity.oauth.dao.OAuthAppDO)5 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)4 Date (java.util.Date)4 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 BeforeTest (org.testng.annotations.BeforeTest)3 OAuthEventInterceptor (org.wso2.carbon.identity.oauth.event.OAuthEventInterceptor)3 OAuth2Parameters (org.wso2.carbon.identity.oauth2.model.OAuth2Parameters)3 RequestObject (org.wso2.carbon.identity.openidconnect.model.RequestObject)3