Search in sources :

Example 16 with URLBuilderException

use of org.wso2.carbon.identity.core.URLBuilderException in project identity-inbound-auth-oauth by wso2-extensions.

the class OIDCLogoutServlet method sendToFrameworkForLogout.

private void sendToFrameworkForLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        triggerLogoutHandlersForPreLogout(request, response);
    } catch (OIDCSessionManagementException e) {
        log.error("Error executing logout handlers on pre logout.");
        if (log.isDebugEnabled()) {
            log.debug("Error executing logout handlers on pre logout.", e);
        }
        response.sendRedirect(getRedirectURL(getErrorPageURL(OAuth2ErrorCodes.SERVER_ERROR, "User logout failed."), request));
    }
    // Generate a SessionDataKey. Authentication framework expects this parameter
    String sessionDataKey = UUID.randomUUID().toString();
    String opBrowserStateCookieValue = OIDCSessionManagementUtil.getOPBrowserStateCookie(request).getValue();
    // Add all parameters to authentication context before sending to authentication framework
    AuthenticationRequest authenticationRequest = new AuthenticationRequest();
    Map<String, String[]> map = new HashMap<>();
    map.put(OIDCSessionConstants.OIDC_SESSION_DATA_KEY_PARAM, new String[] { sessionDataKey });
    authenticationRequest.setRequestQueryParams(map);
    authenticationRequest.addRequestQueryParam(FrameworkConstants.RequestParams.LOGOUT, new String[] { "true" });
    try {
        authenticationRequest.setCommonAuthCallerPath(ServiceURLBuilder.create().addPath(OIDC_LOGOUT_ENDPOINT).build().getRelativeInternalURL());
    } catch (URLBuilderException e) {
        log.error("Error building commonauth caller path to send logout request to framework.", e);
        response.sendRedirect(getRedirectURL(getErrorPageURL(OAuth2ErrorCodes.SERVER_ERROR, "User logout failed."), request));
    }
    authenticationRequest.setPost(true);
    OIDCSessionDataCacheEntry cacheEntry = getSessionDataFromCache(opBrowserStateCookieValue);
    if (cacheEntry != null) {
        authenticationRequest.setRelyingParty(cacheEntry.getParamMap().get(OIDCSessionConstants.OIDC_CACHE_CLIENT_ID_PARAM));
        authenticationRequest.setTenantDomain(cacheEntry.getParamMap().get(OIDCSessionConstants.OIDC_CACHE_TENANT_DOMAIN_PARAM));
        addOPBSCookieValueToCacheEntry(opBrowserStateCookieValue, cacheEntry);
        addSessionDataToCache(sessionDataKey, cacheEntry);
    }
    // Add headers to AuthenticationRequestContext
    for (Enumeration e = request.getHeaderNames(); e.hasMoreElements(); ) {
        String headerName = e.nextElement().toString();
        authenticationRequest.addHeader(headerName, request.getHeader(headerName));
    }
    AuthenticationRequestCacheEntry authenticationRequestCacheEntry = new AuthenticationRequestCacheEntry(authenticationRequest);
    addAuthenticationRequestToRequest(request, authenticationRequestCacheEntry);
    OIDCSessionManagementUtil.removeOPBrowserStateCookie(request, response);
    sendRequestToFramework(request, response, sessionDataKey, FrameworkConstants.RequestType.CLAIM_TYPE_OIDC);
}
Also used : URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) Enumeration(java.util.Enumeration) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) OIDCSessionDataCacheEntry(org.wso2.carbon.identity.oidc.session.cache.OIDCSessionDataCacheEntry) AuthenticationRequest(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationRequest) OIDCSessionManagementException(org.wso2.carbon.identity.oidc.session.OIDCSessionManagementException) AuthenticationRequestCacheEntry(org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationRequestCacheEntry)

Example 17 with URLBuilderException

use of org.wso2.carbon.identity.core.URLBuilderException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method handleAuthFlowThroughFramework.

