Search in sources :

Example 36 with OAuthClientAuthnContext

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

the class OAuth2CibaEndpointTest method testCibaForBadRequest.

@Test(dataProvider = "provideRequestParamsForBadRequest")
public void testCibaForBadRequest(String parameter, String paramValue, int expectedStatus) throws Exception {
    Map<String, String[]> requestParams = new HashMap<>();
    requestParams.put(parameter, new String[] { paramValue });
    when(httpServletRequest.getParameterMap()).thenReturn(requestParams);
    when(httpServletRequest.getParameter(REQUEST_ATTRIBUTE)).thenReturn(paramValue);
    when(httpServletRequest.getParameterNames()).thenReturn(Collections.enumeration(requestParams.keySet()));
    OAuthClientAuthnContext oAuthClientAuthnContext = new OAuthClientAuthnContext();
    oAuthClientAuthnContext.setAuthenticated(true);
    oAuthClientAuthnContext.setClientId("ZzxmDqqK8YYfjtlOh9vw85qnNVoa");
    when(httpServletRequest.getAttribute(OAuthConstants.CLIENT_AUTHN_CONTEXT)).thenReturn(oAuthClientAuthnContext);
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfiguration);
    mockStatic(OAuth2Util.class);
    when(OAuth2Util.getAppInformationByClientId(CONSUMER_KEY)).thenReturn(oAuthAppDO);
    when(oAuthAppDO.getGrantTypes()).thenReturn(CibaConstants.OAUTH_CIBA_GRANT_TYPE);
    OAuth2CibaEndpoint cibaEndpoint = new OAuth2CibaEndpoint();
    Response response = cibaEndpoint.ciba(httpServletRequest, httpServletResponse, new MultivaluedHashMap());
    Assert.assertEquals(expectedStatus, response.getStatus());
}
Also used : CibaAuthCodeResponse(org.wso2.carbon.identity.oauth.ciba.model.CibaAuthCodeResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(javax.ws.rs.core.Response) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) Matchers.anyString(org.mockito.Matchers.anyString) OAuthClientAuthnContext(org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 37 with OAuthClientAuthnContext

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

the class OAuth2CibaEndpointTest method testCibaForProperRequest.

@Test
public void testCibaForProperRequest() throws Exception {
    Map<String, String[]> requestParams = new HashMap<>();
    requestParams.put(REQUEST_ATTRIBUTE, new String[] { "eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJaenhtRHFxSzhZWWZqdGxPaDl2dzg1cW5OVm9hIiwiYXVkIjoiaHR0cHM6Ly9sb2Nhb" + "Ghvc3Q6OTQ0My9vYXV0aDIvY2liYSIsImJpbmRpbmdfbWVzc2FnZSI6InRyeSIsImxvZ2luX2hpbnQiOiJ2aXZlayI" + "sInNjb3BlIjoib3BlbmlkIHNjb3BlMSBzY29wZXgiLCJpYXQiOjExMjg3MTQyMTksImV4cCI6OTYyODcxNDIxOSwib" + "mJmIjoxMTI4NzE0MjE5LCJhY3IiOiI1Nzg4ODc4OCIsImp0aSI6IjlmZjg0NWI5LTIwYmYtNDAzMy05ZWQzLTNjY2M" + "2M2Y1MjA0YyIsInRyYW5zYWN0aW9uX2NvbnRleHQiOnsidXNlciI6InVzZXIiLCJhbW91bnQiOjEwMDAsInNob3AiO" + "iJXU08yIENJQkEgREVNTyBDT05TT0xFIiwiYXBwbGljYXRpb24iOiJQYXlIZXJlIn19.Sx_MjjautinmOV9vvP8yhu" + "suBggOdBCjn1NyprpJoEg" });
    mockStatic(LoggerUtils.class);
    when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
    mockStatic(IdentityTenantUtil.class);
    when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(oAuthServerConfiguration);
    when(httpServletRequest.getParameterMap()).thenReturn(requestParams);
    when(httpServletRequest.getParameterNames()).thenReturn(Collections.enumeration(requestParams.keySet()));
    when(httpServletRequest.getParameter(REQUEST_ATTRIBUTE)).thenReturn("eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJaenhtRHFxSzhZWWZqdGxPaDl2dzg1cW5OVm9hIiwiYXVkIjoiaHR0cHM6Ly9sb2Nhb" + "Ghvc3Q6OTQ0My9vYXV0aDIvY2liYSIsImJpbmRpbmdfbWVzc2FnZSI6InRyeSIsImxvZ2luX2hpbnQiOiJ2aXZlayI" + "sInNjb3BlIjoib3BlbmlkIHNjb3BlMSBzY29wZXgiLCJpYXQiOjExMjg3MTQyMTksImV4cCI6OTYyODcxNDIxOSwib" + "mJmIjoxMTI4NzE0MjE5LCJhY3IiOiI1Nzg4ODc4OCIsImp0aSI6IjlmZjg0NWI5LTIwYmYtNDAzMy05ZWQzLTNjY2M" + "2M2Y1MjA0YyIsInRyYW5zYWN0aW9uX2NvbnRleHQiOnsidXNlciI6InVzZXIiLCJhbW91bnQiOjEwMDAsInNob3AiO" + "iJXU08yIENJQkEgREVNTyBDT05TT0xFIiwiYXBwbGljYXRpb24iOiJQYXlIZXJlIn19.Sx_MjjautinmOV9vvP8yhu" + "suBggOdBCjn1NyprpJoEg");
    OAuthClientAuthnContext oAuthClientAuthnContext = new OAuthClientAuthnContext();
    oAuthClientAuthnContext.setAuthenticated(true);
    oAuthClientAuthnContext.setClientId("ZzxmDqqK8YYfjtlOh9vw85qnNVoa");
    when(httpServletRequest.getAttribute(OAuthConstants.CLIENT_AUTHN_CONTEXT)).thenReturn(oAuthClientAuthnContext);
    mockStatic(OAuth2Util.class);
    when(OAuth2Util.getAppInformationByClientId(CONSUMER_KEY)).thenReturn(oAuthAppDO);
    when(OAuth2Util.getTenantDomainOfOauthApp(oAuthAppDO)).thenReturn("super");
    when(OAuth2Util.getIdTokenIssuer("super")).thenReturn("https://localhost:9443/oauth2/ciba");
    when(OAuth2Util.buildScopeString(any())).thenReturn("scope1 scope2 openid");
    when(oAuthAppDO.getGrantTypes()).thenReturn(CibaConstants.OAUTH_CIBA_GRANT_TYPE);
    OAuthServerConfiguration oauthServerConfigurationMock = mock(OAuthServerConfiguration.class);
    mockStatic(OAuthServerConfiguration.class);
    when(OAuthServerConfiguration.getInstance()).thenReturn(oauthServerConfigurationMock);
    RequestObjectValidator requestObjectValidator = PowerMockito.spy(new CIBARequestObjectValidatorImpl());
    when(oauthServerConfigurationMock.getCIBARequestObjectValidator()).thenReturn(requestObjectValidator);
    doReturn(true).when(requestObjectValidator).validateSignature(any(), any());
    RequestParamRequestObjectBuilder requestParamRequestObjectBuilder = new RequestParamRequestObjectBuilder();
    Map<String, RequestObjectBuilder> requestObjectBuilderMap = new HashMap<>();
    requestObjectBuilderMap.put(REQUEST_PARAM_VALUE_BUILDER, requestParamRequestObjectBuilder);
    when((oauthServerConfigurationMock.getRequestObjectBuilders())).thenReturn(requestObjectBuilderMap);
    mockStatic(EndpointUtil.class);
    when(EndpointUtil.getCibaAuthService()).thenReturn(authService);
    mockStatic(EndpointUtil.class);
    when(EndpointUtil.getCibaAuthService()).thenReturn(authService);
    when(authService.generateAuthCodeResponse(any())).thenReturn(authCodeResponse);
    CibaAuthzHandler cibaAuthzHandler = new CibaAuthzHandler();
    WhiteboxImpl.setInternalState(oAuth2CibaEndpoint, "cibaAuthzHandler", cibaAuthzHandler);
    WhiteboxImpl.setInternalState(cibaAuthzHandler, "authzEndPoint", oAuth2AuthzEndpoint);
    when(oAuth2AuthzEndpoint.authorize(any(), any())).thenReturn(response);
    Response response = oAuth2CibaEndpoint.ciba(httpServletRequest, httpServletResponse, new MultivaluedHashMap());
    Assert.assertEquals(200, response.getStatus());
}
Also used : HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) RequestObjectBuilder(org.wso2.carbon.identity.openidconnect.RequestObjectBuilder) RequestParamRequestObjectBuilder(org.wso2.carbon.identity.openidconnect.RequestParamRequestObjectBuilder) OAuthServerConfiguration(org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration) Matchers.anyString(org.mockito.Matchers.anyString) OAuthClientAuthnContext(org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext) RequestObjectValidator(org.wso2.carbon.identity.openidconnect.RequestObjectValidator) CibaAuthCodeResponse(org.wso2.carbon.identity.oauth.ciba.model.CibaAuthCodeResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(javax.ws.rs.core.Response) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) RequestParamRequestObjectBuilder(org.wso2.carbon.identity.openidconnect.RequestParamRequestObjectBuilder) CIBARequestObjectValidatorImpl(org.wso2.carbon.identity.openidconnect.CIBARequestObjectValidatorImpl) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 38 with OAuthClientAuthnContext

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

