Search in sources :

Example 31 with OAuth

use of org.apache.oltu.oauth2.common.OAuth in project identity-inbound-auth-oauth by wso2-extensions.

the class TokenResponseTypeHandler method issue.

@Override
public OAuth2AuthorizeRespDTO issue(OAuthAuthzReqMessageContext oauthAuthzMsgCtx) throws IdentityOAuth2Exception {
    OAuthEventInterceptor oAuthEventInterceptorProxy = OAuthComponentServiceHolder.getInstance().getOAuthEventInterceptorProxy();
    if (oAuthEventInterceptorProxy != null && oAuthEventInterceptorProxy.isEnabled()) {
        Map<String, Object> paramMap = new HashMap<>();
        oAuthEventInterceptorProxy.onPreTokenIssue(oauthAuthzMsgCtx, paramMap);
    }
    OAuth2AuthorizeRespDTO respDTO = new OAuth2AuthorizeRespDTO();
    OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
    String scope = OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope());
    respDTO.setCallbackURI(authorizationReqDTO.getCallbackUrl());
    String consumerKey = authorizationReqDTO.getConsumerKey();
    String authorizedUserId = null;
    try {
        authorizedUserId = authorizationReqDTO.getUser().getUserId();
    } catch (UserIdNotFoundException e) {
        throw new IdentityOAuth2Exception("Error occurred while retrieving the user id for user: " + authorizationReqDTO.getUser().getLoggableUserId());
    }
    String oAuthCacheKeyString;
    String responseType = oauthAuthzMsgCtx.getAuthorizationReqDTO().getResponseType();
    String grantType;
    // Loading the stored application data.
    OAuthAppDO oAuthAppDO;
    try {
        oAuthAppDO = OAuth2Util.getAppInformationByClientId(consumerKey);
    } catch (InvalidOAuthClientException e) {
        throw new IdentityOAuth2Exception("Error while retrieving app information for clientId: " + consumerKey, e);
    }
    if (StringUtils.contains(responseType, OAuthConstants.GrantTypes.TOKEN)) {
        grantType = OAuthConstants.GrantTypes.IMPLICIT;
    } else {
        grantType = responseType;
    }
    oAuthCacheKeyString = consumerKey + ":" + authorizedUserId + ":" + scope;
    OAuthCacheKey cacheKey = new OAuthCacheKey(oAuthCacheKeyString);
    String userStoreDomain = null;
    // Select the user store domain when multiple user stores are configured.
    if (OAuth2Util.checkAccessTokenPartitioningEnabled() && OAuth2Util.checkUserNameAssertionEnabled()) {
        userStoreDomain = OAuth2Util.getUserStoreForFederatedUser(authorizationReqDTO.getUser());
    }
    if (log.isDebugEnabled()) {
        log.debug("Service Provider specific expiry time enabled for application : " + consumerKey + ". Application access token expiry time : " + oAuthAppDO.getApplicationAccessTokenExpiryTime() + ", User access token expiry time : " + oAuthAppDO.getUserAccessTokenExpiryTime() + ", Refresh token expiry time : " + oAuthAppDO.getRefreshTokenExpiryTime());
    }
    String refreshToken = null;
    Timestamp refreshTokenIssuedTime = null;
    long refreshTokenValidityPeriodInMillis = 0;
    AccessTokenDO tokenDO = null;
    synchronized ((consumerKey + ":" + authorizedUserId + ":" + scope).intern()) {
        AccessTokenDO existingAccessTokenDO = null;
        // check if valid access token exists in cache
        if (isHashDisabled && cacheEnabled) {
            existingAccessTokenDO = (AccessTokenDO) OAuthCache.getInstance().getValueFromCache(cacheKey);
            if (existingAccessTokenDO != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Retrieved active Access Token for Client Id : " + consumerKey + ", User ID :" + authorizationReqDTO.getUser().getLoggableUserId() + " and Scope : " + scope + " from cache");
                }
                long expireTime = OAuth2Util.getTokenExpireTimeMillis(existingAccessTokenDO);
                if ((expireTime > 0 || expireTime < 0)) {
                    // Return still valid existing access token when JWTTokenIssuer is not used.
                    if (isNotRenewAccessTokenPerRequest(oauthAuthzMsgCtx)) {
                        if (log.isDebugEnabled()) {
                            if (expireTime > 0) {
                                log.debug("Access Token is valid for another " + expireTime + "ms");
                            } else {
                                log.debug("Infinite lifetime Access Token found in cache");
                            }
                        }
                        respDTO.setAccessToken(existingAccessTokenDO.getAccessToken());
                        if (expireTime > 0) {
                            respDTO.setValidityPeriod(expireTime / 1000);
                        } else {
                            respDTO.setValidityPeriod(Long.MAX_VALUE / 1000);
                        }
                        respDTO.setScope(oauthAuthzMsgCtx.getApprovedScope());
                        respDTO.setTokenType(existingAccessTokenDO.getTokenType());
                        // We only need to deal with id_token and user attributes if the request is OIDC
                        if (isOIDCRequest(oauthAuthzMsgCtx)) {
                            buildIdToken(oauthAuthzMsgCtx, respDTO);
                        }
                        triggerPostListeners(oauthAuthzMsgCtx, existingAccessTokenDO, respDTO);
                        return respDTO;
                    }
                } else {
                    long refreshTokenExpiryTime = OAuth2Util.getRefreshTokenExpireTimeMillis(existingAccessTokenDO);
                    if (refreshTokenExpiryTime < 0 || refreshTokenExpiryTime > 0) {
                        if (log.isDebugEnabled()) {
                            log.debug("Access token has expired, But refresh token is still valid. User existing " + "refresh token.");
                        }
                        refreshToken = existingAccessTokenDO.getRefreshToken();
                        refreshTokenIssuedTime = existingAccessTokenDO.getRefreshTokenIssuedTime();
                        refreshTokenValidityPeriodInMillis = existingAccessTokenDO.getRefreshTokenValidityPeriodInMillis();
                    }
                    // Token is expired. Clear it from cache
                    OAuthCache.getInstance().clearCacheEntry(cacheKey);
                    if (log.isDebugEnabled()) {
                        log.debug("Access Token is expired. Therefore cleared it from cache and marked it as" + " expired in database");
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("No active access token found in cache for Client ID : " + consumerKey + ", User " + "ID" + " : " + authorizationReqDTO.getUser().getLoggableUserId() + " and Scope : " + scope);
                }
            }
        }
        // in the database
        if (isHashDisabled && existingAccessTokenDO == null) {
            existingAccessTokenDO = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getLatestAccessToken(consumerKey, authorizationReqDTO.getUser(), userStoreDomain, scope, false);
            if (existingAccessTokenDO != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Retrieved latest Access Token for Client ID : " + consumerKey + ", User ID :" + authorizationReqDTO.getUser().getLoggableUserId() + " and Scope : " + scope + " from database");
                }
                long expiryTime = OAuth2Util.getTokenExpireTimeMillis(existingAccessTokenDO);
                long refreshTokenExpiryTime = OAuth2Util.getRefreshTokenExpireTimeMillis(existingAccessTokenDO);
                if (OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(existingAccessTokenDO.getTokenState()) && (expiryTime > 0 || expiryTime < 0)) {
                    // Return still valid existing access token when JWTTokenIssuer is not used.
                    if (isNotRenewAccessTokenPerRequest(oauthAuthzMsgCtx)) {
                        // token is active and valid
                        if (log.isDebugEnabled()) {
                            if (expiryTime > 0) {
                                log.debug("Access token is valid for another " + expiryTime + "ms");
                            } else {
                                log.debug("Infinite lifetime Access Token found in cache");
                            }
                        }
                        if (cacheEnabled) {
                            OAuthCache.getInstance().addToCache(cacheKey, existingAccessTokenDO);
                            if (log.isDebugEnabled()) {
                                log.debug("Access Token was added to cache for cache key : " + cacheKey.getCacheKeyString());
                            }
                        }
                        respDTO.setAccessToken(existingAccessTokenDO.getAccessToken());
                        if (expiryTime > 0) {
                            respDTO.setValidityPeriod(expiryTime / 1000);
                        } else {
                            respDTO.setValidityPeriod(Long.MAX_VALUE / 1000);
                        }
                        respDTO.setScope(oauthAuthzMsgCtx.getApprovedScope());
                        respDTO.setTokenType(existingAccessTokenDO.getTokenType());
                        // we only need to deal with id_token and user attributes if the request is OIDC
                        if (isOIDCRequest(oauthAuthzMsgCtx)) {
                            buildIdToken(oauthAuthzMsgCtx, respDTO);
                        }
                        triggerPostListeners(oauthAuthzMsgCtx, existingAccessTokenDO, respDTO);
                        return respDTO;
                    }
                } else {
                    if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
                        log.debug("Access Token is " + existingAccessTokenDO.getTokenState());
                    }
                    String tokenState = existingAccessTokenDO.getTokenState();
                    if (OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(tokenState)) {
                        // Token is expired. If refresh token is still valid, use it.
                        if (refreshTokenExpiryTime > 0 || refreshTokenExpiryTime < 0) {
                            if (log.isDebugEnabled()) {
                                log.debug("Access token has expired, But refresh token is still valid. User " + "existing refresh token.");
                            }
                            refreshToken = existingAccessTokenDO.getRefreshToken();
                            refreshTokenIssuedTime = existingAccessTokenDO.getRefreshTokenIssuedTime();
                            refreshTokenValidityPeriodInMillis = existingAccessTokenDO.getRefreshTokenValidityPeriodInMillis();
                        }
                        if (log.isDebugEnabled()) {
                            log.debug("Marked Access Token as expired");
                        }
                    } else {
                        // Token is revoked or inactive
                        if (log.isDebugEnabled()) {
                            log.debug("Access Token is " + existingAccessTokenDO.getTokenState());
                        }
                    }
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("No access token found in database for Client ID : " + consumerKey + ", User ID : " + authorizationReqDTO.getUser().getLoggableUserId() + " and Scope : " + scope);
                }
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Issuing a new access token for client id: " + consumerKey + ", user : " + authorizationReqDTO.getUser().getLoggableUserId() + "and scope : " + scope);
        }
        Timestamp timestamp = new Timestamp(new Date().getTime());
        // if reusing existing refresh token, use its original issued time
        if (refreshTokenIssuedTime == null) {
            refreshTokenIssuedTime = timestamp;
        }
        // Default token validity Period
        long validityPeriodInMillis = OAuthServerConfiguration.getInstance().getUserAccessTokenValidityPeriodInSeconds() * 1000;
        if (oAuthAppDO.getUserAccessTokenExpiryTime() != 0) {
            validityPeriodInMillis = oAuthAppDO.getUserAccessTokenExpiryTime() * 1000;
        }
        // if a VALID validity period is set through the callback, then use it
        long callbackValidityPeriod = oauthAuthzMsgCtx.getValidityPeriod();
        if ((callbackValidityPeriod != OAuthConstants.UNASSIGNED_VALIDITY_PERIOD) && callbackValidityPeriod > 0) {
            validityPeriodInMillis = callbackValidityPeriod * 1000;
        }
        // otherwise use existing refresh token's validity period
        if (refreshTokenValidityPeriodInMillis == 0) {
            if (oAuthAppDO.getRefreshTokenExpiryTime() != 0) {
                refreshTokenValidityPeriodInMillis = oAuthAppDO.getRefreshTokenExpiryTime() * 1000;
            } else {
                refreshTokenValidityPeriodInMillis = OAuthServerConfiguration.getInstance().getRefreshTokenValidityPeriodInSeconds() * 1000;
            }
        }
        // issue a new access token
        String accessToken;
        // set the validity period. this is needed by downstream handlers.
        // if this is set before - then this will override it by the calculated new value.
        oauthAuthzMsgCtx.setValidityPeriod(validityPeriodInMillis);
        // set the refresh token validity period. this is needed by downstream handlers.
        // if this is set before - then this will override it by the calculated new value.
        oauthAuthzMsgCtx.setRefreshTokenvalidityPeriod(refreshTokenValidityPeriodInMillis);
        // set access token issued time.this is needed by downstream handlers.
        oauthAuthzMsgCtx.setAccessTokenIssuedTime(timestamp.getTime());
        // set refresh token issued time.this is needed by downstream handlers.
        oauthAuthzMsgCtx.setRefreshTokenIssuedTime(refreshTokenIssuedTime.getTime());
        try {
            OauthTokenIssuer oauthIssuerImpl = OAuth2Util.getOAuthTokenIssuerForOAuthApp(oAuthAppDO);
            accessToken = oauthIssuerImpl.accessToken(oauthAuthzMsgCtx);
            // regenerate only if refresh token is null
            if (refreshToken == null) {
                refreshToken = oauthIssuerImpl.refreshToken(oauthAuthzMsgCtx);
            }
        } catch (OAuthSystemException e) {
            throw new IdentityOAuth2Exception("Error occurred while generating access token and refresh token", e);
        }
        if (OAuth2Util.checkUserNameAssertionEnabled()) {
            accessToken = OAuth2Util.addUsernameToToken(authorizationReqDTO.getUser(), accessToken);
            refreshToken = OAuth2Util.addUsernameToToken(authorizationReqDTO.getUser(), refreshToken);
        }
        AccessTokenDO newAccessTokenDO = new AccessTokenDO(consumerKey, authorizationReqDTO.getUser(), oauthAuthzMsgCtx.getApprovedScope(), timestamp, refreshTokenIssuedTime, validityPeriodInMillis, refreshTokenValidityPeriodInMillis, OAuthConstants.UserType.APPLICATION_USER);
        newAccessTokenDO.setAccessToken(accessToken);
        newAccessTokenDO.setRefreshToken(refreshToken);
        newAccessTokenDO.setTokenState(OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE);
        newAccessTokenDO.setGrantType(grantType);
        String tokenId = UUID.randomUUID().toString();
        newAccessTokenDO.setTokenId(tokenId);
        oauthAuthzMsgCtx.addProperty(OAuth2Util.ACCESS_TOKEN_DO, newAccessTokenDO);
        // Persist the access token in database
        try {
            OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().insertAccessToken(accessToken, authorizationReqDTO.getConsumerKey(), newAccessTokenDO, existingAccessTokenDO, userStoreDomain);
            deactivateCurrentAuthorizationCode(newAccessTokenDO.getAuthorizationCode(), newAccessTokenDO.getTokenId());
            if (!accessToken.equals(newAccessTokenDO.getAccessToken())) {
                // Using latest active token.
                accessToken = newAccessTokenDO.getAccessToken();
                refreshToken = newAccessTokenDO.getRefreshToken();
            }
        } catch (IdentityException e) {
            throw new IdentityOAuth2Exception("Error occurred while storing new access token : " + accessToken, e);
        }
        tokenDO = newAccessTokenDO;
        if (log.isDebugEnabled()) {
            log.debug("Persisted Access Token for " + "Client ID : " + authorizationReqDTO.getConsumerKey() + ", Authorized User : " + authorizationReqDTO.getUser().getLoggableUserId() + ", Timestamp : " + timestamp + ", Validity period (s) : " + newAccessTokenDO.getValidityPeriod() + ", Scope : " + OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope()) + ", Callback URL : " + authorizationReqDTO.getCallbackUrl() + ", Token State : " + OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE + " and User Type : " + OAuthConstants.UserType.APPLICATION_USER);
        }
        // Add the access token to the cache, if cacheEnabled and the hashing oauth key feature turn on.
        if (isHashDisabled && cacheEnabled) {
            OAuthCache.getInstance().addToCache(cacheKey, newAccessTokenDO);
            // Adding AccessTokenDO to improve validation performance
            OAuthCacheKey accessTokenCacheKey = new OAuthCacheKey(accessToken);
            OAuthCache.getInstance().addToCache(accessTokenCacheKey, newAccessTokenDO);
            if (log.isDebugEnabled()) {
                log.debug("Access Token was added to OAuthCache for cache key : " + cacheKey.getCacheKeyString());
                log.debug("Access Token was added to OAuthCache for cache key : " + accessTokenCacheKey.getCacheKeyString());
            }
        }
        if (StringUtils.contains(responseType, ResponseType.TOKEN.toString())) {
            respDTO.setAccessToken(accessToken);
            if (validityPeriodInMillis > 0) {
                respDTO.setValidityPeriod(newAccessTokenDO.getValidityPeriod());
            } else {
                respDTO.setValidityPeriod(Long.MAX_VALUE / 1000);
            }
            respDTO.setScope(newAccessTokenDO.getScope());
            respDTO.setTokenType(newAccessTokenDO.getTokenType());
        }
    }
    // we only need to deal with id_token and user attributes if the request is OIDC
    if (isOIDCRequest(oauthAuthzMsgCtx)) {
        buildIdToken(oauthAuthzMsgCtx, respDTO);
    }
    triggerPostListeners(oauthAuthzMsgCtx, tokenDO, respDTO);
    return respDTO;
}
Also used : HashMap(java.util.HashMap) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) IdentityException(org.wso2.carbon.identity.base.IdentityException) Timestamp(java.sql.Timestamp) Date(java.util.Date) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OauthTokenIssuer(org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) OAuthCacheKey(org.wso2.carbon.identity.oauth.cache.OAuthCacheKey) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuth2AuthorizeRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO) OAuthEventInterceptor(org.wso2.carbon.identity.oauth.event.OAuthEventInterceptor) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

