org.wso2.carbon.registry.core.utils.UUIDGenerator Java Examples

The following examples show how to use org.wso2.carbon.registry.core.utils.UUIDGenerator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractCarbonUIAuthenticator.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param session
 * @param serviceClient
 * @param rememberMeCookie
 * @throws AxisFault
 */
protected void setAdminCookie(HttpSession session, ServiceClient serviceClient,
        String rememberMeCookie) throws AxisFault {
    String cookie = (String) serviceClient.getServiceContext().getProperty(
            HTTPConstants.COOKIE_STRING);

    if (cookie == null) {
        // For local transport - the cookie will be null.
        // This generated cookie cannot be used for any form authentication with the backend.
        // This is done to be backward compatible.
        cookie = UUIDGenerator.generateUUID();
    }

    if (rememberMeCookie != null) {
        cookie = cookie + "; " + rememberMeCookie;
    }

    if (session != null) {
        session.setAttribute(ServerConstants.ADMIN_SERVICE_AUTH_TOKEN, cookie);
    }
}
 
Example #2
Source File: UserAccountAssociationUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Generate random number for association key
 *
 * @return random number
 * @throws org.wso2.carbon.identity.user.account.association.exception.UserAccountAssociationException
 */
public static String getRandomNumber() throws UserAccountAssociationException {
    try {
        String secretKey = UUIDGenerator.generateUUID();
        String baseString = UUIDGenerator.generateUUID();

        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(key);
        byte[] rawHmac = mac.doFinal(baseString.getBytes());
        String random = Base64.encode(rawHmac);
        random = random.replace("/", "_");
        random = random.replace("=", "a");
        random = random.replace("+", "f");
        return random;
    } catch (Exception e) {
        throw new UserAccountAssociationException("Error when generating a random number.", e);
    }
}
 
Example #3
Source File: PostAuthenticationMgtService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
private void setPASTRCookie(AuthenticationContext context, HttpServletRequest request,
        HttpServletResponse response) {

    if (context.getParameter(FrameworkConstants.PASTR_COOKIE) != null) {
        if (log.isDebugEnabled()) {
            log.debug("PASTR cookie is already set to context : " + context.getContextIdentifier());
        }
        return;
    } else {
        if (log.isDebugEnabled()) {
            log.debug(
                    "PASTR cookie is not set to context : " + context.getContextIdentifier() + ". Hence setting the"
                            + " " + "cookie");
        }
        String pastrCookieValue = UUIDGenerator.generateUUID();
        FrameworkUtils
                .setCookie(request, response, FrameworkUtils.getPASTRCookieName(context.getContextIdentifier()),
                        pastrCookieValue, -1);
        context.addParameter(FrameworkConstants.PASTR_COOKIE, pastrCookieValue);
    }
}
 
Example #4
Source File: IdentityUtil.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a random number using two UUIDs and HMAC-SHA1
 *
 * @return Random Number generated.
 * @throws IdentityException Exception due to Invalid Algorithm or Invalid Key
 */
public static String getRandomNumber() throws IdentityException {
    try {
        String secretKey = UUIDGenerator.generateUUID();
        String baseString = UUIDGenerator.generateUUID();

        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(key);
        byte[] rawHmac = mac.doFinal(baseString.getBytes());
        String random = Base64.getEncoder().encodeToString(rawHmac);
        // Registry doesn't have support for these character.
        random = random.replace("/", "_");
        random = random.replace("=", "a");
        random = random.replace("+", "f");
        return random;
    } catch (Exception e) {
        log.error("Error when generating a random number.", e);
        throw IdentityException.error("Error when generating a random number.", e);
    }
}
 
Example #5
Source File: RecoveryProcessor.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
public VerificationBean updateConfirmationCode(int sequence, String username, int tenantId)
        throws IdentityException {

    String confirmationKey = generateUserCode(sequence, username);
    String secretKey = UUIDGenerator.generateUUID();

    UserRecoveryDataDO recoveryDataDO = new UserRecoveryDataDO(username,
            tenantId, confirmationKey, secretKey);

    if (sequence != 3 && sequence != 30) {
        dataStore.invalidate(username, tenantId);
    }
    dataStore.store(recoveryDataDO);
    String externalCode = null;
    try {
        externalCode = getUserExternalCodeStr(confirmationKey);
    } catch (Exception e) {
        throw IdentityException.error("Error occurred while getting external code for user : "
                + username, e);
    }

    return new VerificationBean(username, externalCode);
}
 
Example #6
Source File: OAuthUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a random number using two UUIDs and HMAC-SHA1
 *
 * @return generated secure random number
 * @throws IdentityOAuthAdminException Invalid Algorithm or Invalid Key
 */