the class OAuthClientAuthenticatorProxy method handleMessage.

/**
 * Handles the incoming JAX-RS message for the purpose of OAuth2 client authentication.
 *
 * @param message JAX-RS message
 */
@Override
public void handleMessage(Message message) {
    Map<String, List> bodyContentParams = getContentParams(message);
    HttpServletRequest request = ((HttpServletRequest) message.get(HTTP_REQUEST));
    OAuthClientAuthnContext oAuthClientAuthnContext = oAuthClientAuthnService.authenticateClient(request, bodyContentParams);
    if (!oAuthClientAuthnContext.isPreviousAuthenticatorEngaged()) {
        oAuthClientAuthnContext.setErrorCode(OAuth2ErrorCodes.INVALID_CLIENT);
        oAuthClientAuthnContext.setErrorMessage("Unsupported client authentication mechanism");
    }
    setContextToRequest(request, oAuthClientAuthnContext);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) List(java.util.List) OAuthClientAuthnContext(org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext)

Example 39 with OAuthClientAuthnContext

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

the class AccessTokenIssuer method issue.

/**
 * Issue access token using the respective grant handler and client authentication handler.
 *
 * @param tokenReqDTO
 * @return access token response
 * @throws IdentityException
 * @throws InvalidOAuthClientException
 */