Example 32 with OAuth

use of org.apache.oltu.oauth2.common.OAuth in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method getTokenBinder.

private Optional<TokenBinder> getTokenBinder(String clientId) throws OAuthSystemException {
    OAuthAppDO oAuthAppDO;
    try {
        oAuthAppDO = OAuth2Util.getAppInformationByClientId(clientId);
    } catch (IdentityOAuth2Exception | InvalidOAuthClientException e) {
        throw new OAuthSystemException("Failed to retrieve OAuth application with client id: " + clientId, e);
    }
    if (oAuthAppDO == null || StringUtils.isBlank(oAuthAppDO.getTokenBindingType())) {
        return Optional.empty();
    }
    OAuth2Service oAuth2Service = getOAuth2Service();
    List<TokenBinder> supportedTokenBinders = oAuth2Service.getSupportedTokenBinders();
    if (supportedTokenBinders == null || supportedTokenBinders.isEmpty()) {
        return Optional.empty();
    }
    return supportedTokenBinders.stream().filter(t -> t.getBindingType().equals(oAuthAppDO.getTokenBindingType())).findAny();
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) Arrays(java.util.Arrays) Produces(javax.ws.rs.Produces) AuthorizationGrantCache(org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCache) Enumeration(java.util.Enumeration) FrameworkConstants(org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants) IdentityOAuth2ScopeException(org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeException) CarbonOAuthAuthzRequest(org.wso2.carbon.identity.oauth2.model.CarbonOAuthAuthzRequest) JSONException(org.json.JSONException) MediaType(javax.ws.rs.core.MediaType) OAuthError(org.apache.oltu.oauth2.common.error.OAuthError) AuthenticationResult(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult) Map(java.util.Map) SessionDataCacheEntry(org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry) OpenIDConnectClaimFilterImpl(org.wso2.carbon.identity.openidconnect.OpenIDConnectClaimFilterImpl) NONCE(org.wso2.carbon.identity.openidconnect.model.Constants.NONCE) ServiceURLBuilder(org.wso2.carbon.identity.core.ServiceURLBuilder) OpenIDConnectUserRPStore(org.wso2.carbon.identity.oauth.endpoint.util.OpenIDConnectUserRPStore) OIDCRequestObjectUtil(org.wso2.carbon.identity.openidconnect.OIDCRequestObjectUtil) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) URIBuilder(org.apache.http.client.utils.URIBuilder) AuthenticatorFlowStatus(org.wso2.carbon.identity.application.authentication.framework.AuthenticatorFlowStatus) SCOPE(org.wso2.carbon.identity.openidconnect.model.Constants.SCOPE) InvalidRequestException(org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestException) EndpointUtil.validateParams(org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.validateParams) Set(java.util.Set) SignedJWT(com.nimbusds.jwt.SignedJWT) StandardCharsets(java.nio.charset.StandardCharsets) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException) REQUESTED_CLAIMS(org.wso2.carbon.identity.application.authentication.endpoint.util.Constants.REQUESTED_CLAIMS) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) ConsentHandlingFailedException(org.wso2.carbon.identity.oauth.endpoint.exception.ConsentHandlingFailedException) PASSTHROUGH_TO_COMMONAUTH(org.wso2.carbon.identity.oauth.endpoint.state.OAuthAuthorizeState.PASSTHROUGH_TO_COMMONAUTH) LogFactory(org.apache.commons.logging.LogFactory) TENANT_DOMAIN(org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants.RequestParams.TENANT_DOMAIN) REQUEST_PARAM_SP(org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants.REQUEST_PARAM_SP) RequestedClaim(org.wso2.carbon.identity.openidconnect.model.RequestedClaim) GET(javax.ws.rs.GET) HttpRequestHeaderHandler(org.wso2.carbon.identity.oauth2.model.HttpRequestHeaderHandler) OAuthRequestWrapper(org.wso2.carbon.identity.oauth.endpoint.OAuthRequestWrapper) EndpointUtil.getOAuthServerConfiguration(org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getOAuthServerConfiguration) ArrayList(java.util.ArrayList) InvalidRequestParentException(org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException) ClaimMetadataException(org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException) HttpServletRequest(javax.servlet.http.HttpServletRequest) Encode(org.owasp.encoder.Encode) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) IdentityOAuthAdminException(org.wso2.carbon.identity.oauth.IdentityOAuthAdminException) RequestObjectException(org.wso2.carbon.identity.oauth2.RequestObjectException) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) CommonAuthRequestWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper) IdentityTenantUtil(org.wso2.carbon.identity.core.util.IdentityTenantUtil) LinkedHashSet(java.util.LinkedHashSet) MAX_AGE(org.wso2.carbon.identity.openidconnect.model.Constants.MAX_AGE) Files(java.nio.file.Files) ID_TOKEN_HINT(org.wso2.carbon.identity.openidconnect.model.Constants.ID_TOKEN_HINT) IOException(java.io.IOException) AUTHENTICATION_RESPONSE(org.wso2.carbon.identity.oauth.endpoint.state.OAuthAuthorizeState.AUTHENTICATION_RESPONSE) USER_CLAIMS_CONSENT_ONLY(org.wso2.carbon.identity.application.authentication.endpoint.util.Constants.USER_CLAIMS_CONSENT_ONLY) STATE(org.wso2.carbon.identity.openidconnect.model.Constants.STATE) EndpointUtil.getErrorPageURL(org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getErrorPageURL) OAuthMessage(org.wso2.carbon.identity.oauth.endpoint.message.OAuthMessage) Paths(java.nio.file.Paths) PROMPT(org.wso2.carbon.identity.openidconnect.model.Constants.PROMPT) ServletException(javax.servlet.ServletException) OAuth(org.apache.oltu.oauth2.common.OAuth) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) URISyntaxException(java.net.URISyntaxException) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) Path(javax.ws.rs.Path) Scanner(java.util.Scanner) AUTH_TIME(org.wso2.carbon.identity.openidconnect.model.Constants.AUTH_TIME) JSONObject(org.json.JSONObject) OIDCConstants(org.wso2.carbon.identity.openidconnect.OIDCConstants) USER_CONSENT_RESPONSE(org.wso2.carbon.identity.oauth.endpoint.state.OAuthAuthorizeState.USER_CONSENT_RESPONSE) OAuth2ErrorCodes(org.wso2.carbon.identity.oauth.common.OAuth2ErrorCodes) Consumes(javax.ws.rs.Consumes) LOGIN_HINT(org.wso2.carbon.identity.openidconnect.model.Constants.LOGIN_HINT) URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) URI(java.net.URI) ParseException(java.text.ParseException) INITIAL_REQUEST(org.wso2.carbon.identity.oauth.endpoint.state.OAuthAuthorizeState.INITIAL_REQUEST) EndpointUtil.getOAuth2Service(org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getOAuth2Service) OIDCSessionState(org.wso2.carbon.identity.oidc.session.OIDCSessionState) AuthenticationResultCacheEntry(org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationResultCacheEntry) Context(javax.ws.rs.core.Context) EndpointUtil.retrieveStateForErrorURL(org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.retrieveStateForErrorURL) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) OAuthASResponse(org.apache.oltu.oauth2.as.response.OAuthASResponse) OAuth2AuthorizeRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO) CommonAuthResponseWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper) UUID(java.util.UUID) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) OIDCSessionManagementUtil(org.wso2.carbon.identity.oidc.session.util.OIDCSessionManagementUtil) List(java.util.List) IdentityConstants(org.wso2.carbon.identity.base.IdentityConstants) HttpHeaders(javax.ws.rs.core.HttpHeaders) OAuth2Service(org.wso2.carbon.identity.oauth2.OAuth2Service) Response(javax.ws.rs.core.Response) OAuthAuthzRequest(org.apache.oltu.oauth2.as.request.OAuthAuthzRequest) Optional(java.util.Optional) CommonAuthenticationHandler(org.wso2.carbon.identity.application.authentication.framework.CommonAuthenticationHandler) SSOConsentServiceException(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.exception.SSOConsentServiceException) NameValuePair(org.apache.http.NameValuePair) AuthHistory(org.wso2.carbon.identity.application.authentication.framework.context.AuthHistory) FrameworkUtils(org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils) OAuth2ClientValidationResponseDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO) UnsupportedEncodingException(java.io.UnsupportedEncodingException) EndpointUtil.getSSOConsentService(org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getSSOConsentService) ServiceProviderProperty(org.wso2.carbon.identity.application.common.model.ServiceProviderProperty) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) REDIRECT_URI(org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Params.REDIRECT_URI) SessionContext(org.wso2.carbon.identity.application.authentication.framework.context.SessionContext) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) HashMap(java.util.HashMap) EndpointUtil(org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil) Claim(org.wso2.carbon.identity.application.common.model.Claim) HashSet(java.util.HashSet) CarbonUtils(org.wso2.carbon.utils.CarbonUtils) ClaimMapping(org.wso2.carbon.identity.application.common.model.ClaimMapping) CollectionUtils(org.apache.commons.collections.CollectionUtils) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) ExternalClaim(org.wso2.carbon.identity.claim.metadata.mgt.model.ExternalClaim) LoggerUtils(org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils) OAuthErrorDTO(org.wso2.carbon.identity.oauth.dto.OAuthErrorDTO) ClaimMetaData(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ClaimMetaData) SessionDataCache(org.wso2.carbon.identity.oauth.cache.SessionDataCache) Cookie(javax.servlet.http.Cookie) ConsentClaimsData(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ConsentClaimsData) UUIDGenerator(org.wso2.carbon.registry.core.utils.UUIDGenerator) EndpointUtil.getLoginPageURL(org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getLoginPageURL) DISPLAY(org.wso2.carbon.identity.openidconnect.model.Constants.DISPLAY) IdentityOAuth2ClientException(org.wso2.carbon.identity.oauth2.IdentityOAuth2ClientException) POST(javax.ws.rs.POST) MapUtils(org.apache.commons.collections.MapUtils) OAuthConstants(org.wso2.carbon.identity.oauth.common.OAuthConstants) HttpServletResponse(javax.servlet.http.HttpServletResponse) OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) ClaimMetadataHandler(org.wso2.carbon.identity.claim.metadata.mgt.ClaimMetadataHandler) AuthorizationGrantCacheEntry(org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry) AuthorizationGrantCacheKey(org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheKey) MANDATORY_CLAIMS(org.wso2.carbon.identity.application.authentication.endpoint.util.Constants.MANDATORY_CLAIMS) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) TokenBinder(org.wso2.carbon.identity.oauth2.token.bindings.TokenBinder) URLEncoder(java.net.URLEncoder) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) StringJoiner(java.util.StringJoiner) IdentityUtil(org.wso2.carbon.identity.core.util.IdentityUtil) Log(org.apache.commons.logging.Log) DigestUtils(org.apache.commons.codec.digest.DigestUtils) Collections(java.util.Collections) ArrayUtils(org.apache.commons.lang.ArrayUtils) EndpointUtil.getOAuth2Service(org.wso2.carbon.identity.oauth.endpoint.util.EndpointUtil.getOAuth2Service) OAuth2Service(org.wso2.carbon.identity.oauth2.OAuth2Service) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException) TokenBinder(org.wso2.carbon.identity.oauth2.token.bindings.TokenBinder)