private Response handleAuthFlowThroughFramework(OAuthMessage oAuthMessage) throws URISyntaxException, InvalidRequestParentException {
    try {
        CommonAuthResponseWrapper responseWrapper = new CommonAuthResponseWrapper(oAuthMessage.getResponse());
        invokeCommonauthFlow(oAuthMessage, responseWrapper);
        return processAuthResponseFromFramework(oAuthMessage, responseWrapper);
    } catch (ServletException | IOException | URLBuilderException e) {
        log.error("Error occurred while sending request to authentication framework.");
        return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).build();
    }
}
Also used : ServletException(javax.servlet.ServletException) URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) IOException(java.io.IOException) CommonAuthResponseWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthResponseWrapper)

Example 18 with URLBuilderException

use of org.wso2.carbon.identity.core.URLBuilderException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpointTest method mockServiceURLBuilder.

private void mockServiceURLBuilder() throws URLBuilderException {
    ServiceURLBuilder builder = new ServiceURLBuilder() {

        String path = "";

        @Override
        public ServiceURLBuilder addPath(String... strings) {
            Arrays.stream(strings).forEach(x -> {
                path += "/" + x;
            });
            return this;
        }

        @Override
        public ServiceURLBuilder addParameter(String s, String s1) {
            return this;
        }

        @Override
        public ServiceURLBuilder setFragment(String s) {
            return this;
        }

        @Override
        public ServiceURLBuilder addFragmentParameter(String s, String s1) {
            return this;
        }

        @Override
        public ServiceURL build() throws URLBuilderException {
            ServiceURL serviceURL = mock(ServiceURL.class);
            when(serviceURL.getAbsolutePublicURL()).thenReturn("https://localhost:9443" + path);
            when(serviceURL.getRelativeInternalURL()).thenReturn(path);
            return serviceURL;
        }
    };
    mockStatic(ServiceURLBuilder.class);
    when(ServiceURLBuilder.create()).thenReturn(builder);
}
Also used : ServiceURL(org.wso2.carbon.identity.core.ServiceURL) Matchers.anyString(org.mockito.Matchers.anyString) ServiceURLBuilder(org.wso2.carbon.identity.core.ServiceURLBuilder)

Example 19 with URLBuilderException

use of org.wso2.carbon.identity.core.URLBuilderException in project identity-inbound-auth-oauth by wso2-extensions.

the class EndpointUtil method buildAuthenticationRequestCacheEntry.

private static AuthenticationRequestCacheEntry buildAuthenticationRequestCacheEntry(String clientId, boolean forceAuthenticate, boolean checkAuthentication, Map<String, String[]> reqParams) throws IdentityOAuth2Exception, URLBuilderException {
    AuthenticationRequest authenticationRequest = new AuthenticationRequest();
    int tenantId = OAuth2Util.getClientTenatId();
    // Build the authentication request context.
    String commonAuthCallerPath = ServiceURLBuilder.create().addPath(OAUTH2_AUTHORIZE).build().getRelativeInternalURL();
    authenticationRequest.setCommonAuthCallerPath(commonAuthCallerPath);
    authenticationRequest.setForceAuth(forceAuthenticate);
    authenticationRequest.setPassiveAuth(checkAuthentication);
    authenticationRequest.setRelyingParty(clientId);
    authenticationRequest.setTenantDomain(OAuth2Util.getTenantDomain(tenantId));
    authenticationRequest.setRequestQueryParams(reqParams);
    // Build an AuthenticationRequestCacheEntry which wraps AuthenticationRequestContext
    return new AuthenticationRequestCacheEntry(authenticationRequest);
}
Also used : AuthenticationRequest(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationRequest) AuthenticationRequestCacheEntry(org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationRequestCacheEntry)

Example 20 with URLBuilderException

use of org.wso2.carbon.identity.core.URLBuilderException in project identity-inbound-auth-oauth by wso2-extensions.

the class UserAuthenticationEndpoint method deviceAuthorize.