public static String getRandomNumber() throws IdentityOAuthAdminException {
    try {
        String secretKey = UUIDGenerator.generateUUID();
        String baseString = UUIDGenerator.generateUUID();

        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(Charsets.UTF_8), ALGORITHM);
        Mac mac = Mac.getInstance(ALGORITHM);
        mac.init(key);
        byte[] rawHmac = mac.doFinal(baseString.getBytes(Charsets.UTF_8));
        String random = Base64.encode(rawHmac);
        // Registry doesn't have support for these character.
        random = random.replace("/", "_");
        random = random.replace("=", "a");
        random = random.replace("+", "f");
        return random;
    } catch (Exception e) {
        throw new IdentityOAuthAdminException("Error when generating a random number.", e);
    }
}
 
Example #7
Source File: RecoveryProcessor.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
public VerificationBean updateConfirmationCode(int sequence, String username, int tenantId) throws IdentityException {

        String confirmationKey = generateUserCode(sequence, username);
        String secretKey = UUIDGenerator.generateUUID();

        UserRecoveryDataDO recoveryDataDO = new UserRecoveryDataDO(username,
                tenantId, confirmationKey, secretKey);

        if (sequence != 3 && sequence != 30) {
            dataStore.invalidate(username, tenantId);
        }
        dataStore.store(recoveryDataDO);
        String externalCode = null;
        try {
            externalCode = getUserExternalCodeStr(confirmationKey);
        } catch (Exception e) {
            throw IdentityException.error("Error occurred while getting external code for user : "
                    + username, e);
        }

        return new VerificationBean(username, externalCode);
    }
 
Example #8
Source File: IdentityUtil.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a random number using two UUIDs and HMAC-SHA1
 *
 * @return Random Number generated.
 * @throws IdentityException Exception due to Invalid Algorithm or Invalid Key
 */
public static String getRandomNumber() throws IdentityException {
    try {
        String secretKey = UUIDGenerator.generateUUID();
        String baseString = UUIDGenerator.generateUUID();

        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(key);
        byte[] rawHmac = mac.doFinal(baseString.getBytes());
        String random = Base64.encode(rawHmac);
        // Registry doesn't have support for these character.
        random = random.replace("/", "_");
        random = random.replace("=", "a");
        random = random.replace("+", "f");
        return random;
    } catch (Exception e) {
        log.error("Error when generating a random number.", e);
        throw IdentityException.error("Error when generating a random number.", e);
    }
}
 
Example #9
Source File: PassiveSTS.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
private void handleAuthenticationRequest(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    Map paramMap = request.getParameterMap();

    SessionDTO sessionDTO = new SessionDTO();
    sessionDTO.setAction(getAttribute(paramMap, PassiveRequestorConstants.ACTION));
    sessionDTO.setAttributes(getAttribute(paramMap, PassiveRequestorConstants.ATTRIBUTE));
    sessionDTO.setContext(getAttribute(paramMap, PassiveRequestorConstants.CONTEXT));
    sessionDTO.setReplyTo(getAttribute(paramMap, PassiveRequestorConstants.REPLY_TO));
    sessionDTO.setPseudo(getAttribute(paramMap, PassiveRequestorConstants.PSEUDO));
    sessionDTO.setRealm(getAttribute(paramMap, PassiveRequestorConstants.REALM));
    sessionDTO.setRequest(getAttribute(paramMap, PassiveRequestorConstants.REQUEST));
    sessionDTO.setRequestPointer(getAttribute(paramMap, PassiveRequestorConstants.REQUEST_POINTER));
    sessionDTO.setPolicy(getAttribute(paramMap, PassiveRequestorConstants.POLCY));
    sessionDTO.setTenantDomain(getAttribute(paramMap, MultitenantConstants.TENANT_DOMAIN));
    sessionDTO.setReqQueryString(request.getQueryString());

    String sessionDataKey = UUIDGenerator.generateUUID();
    addSessionDataToCache(sessionDataKey, sessionDTO);

    sendToAuthenticationFramework(request, response, sessionDataKey, sessionDTO);
}
 
Example #10
Source File: SalesforceProvisioningConnector.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Alter username while changing user to active state to inactive state. This is necessary when adding previously
 * deleted users.
 *
 * @param provisioningEntity
 * @return
 * @throws IdentityProvisioningException
 */
protected String alterUsername(ProvisioningEntity provisioningEntity) throws IdentityProvisioningException {

    if (StringUtils.isBlank(provisioningEntity.getEntityName())) {
        throw new IdentityProvisioningException("Could Not Find Entity Name from Provisioning Entity");
    }
    String alteredUsername = SalesforceConnectorConstants.SALESFORCE_OLD_USERNAME_PREFIX +
                                UUIDGenerator.generateUUID() + provisioningEntity.getEntityName();

    if (log.isDebugEnabled()) {
        log.debug("Alter username: " + provisioningEntity.getEntityName() + " to: " + alteredUsername +
                  "while deleting user");
    }
    return alteredUsername;
}
 