Example 33 with OAuth

use of org.apache.oltu.oauth2.common.OAuth 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.");
    }
}
Also used : OAuth2ScopeConsentResponse(org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse) JDBCPermissionBasedInternalScopeValidator(org.wso2.carbon.identity.oauth2.validators.JDBCPermissionBasedInternalScopeValidator) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) IdentityOAuth2ScopeException(org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeException)

Example 34 with OAuth

use of org.apache.oltu.oauth2.common.OAuth 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"));
    }
}
Also used : OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) Scope(org.wso2.carbon.identity.oauth2.bean.Scope) Arrays(java.util.Arrays) DefaultOIDCProcessor(org.wso2.carbon.identity.discovery.DefaultOIDCProcessor) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) OAuth2ScopeConsentResponse(org.wso2.carbon.identity.oauth2.model.OAuth2ScopeConsentResponse) Test(org.testng.annotations.Test) ServiceURL(org.wso2.carbon.identity.core.ServiceURL) PowerMockito.doNothing(org.powermock.api.mockito.PowerMockito.doNothing) AuthenticationRequestCacheEntry(org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationRequestCacheEntry) Map(java.util.Map) URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) Matchers.anyInt(org.mockito.Matchers.anyInt) SessionDataCacheEntry(org.wso2.carbon.identity.oauth.cache.SessionDataCacheEntry) PowerMockito.whenNew(org.powermock.api.mockito.PowerMockito.whenNew) OAuthAdminServiceImpl(org.wso2.carbon.identity.oauth.OAuthAdminServiceImpl) JDBCPermissionBasedInternalScopeValidator(org.wso2.carbon.identity.oauth2.validators.JDBCPermissionBasedInternalScopeValidator) ServiceURLBuilder(org.wso2.carbon.identity.core.ServiceURLBuilder) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) OAuthClientException(org.wso2.carbon.identity.oauth.common.exception.OAuthClientException) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) OAuthASResponse(org.apache.oltu.oauth2.as.response.OAuthASResponse) Set(java.util.Set) PowerMockito.doReturn(org.powermock.api.mockito.PowerMockito.doReturn) HashedMap(org.apache.commons.collections.map.HashedMap) StandardCharsets(java.nio.charset.StandardCharsets) Matchers.any(org.mockito.Matchers.any) List(java.util.List) PowerMockito.mock(org.powermock.api.mockito.PowerMockito.mock) OAuth2Service(org.wso2.carbon.identity.oauth2.OAuth2Service) Matchers.anyMap(org.mockito.Matchers.anyMap) URLEncodedUtils(org.apache.http.client.utils.URLEncodedUtils) Modifier(java.lang.reflect.Modifier) PowerMockito.doAnswer(org.powermock.api.mockito.PowerMockito.doAnswer) Optional(java.util.Optional) OIDCProcessor(org.wso2.carbon.identity.discovery.OIDCProcessor) NameValuePair(org.apache.http.NameValuePair) FrameworkUtils(org.wso2.carbon.identity.application.authentication.framework.util.FrameworkUtils) MemberMatcher.method(org.powermock.api.support.membermodification.MemberMatcher.method) DefaultOIDCProviderRequestBuilder(org.wso2.carbon.identity.discovery.builders.DefaultOIDCProviderRequestBuilder) OAuth2ScopeService(org.wso2.carbon.identity.oauth2.OAuth2ScopeService) OAuthProblemException(org.apache.oltu.oauth2.common.exception.OAuthProblemException) DataProvider(org.testng.annotations.DataProvider) PowerMockito.mockStatic(org.powermock.api.mockito.PowerMockito.mockStatic) Mock(org.mockito.Mock) Assert.assertEquals(org.testng.Assert.assertEquals) PrivilegedCarbonContext(org.wso2.carbon.context.PrivilegedCarbonContext) HashMap(java.util.HashMap) Constructor(java.lang.reflect.Constructor) Matchers.anyString(org.mockito.Matchers.anyString) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) BeforeTest(org.testng.annotations.BeforeTest) HttpServletRequest(javax.servlet.http.HttpServletRequest) Assert(org.testng.Assert) OAuthResponse(org.apache.oltu.oauth2.common.message.OAuthResponse) Base64Utils(org.apache.axiom.util.base64.Base64Utils) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) LoggerUtils(org.wso2.carbon.identity.central.log.mgt.utils.LoggerUtils) MultitenantConstants(org.wso2.carbon.base.MultitenantConstants) SessionDataCache(org.wso2.carbon.identity.oauth.cache.SessionDataCache) WebFingerProcessor(org.wso2.carbon.identity.webfinger.WebFingerProcessor) PowerMockito(org.powermock.api.mockito.PowerMockito) SSOConsentService(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.SSOConsentService) IdentityTenantUtil(org.wso2.carbon.identity.core.util.IdentityTenantUtil) WithCarbonHome(org.wso2.carbon.identity.common.testng.WithCarbonHome) PowerMockito.when(org.powermock.api.mockito.PowerMockito.when) HttpServletResponse(javax.servlet.http.HttpServletResponse) Field(java.lang.reflect.Field) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ServerConfiguration(org.wso2.carbon.base.ServerConfiguration) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) OAuth2TokenValidationService(org.wso2.carbon.identity.oauth2.OAuth2TokenValidationService) PowerMockIdentityBaseTest(org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest) URLEncoder(java.net.URLEncoder) FileBasedConfigurationBuilder(org.wso2.carbon.identity.application.authentication.framework.config.builder.FileBasedConfigurationBuilder) DefaultWebFingerProcessor(org.wso2.carbon.identity.webfinger.DefaultWebFingerProcessor) PowerMockito.spy(org.powermock.api.mockito.PowerMockito.spy) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) OIDCProviderRequestBuilder(org.wso2.carbon.identity.discovery.builders.OIDCProviderRequestBuilder) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) RequestObjectService(org.wso2.carbon.identity.openidconnect.RequestObjectService) IdentityUtil(org.wso2.carbon.identity.core.util.IdentityUtil) Assert.assertTrue(org.testng.Assert.assertTrue) Log(org.apache.commons.logging.Log) ArrayUtils(org.apache.commons.lang.ArrayUtils) NameValuePair(org.apache.http.NameValuePair) JDBCPermissionBasedInternalScopeValidator(org.wso2.carbon.identity.oauth2.validators.JDBCPermissionBasedInternalScopeValidator) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) Matchers.anyString(org.mockito.Matchers.anyString) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) OAuth2Util(org.wso2.carbon.identity.oauth2.util.OAuth2Util) SessionDataCacheKey(org.wso2.carbon.identity.oauth.cache.SessionDataCacheKey) 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 35 with OAuth

use of org.apache.oltu.oauth2.common.OAuth 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)

Aggregations

OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)22 OAuthProblemException (org.apache.oltu.oauth2.common.exception.OAuthProblemException)17 OAuthClientRequest (org.apache.oltu.oauth2.client.request.OAuthClientRequest)14 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)11 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)10 URI (java.net.URI)9 HashMap (java.util.HashMap)7 OAuthIssuerImpl (org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl)6 OAuthASResponse (org.apache.oltu.oauth2.as.response.OAuthASResponse)6 ResponseEntity (org.springframework.http.ResponseEntity)6 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)6 MD5Generator (org.apache.oltu.oauth2.as.issuer.MD5Generator)5 OAuthAuthzRequest (org.apache.oltu.oauth2.as.request.OAuthAuthzRequest)5 OAuthClient (org.apache.oltu.oauth2.client.OAuthClient)5 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 OAuthAuthzResponse (org.apache.oltu.oauth2.client.response.OAuthAuthzResponse)4 HttpHeaders (org.springframework.http.HttpHeaders)4 ServletException (javax.servlet.ServletException)3