@POST
@Path("/")
@Consumes("application/x-www-form-urlencoded")
@Produces("text/html")
public Response deviceAuthorize(@Context HttpServletRequest request, @Context HttpServletResponse response) throws InvalidRequestParentException, OAuthSystemException {
    try {
        String userCode = request.getParameter(Constants.USER_CODE);
        // True when input(user_code) is not REQUIRED.
        if (StringUtils.isBlank(userCode)) {
            if (log.isDebugEnabled()) {
                log.debug("user_code is missing in the request.");
            }
            response.sendRedirect(ServiceURLBuilder.create().addPath(Constants.DEVICE_ENDPOINT_PATH).addParameter("error", OAuth2ErrorCodes.INVALID_REQUEST).build().getAbsolutePublicURL());
            return null;
        }
        String clientId = deviceAuthService.getClientId(userCode);
        DeviceFlowDO deviceFlowDODetails = DeviceFlowPersistenceFactory.getInstance().getDeviceFlowDAO().getDetailsForUserCode(userCode);
        if (StringUtils.isNotBlank(clientId) && deviceFlowDODetails != null && !isExpiredUserCode(deviceFlowDODetails)) {
            setCallbackURI(clientId);
            deviceAuthService.setAuthenticationStatus(userCode);
            CommonAuthRequestWrapper commonAuthRequestWrapper = new CommonAuthRequestWrapper(request);
            commonAuthRequestWrapper.setParameter(Constants.CLIENT_ID, clientId);
            commonAuthRequestWrapper.setParameter(Constants.RESPONSE_TYPE, Constants.RESPONSE_TYPE_DEVICE);
            commonAuthRequestWrapper.setParameter(Constants.REDIRECTION_URI, deviceFlowDO.getCallbackUri());
            if (getScope(userCode) != null) {
                String scope = String.join(Constants.SEPARATED_WITH_SPACE, getScope(userCode));
                commonAuthRequestWrapper.setParameter(Constants.SCOPE, scope);
            }
            commonAuthRequestWrapper.setParameter(Constants.NONCE, userCode);
            return oAuth2AuthzEndpoint.authorize(commonAuthRequestWrapper, response);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Incorrect user_code.");
            }
            response.sendRedirect(ServiceURLBuilder.create().addPath(Constants.DEVICE_ENDPOINT_PATH).addParameter("error", OAuth2ErrorCodes.INVALID_REQUEST).build().getAbsolutePublicURL());
            return null;
        }
    } catch (IdentityOAuth2Exception e) {
        return handleIdentityOAuth2Exception(e);
    } catch (IOException e) {
        return handleIOException(e);
    } catch (URLBuilderException e) {
        return handleURLBuilderException(e);
    } catch (URISyntaxException e) {
        return handleURISyntaxException(e);
    }
}
Also used : URLBuilderException(org.wso2.carbon.identity.core.URLBuilderException) CommonAuthRequestWrapper(org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) DeviceFlowDO(org.wso2.carbon.identity.oauth2.device.model.DeviceFlowDO) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Aggregations

URLBuilderException (org.wso2.carbon.identity.core.URLBuilderException)18 IOException (java.io.IOException)5 ServiceURLBuilder (org.wso2.carbon.identity.core.ServiceURLBuilder)5 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 Test (org.testng.annotations.Test)4 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)4 URISyntaxException (java.net.URISyntaxException)3 HashMap (java.util.HashMap)3 CommonAuthRequestWrapper (org.wso2.carbon.identity.application.authentication.framework.model.CommonAuthRequestWrapper)3 ServiceURL (org.wso2.carbon.identity.core.ServiceURL)3 URI (java.net.URI)2 Map (java.util.Map)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 ServletException (javax.servlet.ServletException)2 Consumes (javax.ws.rs.Consumes)2 POST (javax.ws.rs.POST)2 Path (javax.ws.rs.Path)2 Produces (javax.ws.rs.Produces)2 Matchers.anyString (org.mockito.Matchers.anyString)2 AuthenticationRequestCacheEntry (org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationRequestCacheEntry)2