Example #11
Source File: PassiveSTS.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private void sendFrameworkForLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Map paramMap = request.getParameterMap();
    SessionDTO sessionDTO = new SessionDTO();
    sessionDTO.setAction(getAttribute(paramMap, PassiveRequestorConstants.ACTION));
    sessionDTO.setAttributes(getAttribute(paramMap, PassiveRequestorConstants.ATTRIBUTE));
    sessionDTO.setContext(getAttribute(paramMap, PassiveRequestorConstants.CONTEXT));
    sessionDTO.setReplyTo(getAttribute(paramMap, PassiveRequestorConstants.REPLY_TO));
    sessionDTO.setPseudo(getAttribute(paramMap, PassiveRequestorConstants.PSEUDO));
    sessionDTO.setRealm(getAttribute(paramMap, PassiveRequestorConstants.REALM));
    sessionDTO.setRequest(getAttribute(paramMap, PassiveRequestorConstants.REQUEST));
    sessionDTO.setRequestPointer(getAttribute(paramMap, PassiveRequestorConstants.REQUEST_POINTER));
    sessionDTO.setPolicy(getAttribute(paramMap, PassiveRequestorConstants.POLCY));
    sessionDTO.setReqQueryString(request.getQueryString());

    String sessionDataKey = UUIDGenerator.generateUUID();
    addSessionDataToCache(sessionDataKey, sessionDTO);
    String commonAuthURL = IdentityUtil.getServerURL(FrameworkConstants.COMMONAUTH, false, true);

    String selfPath = request.getRequestURI();
    AuthenticationRequest authenticationRequest = new AuthenticationRequest();
    authenticationRequest.addRequestQueryParam(FrameworkConstants.RequestParams.LOGOUT,
            new String[]{Boolean.TRUE.toString()});
    authenticationRequest.setRequestQueryParams(request.getParameterMap());
    authenticationRequest.setCommonAuthCallerPath(selfPath);
    authenticationRequest.appendRequestQueryParams(request.getParameterMap());
    // According to ws-federation-1.2-spec; 'wtrealm' will not be sent in the Passive STS Logout Request.
    if (sessionDTO.getRealm() == null || sessionDTO.getRealm().trim().length() == 0) {
        authenticationRequest.setRelyingParty(new String());
    }
    for (Enumeration e = request.getHeaderNames(); e.hasMoreElements(); ) {
        String headerName = e.nextElement().toString();
        authenticationRequest.addHeader(headerName, request.getHeader(headerName));
    }

    AuthenticationRequestCacheEntry authRequest = new AuthenticationRequestCacheEntry
            (authenticationRequest);
    FrameworkUtils.addAuthenticationRequestToCache(sessionDataKey, authRequest);
    String queryParams = "?" + FrameworkConstants.SESSION_DATA_KEY + "=" + sessionDataKey
            + "&" + FrameworkConstants.RequestParams.TYPE + "=" + FrameworkConstants.PASSIVE_STS;

    response.sendRedirect(commonAuthURL + queryParams);

}
 
Example #12
Source File: SAMLSSOProviderServlet.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
private void sendToFrameworkForLogout(HttpServletRequest request, HttpServletResponse response,
                                      SAMLSSOReqValidationResponseDTO signInRespDTO, String relayState,
                                      String sessionId,
                                      boolean invalid, boolean isPost) throws ServletException, IOException {

    SAMLSSOSessionDTO sessionDTO = new SAMLSSOSessionDTO();
    sessionDTO.setHttpQueryString(request.getQueryString());
    sessionDTO.setRelayState(relayState);
    sessionDTO.setSessionId(sessionId);
    sessionDTO.setLogoutReq(true);
    sessionDTO.setInvalidLogout(invalid);

    if (signInRespDTO != null) {
        sessionDTO.setDestination(signInRespDTO.getDestination());
        sessionDTO.setRequestMessageString(signInRespDTO.getRequestMessageString());
        sessionDTO.setIssuer(signInRespDTO.getIssuer());
        sessionDTO.setRequestID(signInRespDTO.getId());
        sessionDTO.setSubject(signInRespDTO.getSubject());
        sessionDTO.setRelyingPartySessionId(signInRespDTO.getRpSessionId());
        sessionDTO.setAssertionConsumerURL(signInRespDTO.getAssertionConsumerURL());
        sessionDTO.setValidationRespDTO(signInRespDTO);
    }

    String sessionDataKey = UUIDGenerator.generateUUID();
    addSessionDataToCache(sessionDataKey, sessionDTO);


    String commonAuthURL = IdentityUtil.getServerURL(FrameworkConstants.COMMONAUTH, false, true);

    String selfPath = request.getContextPath();

    //Add all parameters to authentication context before sending to authentication
    // framework
    AuthenticationRequest authenticationRequest = new
            AuthenticationRequest();
    authenticationRequest.addRequestQueryParam(FrameworkConstants.RequestParams.LOGOUT,
                                               new String[]{"true"});
    authenticationRequest.setRequestQueryParams(request.getParameterMap());
    authenticationRequest.setCommonAuthCallerPath(selfPath);
    authenticationRequest.setPost(isPost);

    if (signInRespDTO != null) {
        authenticationRequest.setRelyingParty(signInRespDTO.getIssuer());
    }
    authenticationRequest.appendRequestQueryParams(request.getParameterMap());
    //Add headers to AuthenticationRequestContext
    for (Enumeration e = request.getHeaderNames(); e.hasMoreElements(); ) {
        String headerName = e.nextElement().toString();
        authenticationRequest.addHeader(headerName, request.getHeader(headerName));
    }

    AuthenticationRequestCacheEntry authRequest = new AuthenticationRequestCacheEntry
            (authenticationRequest);
    addAuthenticationRequestToRequest(request, authRequest);
    sendRequestToFramework(request, response, sessionDataKey, FrameworkConstants.RequestType.CLAIM_TYPE_SAML_SSO);
}
 