public OAuth2AccessTokenRespDTO issue(OAuth2AccessTokenReqDTO tokenReqDTO) throws IdentityException {
    String grantType = tokenReqDTO.getGrantType();
    OAuth2AccessTokenRespDTO tokenRespDTO = null;
    AuthorizationGrantHandler authzGrantHandler = authzGrantHandlers.get(grantType);
    OAuthTokenReqMessageContext tokReqMsgCtx = new OAuthTokenReqMessageContext(tokenReqDTO);
    boolean isRefreshRequest = GrantType.REFRESH_TOKEN.toString().equals(grantType);
    triggerPreListeners(tokenReqDTO, tokReqMsgCtx, isRefreshRequest);
    OAuthClientAuthnContext oAuthClientAuthnContext = tokenReqDTO.getoAuthClientAuthnContext();
    if (oAuthClientAuthnContext == null) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", tokenReqDTO.getClientId());
            if (StringUtils.isNotBlank(tokenReqDTO.getClientSecret())) {
                params.put("clientSecret", tokenReqDTO.getClientSecret().replaceAll(".", "*"));
            }
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "OAuth client authentication failed.", "issue-access-token", null);
        }
        oAuthClientAuthnContext = new OAuthClientAuthnContext();
        oAuthClientAuthnContext.setAuthenticated(false);
        oAuthClientAuthnContext.setErrorMessage("Client Authentication Failed");
        oAuthClientAuthnContext.setErrorCode(OAuthError.TokenResponse.INVALID_REQUEST);
    }
    // whether the grant type is confidential or not.
    if (oAuthClientAuthnContext.isMultipleAuthenticatorsEngaged()) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", tokenReqDTO.getClientId());
            params.put("clientAuthenticators", oAuthClientAuthnContext.getExecutedAuthenticators());
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "The client MUST NOT use more than one authentication method per request.", "issue-access-token", null);
        }
        tokenRespDTO = handleError(OAuth2ErrorCodes.INVALID_REQUEST, "The client MUST NOT use more than one " + "authentication method in each", tokenReqDTO);
        setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
        triggerPostListeners(tokenReqDTO, tokenRespDTO, tokReqMsgCtx, isRefreshRequest);
        return tokenRespDTO;
    }
    boolean isAuthenticated = oAuthClientAuthnContext.isAuthenticated();
    if (authzGrantHandler == null) {
        String errorMsg = "Unsupported grant type : " + grantType + ", is used.";
        if (log.isDebugEnabled()) {
            log.debug(errorMsg);
        }
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", tokenReqDTO.getClientId());
            params.put("grantType", grantType);
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Unsupported grant type.", "issue-access-token", null);
        }
        tokenRespDTO = handleError(OAuthError.TokenResponse.UNSUPPORTED_GRANT_TYPE, errorMsg, tokenReqDTO);
        setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
        triggerPostListeners(tokenReqDTO, tokenRespDTO, tokReqMsgCtx, isRefreshRequest);
        return tokenRespDTO;
    }
    // If the client is not confidential then there is no need to authenticate the client.
    if (!authzGrantHandler.isConfidentialClient() && StringUtils.isNotEmpty(oAuthClientAuthnContext.getClientId())) {
        isAuthenticated = true;
    }
    if (!isAuthenticated && !oAuthClientAuthnContext.isPreviousAuthenticatorEngaged() && authzGrantHandler.isConfidentialClient()) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", tokenReqDTO.getClientId());
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Unsupported client authentication method.", "issue-access-token", null);
        }
        tokenRespDTO = handleError(OAuth2ErrorCodes.INVALID_CLIENT, "Unsupported Client Authentication Method!", tokenReqDTO);
        setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
        triggerPostListeners(tokenReqDTO, tokenRespDTO, tokReqMsgCtx, isRefreshRequest);
        return tokenRespDTO;
    }
    if (!isAuthenticated) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", tokenReqDTO.getClientId());
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Client authentication failed. " + oAuthClientAuthnContext.getErrorMessage(), "issue-access-token", null);
        }
        tokenRespDTO = handleError(oAuthClientAuthnContext.getErrorCode(), oAuthClientAuthnContext.getErrorMessage(), tokenReqDTO);
        setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
        triggerPostListeners(tokenReqDTO, tokenRespDTO, tokReqMsgCtx, isRefreshRequest);
        return tokenRespDTO;
    }
    // loading the stored application data
    OAuthAppDO oAuthAppDO = getOAuthApplication(tokenReqDTO.getClientId());
    // set the tenantDomain of the SP in the tokenReqDTO
    // Indirectly we can say that the tenantDomain of the SP is the tenantDomain of the user who created SP.
    // This is done to avoid having to send the tenantDomain as a query param to the token endpoint
    String tenantDomainOfApp = OAuth2Util.getTenantDomainOfOauthApp(oAuthAppDO);
    validateRequestTenantDomain(tenantDomainOfApp);
    tokenReqDTO.setTenantDomain(tenantDomainOfApp);
    tokReqMsgCtx.addProperty(OAUTH_APP_DO, oAuthAppDO);
    boolean isOfTypeApplicationUser = authzGrantHandler.isOfTypeApplicationUser();
    if (!isOfTypeApplicationUser) {
        tokReqMsgCtx.setAuthorizedUser(oAuthAppDO.getAppOwner());
        tokReqMsgCtx.addProperty(OAuthConstants.UserType.USER_TYPE, OAuthConstants.UserType.APPLICATION);
    } else {
        tokReqMsgCtx.addProperty(OAuthConstants.UserType.USER_TYPE, OAuthConstants.UserType.APPLICATION_USER);
    }
    boolean isAuthorizedClient = false;
    String error = "The authenticated client is not authorized to use this authorization grant type";
    try {
        isAuthorizedClient = authzGrantHandler.isAuthorizedClient(tokReqMsgCtx);
    } catch (IdentityOAuth2Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Error occurred while validating client for authorization", e);
        }
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "System error occurred.", "issue-access-token", null);
        error = e.getMessage();
    }
    if (!isAuthorizedClient) {
        if (log.isDebugEnabled()) {
            log.debug("Client Id: " + tokenReqDTO.getClientId() + " is not authorized to use grant type: " + grantType);
        }
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", tokenReqDTO.getClientId());
            params.put("grantType", grantType);
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Client is not authorized to use the requested grant type.", "issue-access-token", null);
        }
        tokenRespDTO = handleError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT, error, tokenReqDTO);
        setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
        triggerPostListeners(tokenReqDTO, tokenRespDTO, tokReqMsgCtx, isRefreshRequest);
        return tokenRespDTO;
    }
    boolean isValidGrant = false;
    error = "Provided Authorization Grant is invalid";
    String errorCode = OAuthError.TokenResponse.INVALID_GRANT;
    try {
        isValidGrant = authzGrantHandler.validateGrant(tokReqMsgCtx);
    } catch (IdentityOAuth2Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Error occurred while validating grant", e);
        }
        if (e.getErrorCode() != null) {
            errorCode = e.getErrorCode();
        }
        error = e.getMessage();
        if (e.getErrorCode() != null) {
            errorCode = e.getErrorCode();
        }
    }
    if (tokReqMsgCtx.getAuthorizedUser() != null && tokReqMsgCtx.getAuthorizedUser().isFederatedUser()) {
        tokReqMsgCtx.getAuthorizedUser().setTenantDomain(tenantDomainOfApp);
    }
    if (!isValidGrant) {
        if (log.isDebugEnabled()) {
            log.debug("Invalid Grant provided by the client Id: " + tokenReqDTO.getClientId());
        }
        tokenRespDTO = handleError(errorCode, error, tokenReqDTO);
        setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
        triggerPostListeners(tokenReqDTO, tokenRespDTO, tokReqMsgCtx, isRefreshRequest);
        return tokenRespDTO;
    }
    boolean isAuthorized = authzGrantHandler.authorizeAccessDelegation(tokReqMsgCtx);
    if (!isAuthorized) {
        if (log.isDebugEnabled()) {
            log.debug("Invalid authorization for client Id : " + tokenReqDTO.getClientId());
        }
        tokenRespDTO = handleError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT, "Unauthorized Client!", tokenReqDTO);
        setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
        triggerPostListeners(tokenReqDTO, tokenRespDTO, tokReqMsgCtx, isRefreshRequest);
        return tokenRespDTO;
    }
    List<String> allowedScopes = OAuthServerConfiguration.getInstance().getAllowedScopes();
    List<String> requestedAllowedScopes = new ArrayList<>();
    String[] requestedScopes = tokReqMsgCtx.getScope();
    List<String> scopesToBeValidated = new ArrayList<>();
    if (requestedScopes != null) {
        for (String scope : requestedScopes) {
            if (OAuth2Util.isAllowedScope(allowedScopes, scope)) {
                requestedAllowedScopes.add(scope);
            } else {
                scopesToBeValidated.add(scope);
            }
        }
        tokReqMsgCtx.setScope(scopesToBeValidated.toArray(new String[0]));
    }
    String[] authorizedInternalScopes = new String[0];
    boolean isManagementApp = getServiceProvider(tokenReqDTO).isManagementApp();
    if (isManagementApp) {
        if (log.isDebugEnabled()) {
            log.debug("Handling the internal scope validation.");
        }
        // Execute Internal SCOPE Validation.
        JDBCPermissionBasedInternalScopeValidator scopeValidator = new JDBCPermissionBasedInternalScopeValidator();
        authorizedInternalScopes = scopeValidator.validateScope(tokReqMsgCtx);
        // Execute internal console scopes validation.
        if (IdentityUtil.isSystemRolesEnabled()) {
            RoleBasedInternalScopeValidator roleBasedInternalScopeValidator = new RoleBasedInternalScopeValidator();
            String[] roleBasedInternalConsoleScopes = roleBasedInternalScopeValidator.validateScope(tokReqMsgCtx);
            authorizedInternalScopes = (String[]) ArrayUtils.addAll(authorizedInternalScopes, roleBasedInternalConsoleScopes);
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Skipping the internal scope validation as the application is not" + " configured as Management App");
        }
    }
    // Clear the internal scopes. Internal scopes should only handle in JDBCPermissionBasedInternalScopeValidator.
    // Those scopes should not send to the other scopes validators.
    // Thus remove the scopes from the tokReqMsgCtx. Will be added to the response after executing
    // the other scope validators.
    removeInternalScopes(tokReqMsgCtx);
    // Adding the authorized internal scopes to tokReqMsgCtx for any special validators to use.
    tokReqMsgCtx.setAuthorizedInternalScopes(authorizedInternalScopes);
    boolean isDropUnregisteredScopes = OAuthServerConfiguration.getInstance().isDropUnregisteredScopes();
    if (isDropUnregisteredScopes) {
        if (log.isDebugEnabled()) {
            log.debug("DropUnregisteredScopes config is enabled. Attempting to drop unregistered scopes.");
        }
        String[] filteredScopes = OAuth2Util.dropUnregisteredScopes(tokReqMsgCtx.getScope(), tokReqMsgCtx.getOauth2AccessTokenReqDTO().getTenantDomain());
        tokReqMsgCtx.setScope(filteredScopes);
    }
    boolean isValidScope = authzGrantHandler.validateScope(tokReqMsgCtx);
    if (isValidScope) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", tokenReqDTO.getClientId());
            if (ArrayUtils.isNotEmpty(tokenReqDTO.getScope())) {
                params.put("scope", Arrays.asList(tokenReqDTO.getScope()));
            }
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "OAuth scope validation is successful.", "validate-scope", null);
        }
        // Add authorized internal scopes to the request for sending in the response.
        addAuthorizedInternalScopes(tokReqMsgCtx, tokReqMsgCtx.getAuthorizedInternalScopes());
        addAllowedScopes(tokReqMsgCtx, requestedAllowedScopes.toArray(new String[0]));
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Invalid scope provided by client Id: " + tokenReqDTO.getClientId());
        }
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", tokenReqDTO.getClientId());
            if (ArrayUtils.isNotEmpty(tokenReqDTO.getScope())) {
                params.put("scope", Arrays.asList(tokenReqDTO.getScope()));
            }
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Invalid scope provided in the request.", "validate-scope", null);
        }
        tokenRespDTO = handleError(OAuthError.TokenResponse.INVALID_SCOPE, "Invalid Scope!", tokenReqDTO);
        setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
        triggerPostListeners(tokenReqDTO, tokenRespDTO, tokReqMsgCtx, isRefreshRequest);
        return tokenRespDTO;
    }
    handleTokenBinding(tokenReqDTO, grantType, tokReqMsgCtx, oAuthAppDO);
    try {
        // set the token request context to be used by downstream handlers. This is introduced as a fix for
        // IDENTITY-4111.
        OAuth2Util.setTokenRequestContext(tokReqMsgCtx);
        AuthenticatedUser authorizedUser = tokReqMsgCtx.getAuthorizedUser();
        if (authorizedUser.getAuthenticatedSubjectIdentifier() == null) {
            authorizedUser.setAuthenticatedSubjectIdentifier(getSubjectClaim(getServiceProvider(tokReqMsgCtx.getOauth2AccessTokenReqDTO()), authorizedUser));
        }
        tokenRespDTO = authzGrantHandler.issue(tokReqMsgCtx);
        if (tokenRespDTO.isError()) {
            setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
            return tokenRespDTO;
        }
    } finally {
        triggerPostListeners(tokenReqDTO, tokenRespDTO, tokReqMsgCtx, isRefreshRequest);
        // clears the token request context.
        OAuth2Util.clearTokenRequestContext();
    }
    tokenRespDTO.setCallbackURI(oAuthAppDO.getCallbackUrl());
    String[] scopes = tokReqMsgCtx.getScope();
    if (scopes != null && scopes.length > 0) {
        StringBuilder scopeString = new StringBuilder("");
        for (String scope : scopes) {
            scopeString.append(scope);
            scopeString.append(" ");
        }
        tokenRespDTO.setAuthorizedScopes(scopeString.toString().trim());
    }
    setResponseHeaders(tokReqMsgCtx, tokenRespDTO);
    // Do not change this log format as these logs use by external applications
    if (log.isDebugEnabled()) {
        log.debug("Access token issued to client Id: " + tokenReqDTO.getClientId() + " username: " + tokReqMsgCtx.getAuthorizedUser() + " and scopes: " + tokenRespDTO.getAuthorizedScopes());
    }
    if (LoggerUtils.isDiagnosticLogsEnabled()) {
        Map<String, Object> params = new HashMap<>();
        params.put("clientId", tokenReqDTO.getClientId());
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Access token issued for the application.", "issue-access-token", null);
    }
    if (GrantType.AUTHORIZATION_CODE.toString().equals(grantType)) {
        // Should add user attributes to the cache before building the ID token.
        addUserAttributesAgainstAccessToken(tokenReqDTO, tokenRespDTO);
    }
    if (tokReqMsgCtx.getScope() != null && OAuth2Util.isOIDCAuthzRequest(tokReqMsgCtx.getScope())) {
        if (log.isDebugEnabled()) {
            log.debug("Issuing ID token for client: " + tokenReqDTO.getClientId());
        }
        IDTokenBuilder builder = OAuthServerConfiguration.getInstance().getOpenIDConnectIDTokenBuilder();
        try {
            String idToken = builder.buildIDToken(tokReqMsgCtx, tokenRespDTO);
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                Map<String, Object> params = new HashMap<>();
                params.put("clientId", tokenReqDTO.getClientId());
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "ID token issued for the application.", "issue-id-token", null);
            }
            tokenRespDTO.setIDToken(idToken);
        } catch (IDTokenValidationFailureException e) {
            log.error(e.getMessage());
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                Map<String, Object> params = new HashMap<>();
                params.put("clientId", tokenReqDTO.getClientId());
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "System error occurred.", "issue-id-token", null);
            }
            tokenRespDTO = handleError(OAuth2ErrorCodes.SERVER_ERROR, "Server Error", tokenReqDTO);
            return tokenRespDTO;
        }
    }
    if (GrantType.AUTHORIZATION_CODE.toString().equals(grantType)) {
        // Cache entry against the authorization code has no value beyond the token request.
        clearCacheEntryAgainstAuthorizationCode(getAuthorizationCode(tokenReqDTO));
    }
    return tokenRespDTO;
}
Also used : AuthorizationGrantHandler(org.wso2.carbon.identity.oauth2.token.handlers.grant.AuthorizationGrantHandler) HashMap(java.util.HashMap) JDBCPermissionBasedInternalScopeValidator(org.wso2.carbon.identity.oauth2.validators.JDBCPermissionBasedInternalScopeValidator) ArrayList(java.util.ArrayList) OAuthClientAuthnContext(org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) OAuthAppDO(org.wso2.carbon.identity.oauth.dao.OAuthAppDO) IDTokenBuilder(org.wso2.carbon.identity.openidconnect.IDTokenBuilder) RoleBasedInternalScopeValidator(org.wso2.carbon.identity.oauth2.validators.RoleBasedInternalScopeValidator) OAuth2AccessTokenRespDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) IDTokenValidationFailureException(org.wso2.carbon.identity.oauth2.IDTokenValidationFailureException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 40 with OAuthClientAuthnContext

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

the class OAuth2Util method buildOAuthRevocationRequest.

/**
 * Used to build an OAuth revocation request DTO.
 *
 * @param oAuthClientAuthnContext OAuth client authentication context.
 * @param accessToken             Access token to be revoked.
 * @return Returns a OAuth revocation request DTO.
 */
public static OAuthRevocationRequestDTO buildOAuthRevocationRequest(OAuthClientAuthnContext oAuthClientAuthnContext, String accessToken) {
    OAuthRevocationRequestDTO revocationRequestDTO = new OAuthRevocationRequestDTO();
    revocationRequestDTO.setToken(accessToken);
    revocationRequestDTO.setOauthClientAuthnContext(oAuthClientAuthnContext);
    revocationRequestDTO.setConsumerKey(oAuthClientAuthnContext.getClientId());
    return revocationRequestDTO;
}
Also used : OAuthRevocationRequestDTO(org.wso2.carbon.identity.oauth2.dto.OAuthRevocationRequestDTO)

Aggregations

OAuthClientAuthnContext (org.wso2.carbon.identity.oauth2.bean.OAuthClientAuthnContext)39 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)24 Test (org.testng.annotations.Test)24 PowerMockIdentityBaseTest (org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)21 OAuth2AccessTokenReqDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO)12 OAuth2AccessTokenRespDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO)10 Matchers.anyString (org.mockito.Matchers.anyString)9 HashMap (java.util.HashMap)8 HttpServletRequest (javax.servlet.http.HttpServletRequest)8 OAuthRevocationRequestDTO (org.wso2.carbon.identity.oauth2.dto.OAuthRevocationRequestDTO)7 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)6 AuthorizationGrantHandler (org.wso2.carbon.identity.oauth2.token.handlers.grant.AuthorizationGrantHandler)6 Map (java.util.Map)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)3 Response (javax.ws.rs.core.Response)3 BeforeTest (org.testng.annotations.BeforeTest)3 Consumes (javax.ws.rs.Consumes)2 POST (javax.ws.rs.POST)2 Path (javax.ws.rs.Path)2