Example #13
Source File: SAMLSSOProviderServlet.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Sends the user for authentication to the login page
 *
 * @param req
 * @param resp
 * @param signInRespDTO
 * @param relayState
 * @throws ServletException
 * @throws IOException
 */
private void sendToFrameworkForAuthentication(HttpServletRequest req, HttpServletResponse resp,
                                              SAMLSSOReqValidationResponseDTO signInRespDTO, String relayState, boolean isPost)
        throws ServletException, IOException, UserStoreException, IdentityException {

    SAMLSSOSessionDTO sessionDTO = new SAMLSSOSessionDTO();
    sessionDTO.setHttpQueryString(req.getQueryString());
    sessionDTO.setDestination(signInRespDTO.getDestination());
    sessionDTO.setRelayState(relayState);
    sessionDTO.setRequestMessageString(signInRespDTO.getRequestMessageString());
    sessionDTO.setIssuer(signInRespDTO.getIssuer());
    sessionDTO.setRequestID(signInRespDTO.getId());
    sessionDTO.setSubject(signInRespDTO.getSubject());
    sessionDTO.setRelyingPartySessionId(signInRespDTO.getRpSessionId());
    sessionDTO.setAssertionConsumerURL(signInRespDTO.getAssertionConsumerURL());
    sessionDTO.setTenantDomain(SAMLSSOUtil.getTenantDomainFromThreadLocal());
    sessionDTO.setAttributeConsumingServiceIndex(signInRespDTO.getAttributeConsumingServiceIndex());
    sessionDTO.setForceAuth(signInRespDTO.isForceAuthn());
    sessionDTO.setPassiveAuth(signInRespDTO.isPassive());
    sessionDTO.setValidationRespDTO(signInRespDTO);
    sessionDTO.setIdPInitSSO(signInRespDTO.isIdPInitSSO());

    String sessionDataKey = UUIDGenerator.generateUUID();
    addSessionDataToCache(sessionDataKey, sessionDTO);

    String commonAuthURL = IdentityUtil.getServerURL(FrameworkConstants.COMMONAUTH, false, true);
    String selfPath = req.getContextPath();
    // Setting authentication request context
    AuthenticationRequest authenticationRequest = new AuthenticationRequest();

    // Adding query parameters
    authenticationRequest.appendRequestQueryParams(req.getParameterMap());
    for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements(); ) {
        String headerName = headerNames.nextElement().toString();
        authenticationRequest.addHeader(headerName, req.getHeader(headerName));
    }

    authenticationRequest.setRelyingParty(signInRespDTO.getIssuer());
    authenticationRequest.setCommonAuthCallerPath(selfPath);
    authenticationRequest.setForceAuth(signInRespDTO.isForceAuthn());
    if (!authenticationRequest.getForceAuth() && authenticationRequest.getRequestQueryParam("forceAuth") != null) {
        String[] forceAuth = authenticationRequest.getRequestQueryParam("forceAuth");
        if (!forceAuth[0].trim().isEmpty() && Boolean.parseBoolean(forceAuth[0].trim())) {
            authenticationRequest.setForceAuth(Boolean.parseBoolean(forceAuth[0].trim()));
        }
    }
    authenticationRequest.setPassiveAuth(signInRespDTO.isPassive());
    authenticationRequest.setTenantDomain(sessionDTO.getTenantDomain());
    authenticationRequest.setPost(isPost);

    // Creating cache entry and adding entry to the cache before calling to commonauth
    AuthenticationRequestCacheEntry authRequest = new AuthenticationRequestCacheEntry
            (authenticationRequest);
    addAuthenticationRequestToRequest(req, authRequest);
    FrameworkUtils.setRequestPathCredentials(req);
    sendRequestToFramework(req, resp, sessionDataKey, FrameworkConstants.RequestType.CLAIM_TYPE_SAML_SSO);
}
 
Example #14
Source File: IdentityProcessor.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Get IdentityResponseBuilder for framework login
 *
 * @param context IdentityMessageContext
 * @return IdentityResponseBuilder
 */
protected FrameworkLoginResponse.FrameworkLoginResponseBuilder buildResponseForFrameworkLogin(
        IdentityMessageContext context) {

    IdentityRequest identityRequest = context.getRequest();
    Map<String, String[]> parameterMap = identityRequest.getParameterMap();

    AuthenticationRequest authenticationRequest = new AuthenticationRequest();
    authenticationRequest.appendRequestQueryParams(parameterMap);
    Set<Map.Entry<String,String>> headers = new HashMap(identityRequest.getHeaderMap()).entrySet();
    for (Map.Entry<String,String> header : headers) {
        authenticationRequest.addHeader(header.getKey(), header.getValue());
    }
    authenticationRequest.setTenantDomain(identityRequest.getTenantDomain());
    authenticationRequest.setRelyingParty(getRelyingPartyId(context));
    authenticationRequest.setType(getType(context));
    authenticationRequest.setPassiveAuth(Boolean.parseBoolean(
            String.valueOf(context.getParameter(InboundConstants.PassiveAuth))));
    authenticationRequest.setForceAuth(Boolean.parseBoolean(
            String.valueOf(context.getParameter(InboundConstants.ForceAuth))));
    try {
        authenticationRequest.setCommonAuthCallerPath(URLEncoder.encode(getCallbackPath(context),
                                                                        StandardCharsets.UTF_8.name()));
    } catch (UnsupportedEncodingException e) {
        throw FrameworkRuntimeException.error("Error occurred while URL encoding callback path " +
                getCallbackPath(context), e);
    }

    AuthenticationRequestCacheEntry authRequest = new AuthenticationRequestCacheEntry(authenticationRequest);
    String sessionDataKey = UUIDGenerator.generateUUID();
    authRequest.setValidityPeriod(TimeUnit.MINUTES.toNanos(IdentityUtil.getOperationCleanUpTimeout()));
    FrameworkUtils.addAuthenticationRequestToCache(sessionDataKey, authRequest);

    InboundUtil.addContextToCache(sessionDataKey, context);

    FrameworkLoginResponse.FrameworkLoginResponseBuilder responseBuilder =
            new FrameworkLoginResponse.FrameworkLoginResponseBuilder(context);
    responseBuilder.setAuthName(getType(context));
    responseBuilder.setContextKey(sessionDataKey);
    responseBuilder.setCallbackPath(getCallbackPath(context));
    responseBuilder.setRelyingParty(getRelyingPartyId(context));
    //type parameter is using since framework checking it, but future it'll use AUTH_NAME
    responseBuilder.setAuthType(getType(context));
    String commonAuthURL = IdentityUtil.getServerURL(FrameworkConstants.COMMONAUTH, true, true);
    responseBuilder.setRedirectURL(commonAuthURL);
    return responseBuilder;
}
 
Example #15
Source File: OpenIDHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the login page URL. User will be redirected to this URL when they
 * are not authenticated.
 *
 * @param claimedID
 * @param request
 * @param params
 * @return loginPageUrl
 * @throws IdentityException
 * @throws IOException
 */
private String getLoginPageUrl(String claimedID, HttpServletRequest request, ParameterList params)
        throws IdentityException, IOException {
        
    /*
     * We are setting the request's openid identifier to the session
     * here.  
     */
    request.getSession().setAttribute(OpenIDConstants.SessionAttribute.OPENID, claimedID);

    String commonAuthURL = IdentityUtil.getServerURL(FrameworkConstants.COMMONAUTH, false, true);
    String selfPath = request.getContextPath();
    String sessionDataKey = UUIDGenerator.generateUUID();

    //Authentication context keeps data which should be sent to commonAuth endpoint
    AuthenticationRequest authenticationRequest = new
            AuthenticationRequest();
    authenticationRequest.setRelyingParty(getRelyingParty(request));
    authenticationRequest.setCommonAuthCallerPath(selfPath);
    String username = null;
    String tenantDomain = null;
    if (params.getParameterValue(FrameworkConstants.OPENID_IDENTITY) != null) {
        username = OpenIDUtil.getUserName(params.getParameterValue(FrameworkConstants.OPENID_IDENTITY));
        authenticationRequest.addRequestQueryParam(FrameworkConstants.USERNAME, new String[] { username });
    }
    if (params.getParameterValue(FrameworkConstants.RequestParams.TENANT_DOMAIN) != null) {
        tenantDomain = params.getParameterValue(FrameworkConstants.RequestParams.TENANT_DOMAIN);
        authenticationRequest.setTenantDomain(tenantDomain);
    }

    boolean forceAuthenticate = false;
    if (!claimedID.endsWith("/openid/")) {
        String authenticatedUser =
                (String) request.getSession().getAttribute(OpenIDConstants.SessionAttribute.AUTHENTICATED_OPENID);
        if (log.isDebugEnabled()) {
            log.debug("claimedID : " + claimedID + ", authenticated user : " + authenticatedUser);
        }
        if (authenticatedUser != null && !"".equals(authenticatedUser.trim())
            && !claimedID.equals(authenticatedUser.trim())) {
            if (log.isDebugEnabled()) {
                log.debug("Overriding previously authenticated OpenID : " + authenticatedUser
                          + " with the OpenID in the current request :" + claimedID
                          + " and setting forceAuthenticate.");
            }
            forceAuthenticate = true;
        }
    }
    authenticationRequest.setForceAuth(forceAuthenticate);
    //Add request headers to authentication request context. ie to cache
    authenticationRequest.setRequestQueryParams(request.getParameterMap());
    for (Enumeration headerNames = request.getHeaderNames(); headerNames.hasMoreElements(); ) {
        String headerName = headerNames.nextElement().toString();
        authenticationRequest.addHeader(headerName, request.getHeader(headerName));
    }

    AuthenticationRequestCacheEntry authRequest = new AuthenticationRequestCacheEntry(authenticationRequest);
    FrameworkUtils.addAuthenticationRequestToCache(sessionDataKey, authRequest);
    StringBuilder queryStringBuilder = new StringBuilder();
    queryStringBuilder.append(commonAuthURL).
            append("?").
                              append(FrameworkConstants.SESSION_DATA_KEY).
                              append("=").
                              append(sessionDataKey).
                              append("&").
                              append(FrameworkConstants.RequestParams.TYPE).
                              append("=").
                              append(FrameworkConstants.RequestType.CLAIM_TYPE_OPENID);
    // reading the authorization header for request path authentication
    FrameworkUtils.setRequestPathCredentials(request);

    return queryStringBuilder.toString();
}
 
Example #16
Source File: DefaultRequestCoordinator.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Handles the initial request (from the calling servlet)
 *
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 * @throws
 */
protected AuthenticationContext initializeFlow(HttpServletRequest request,
                                               HttpServletResponse response) throws FrameworkException {

    if (log.isDebugEnabled()) {
        log.debug("Initializing the flow");
    }


    // "sessionDataKey" - calling servlet maintains its state information
    // using this
    String callerSessionDataKey = request.getParameter(FrameworkConstants.SESSION_DATA_KEY);

    // "commonAuthCallerPath" - path of the calling servlet. This is the url
    // response should be sent to
    String callerPath = getCallerPath(request);

    // "type" - type of the request. e.g. samlsso, openid, oauth, passivests
    String requestType = request.getParameter(FrameworkConstants.RequestParams.TYPE);

    // "relyingParty"
    String relyingParty = request.getParameter(FrameworkConstants.RequestParams.ISSUER);

    // tenant domain
    String tenantDomain = getTenantDomain(request);

    // Store the request data sent by the caller
    AuthenticationContext context = new AuthenticationContext();
    context.setCallerSessionKey(callerSessionDataKey);
    context.setCallerPath(callerPath);
    context.setRequestType(requestType);
    context.setRelyingParty(relyingParty);
    context.setTenantDomain(tenantDomain);

    // generate a new key to hold the context data object
    String contextId = UUIDGenerator.generateUUID();
    context.setContextIdentifier(contextId);

    if (log.isDebugEnabled()) {
        log.debug("Framework contextId: " + contextId);
    }


    // if this a logout request from the calling servlet
    if (request.getParameter(FrameworkConstants.RequestParams.LOGOUT) != null) {

        if (log.isDebugEnabled()) {
            log.debug("Starting a logout flow");
        }

        context.setLogoutRequest(true);

        if (context.getRelyingParty() == null || context.getRelyingParty().trim().length() == 0) {

            if (log.isDebugEnabled()) {
                log.debug("relyingParty param is null. This is a possible logout scenario.");
            }

            Cookie cookie = FrameworkUtils.getAuthCookie(request);

            if (cookie != null) {
                context.setSessionIdentifier(cookie.getValue());
            }

            return context;
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Starting an authentication flow");
        }
    }

    findPreviousAuthenticatedSession(request, context);
    buildOutboundQueryString(request, context);

    return context;
}
 
Example #17
Source File: InboundAuthenticationRequestProcessor.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Build response for framework logout
 *
 * @param context Inbound authentication context
 * @return
 * @throws IOException
 * @throws IdentityApplicationManagementException
 * @throws FrameworkException
 */
protected InboundAuthenticationResponse buildResponseForFrameworkLogout(InboundAuthenticationContext context)
        throws IOException, IdentityApplicationManagementException, FrameworkException {

    String sessionDataKey = UUIDGenerator.generateUUID();

    AuthenticationRequest authenticationRequest = new AuthenticationRequest();
    InboundAuthenticationRequest inboundAuthenticationRequest = context.getInboundAuthenticationRequest();

    Map<String, String[]> parameterMap = inboundAuthenticationRequest.getParameters();

    parameterMap.put(FrameworkConstants.SESSION_DATA_KEY, new String[] { sessionDataKey });
    parameterMap.put(FrameworkConstants.RequestParams.TYPE, new String[] { getName() });

    authenticationRequest.appendRequestQueryParams(parameterMap);

    for (Map.Entry<String, String> entry : inboundAuthenticationRequest.getHeaders().entrySet()) {
        authenticationRequest.addHeader(entry.getKey(), entry.getValue());
    }

    authenticationRequest.setRelyingParty(getRelyingPartyId());
    authenticationRequest.setType(getName());
    authenticationRequest.setCommonAuthCallerPath(URLEncoder.encode(getCallbackPath(context), "UTF-8"));
    authenticationRequest.addRequestQueryParam(FrameworkConstants.RequestParams.LOGOUT,
            new String[]{"true"});

    AuthenticationRequestCacheEntry authRequest = new AuthenticationRequestCacheEntry(authenticationRequest);
    FrameworkUtils.addAuthenticationRequestToCache(sessionDataKey, authRequest);

    InboundAuthenticationContextCacheEntry contextCacheEntry = new InboundAuthenticationContextCacheEntry(context);
    InboundAuthenticationUtil.addInboundAuthenticationContextToCache(sessionDataKey, contextCacheEntry);

    InboundAuthenticationResponse response = new InboundAuthenticationResponse();
    response.addParameters(InboundAuthenticationConstants.RequestProcessor.AUTH_NAME, getName());
    response.addParameters(InboundAuthenticationConstants.RequestProcessor.SESSION_DATA_KEY, sessionDataKey);
    response.addParameters(InboundAuthenticationConstants.RequestProcessor.CALL_BACK_PATH,
            getCallbackPath(context));
    response.addParameters(InboundAuthenticationConstants.RequestProcessor.RELYING_PARTY, getRelyingPartyId());
    //type parameter is using since framework checking it, but future it'll use AUTH_NAME
    response.addParameters(InboundAuthenticationConstants.RequestProcessor.AUTH_TYPE, getName());
    String commonAuthURL = IdentityUtil.getServerURL(FrameworkConstants.COMMONAUTH, true, true);
    response.setRedirectURL(commonAuthURL);
    return response;
}
 
Example #18
Source File: InboundAuthenticationRequestProcessor.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * Build response for framework login
 *
 * @param context Inbound authentication context
 * @return
 * @throws IOException
 * @throws IdentityApplicationManagementException
 * @throws FrameworkException
 */
protected InboundAuthenticationResponse buildResponseForFrameworkLogin(InboundAuthenticationContext context)
        throws IOException, IdentityApplicationManagementException, FrameworkException {

    String sessionDataKey = UUIDGenerator.generateUUID();

    AuthenticationRequest authenticationRequest = new AuthenticationRequest();
    InboundAuthenticationRequest inboundAuthenticationRequest = context.getInboundAuthenticationRequest();

    Map<String, String[]> parameterMap = inboundAuthenticationRequest.getParameters();

    parameterMap.put(FrameworkConstants.SESSION_DATA_KEY, new String[] { sessionDataKey });
    parameterMap.put(FrameworkConstants.RequestParams.TYPE, new String[] { getName() });

    authenticationRequest.appendRequestQueryParams(parameterMap);

    for (Map.Entry<String, String> entry : inboundAuthenticationRequest.getHeaders().entrySet()) {
        authenticationRequest.addHeader(entry.getKey(), entry.getValue());
    }

    authenticationRequest.setRelyingParty(getRelyingPartyId());
    authenticationRequest.setType(getName());
    authenticationRequest.setCommonAuthCallerPath(URLEncoder.encode(getCallbackPath(context), "UTF-8"));

    AuthenticationRequestCacheEntry authRequest = new AuthenticationRequestCacheEntry(authenticationRequest);
    FrameworkUtils.addAuthenticationRequestToCache(sessionDataKey, authRequest);

    InboundAuthenticationContextCacheEntry contextCacheEntry = new InboundAuthenticationContextCacheEntry(context);
    InboundAuthenticationUtil.addInboundAuthenticationContextToCache(sessionDataKey, contextCacheEntry);

    InboundAuthenticationResponse response = new InboundAuthenticationResponse();
    response.addParameters(InboundAuthenticationConstants.RequestProcessor.AUTH_NAME, getName());
    response.addParameters(InboundAuthenticationConstants.RequestProcessor.SESSION_DATA_KEY, sessionDataKey);
    response.addParameters(InboundAuthenticationConstants.RequestProcessor.CALL_BACK_PATH,
            getCallbackPath(context));
    response.addParameters(InboundAuthenticationConstants.RequestProcessor.RELYING_PARTY, getRelyingPartyId());
    //type parameter is using since framework checking it, but future it'll use AUTH_NAME
    response.addParameters(InboundAuthenticationConstants.RequestProcessor.AUTH_TYPE, getName());
    String commonAuthURL = IdentityUtil.getServerURL(FrameworkConstants.COMMONAUTH, true, true);
    response.setRedirectURL(commonAuthURL);
    return response;
}
 
Example #19
Source File: DefaultRequestCoordinator.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Handles the initial request (from the calling servlet)
 *
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 * @throws
 */
protected AuthenticationContext initializeFlow(HttpServletRequest request, HttpServletResponse response)
        throws FrameworkException {

    if (log.isDebugEnabled()) {
        log.debug("Initializing the flow");
    }

    // "sessionDataKey" - calling servlet maintains its state information
    // using this
    String callerSessionDataKey = request.getParameter(FrameworkConstants.SESSION_DATA_KEY);

    // "commonAuthCallerPath" - path of the calling servlet. This is the url
    // response should be sent to
    String callerPath = getCallerPath(request);

    // "type" - type of the request. e.g. samlsso, openid, oauth, passivests
    String requestType = request.getParameter(FrameworkConstants.RequestParams.TYPE);

    // "relyingParty"
    String relyingParty = request.getParameter(FrameworkConstants.RequestParams.ISSUER);

    // tenant domain
    String tenantDomain = getTenantDomain(request);

    // Store the request data sent by the caller
    AuthenticationContext context = new AuthenticationContext();
    context.setCallerSessionKey(callerSessionDataKey);
    context.setCallerPath(callerPath);
    context.setRequestType(requestType);
    context.setRelyingParty(relyingParty);
    context.setTenantDomain(tenantDomain);

    // generate a new key to hold the context data object
    String contextId = UUIDGenerator.generateUUID();
    context.setContextIdentifier(contextId);

    if (log.isDebugEnabled()) {
        log.debug("Framework contextId: " + contextId);
    }

    // if this a logout request from the calling servlet
    if (request.getParameter(FrameworkConstants.RequestParams.LOGOUT) != null) {

        if (log.isDebugEnabled()) {
            log.debug("Starting a logout flow");
        }

        context.setLogoutRequest(true);

        if (context.getRelyingParty() == null || context.getRelyingParty().trim().length() == 0) {

            if (log.isDebugEnabled()) {
                log.debug("relyingParty param is null. This is a possible logout scenario.");
            }

            Cookie cookie = FrameworkUtils.getAuthCookie(request);

            String sessionContextKey = null;
            if (cookie != null) {
                sessionContextKey = DigestUtils.sha256Hex(cookie.getValue());
            } else {
                sessionContextKey = request.getParameter(SESSION_ID);
            }
            context.setSessionIdentifier(sessionContextKey);
            return context;
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Starting an authentication flow");
        }
    }

    List<ClaimMapping> requestedClaimsInRequest = (List<ClaimMapping>) request.getAttribute(REQUESTED_ATTRIBUTES);
    context.setProperty(FrameworkConstants.SP_REQUESTED_CLAIMS_IN_REQUEST, requestedClaimsInRequest);

    associateTransientRequestData(request, response, context);
    findPreviousAuthenticatedSession(request, context);
    buildOutboundQueryString(request, context);

    return context;
}
 
Example #20
Source File: IdentityProcessor.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Get IdentityResponseBuilder for framework logout
 *
 * @param context IdentityMessageContext
 * @return IdentityResponseBuilder
 */
protected FrameworkLogoutResponse.FrameworkLogoutResponseBuilder buildResponseForFrameworkLogout(
        IdentityMessageContext context) {

    IdentityRequest identityRequest = context.getRequest();
    Map<String, String[]> parameterMap = identityRequest.getParameterMap();

    AuthenticationRequest authenticationRequest = new AuthenticationRequest();
    authenticationRequest.appendRequestQueryParams(parameterMap);
    Set<Map.Entry<String,String>> headers = new HashMap(identityRequest.getHeaderMap()).entrySet();
    for (Map.Entry<String,String> header : headers) {
        authenticationRequest.addHeader(header.getKey(), header.getValue());
    }
    authenticationRequest.setTenantDomain(identityRequest.getTenantDomain());
    authenticationRequest.setRelyingParty(getRelyingPartyId(context));
    authenticationRequest.setType(getType(context));
    try {
        authenticationRequest.setCommonAuthCallerPath(URLEncoder.encode(getCallbackPath(context),
                                                                        StandardCharsets.UTF_8.name()));
    } catch (UnsupportedEncodingException e) {
        throw FrameworkRuntimeException.error("Error occurred while URL encoding callback path " +
                getCallbackPath(context), e);
    }
    authenticationRequest.addRequestQueryParam(FrameworkConstants.RequestParams.LOGOUT, new String[]{"true"});

    AuthenticationRequestCacheEntry authRequest = new AuthenticationRequestCacheEntry(authenticationRequest);
    String sessionDataKey = UUIDGenerator.generateUUID();
    authRequest.setValidityPeriod(TimeUnit.MINUTES.toNanos(IdentityUtil.getOperationCleanUpTimeout()));
    FrameworkUtils.addAuthenticationRequestToCache(sessionDataKey, authRequest);

    InboundUtil.addContextToCache(sessionDataKey, context);

    FrameworkLogoutResponse.FrameworkLogoutResponseBuilder responseBuilder =
            new FrameworkLogoutResponse.FrameworkLogoutResponseBuilder(context);
    responseBuilder.setAuthName(getType(context));
    responseBuilder.setContextKey(sessionDataKey);
    responseBuilder.setCallbackPath(getCallbackPath(context));
    responseBuilder.setRelyingParty(getRelyingPartyId(context));
    //type parameter is using since framework checking it, but future it'll use AUTH_NAME
    responseBuilder.setAuthType(getType(context));
    String commonAuthURL = IdentityUtil.getServerURL(FrameworkConstants.COMMONAUTH, true, true);
    responseBuilder.setRedirectURL(commonAuthURL);
    return responseBuilder;
}
 
Example #21
Source File: WorkflowExecutor.java    From carbon-apimgt with Apache License 2.0 2 votes vote down vote up
/**
 * Method generates and returns UUID
 *
 * @return UUID
 */
public String generateUUID() {
    return UUIDGenerator.generateUUID();
}