Java Code Examples for org.apache.axis2.context.MessageContext#getCurrentMessageContext()

The following examples show how to use org.apache.axis2.context.MessageContext#getCurrentMessageContext() . 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: OpenIDProviderService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param username
 * @param operation
 * @throws IdentityProviderException
 */
private void checkUserAuthorization(String username, String operation) throws IdentityProviderException {
    MessageContext msgContext = MessageContext.getCurrentMessageContext();
    HttpServletRequest request = (HttpServletRequest) msgContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
    HttpSession httpSession = request.getSession(false);
    if (httpSession != null) {
        String userName = (String) httpSession.getAttribute(OpenIDServerConstants.OPENID_LOGGEDIN_USER);
        if (!username.equals(userName)) {
            throw new IdentityProviderException("Unauthorised action by user " + username +
                                                " to access " + operation);
        }
        return;
    }
    throw new IdentityProviderException("Unauthorised action by user " + username +
                                        " to access " + operation);
}
 
Example 2
Source File: IdentityProviderService.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * @param username
 * @param operation
 * @throws IdentityProviderException
 */
private void checkUserAuthorization(String username, String operation) throws IdentityProviderException {
    MessageContext msgContext = MessageContext.getCurrentMessageContext();
    HttpServletRequest request = (HttpServletRequest) msgContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
    HttpSession httpSession = request.getSession(false);

    String tenantFreeUsername = MultitenantUtils.getTenantAwareUsername(username);

    if (httpSession != null) {
        String loggedInUsername = (String) httpSession.getAttribute(ServerConstants.USER_LOGGED_IN);
        if (!tenantFreeUsername.equals(loggedInUsername)) {
            throw new IdentityProviderException("Unauthorised action by user " + username
                                                + " to access " + operation);
        }
    } else {
        throw new IdentityProviderException("Unauthorised action by user " + tenantFreeUsername
                                            + " to access " + operation);
    }
}
 
Example 3
Source File: DSSessionManager.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an object stored in the session with the given name.
 */
private static Object getSessionObject(String name) {
	MessageContext messageContext = MessageContext.getCurrentMessageContext();
	if (messageContext != null) {
		ServiceContext serviceContext = messageContext.getServiceContext();
		if (serviceContext != null) {
			return serviceContext.getProperty(name);
		}			
	} else {
		return threadLocalSession.get().get(name);
	}
	return null;
}
 
Example 4
Source File: MethodTimeLogger.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * If the pointcuts results true, this method is invoked every time a method satisfies the
 * criteria given in the pointcut.
 *
 * @param point The JoinPoint before method execution
 * @return result of method execution
 * @throws Throwable
 */
@Around("isConfigEnabled() && (pointCut() || pointCutAll())")
public Object log(ProceedingJoinPoint point) throws Throwable {
    long start = System.currentTimeMillis();
    MethodSignature signature = (MethodSignature) point.getSignature();
    Object result = point.proceed();
    String[] args = signature.getParameterNames();

    String argString;
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("[");
    if (args != null && args.length != 0) {
        String delimiter = "";
        for (String arg : args) {
            stringBuilder.append(delimiter);
            delimiter = ", ";
            stringBuilder.append(arg);
        }
    }
    stringBuilder.append("]");
    argString = stringBuilder.toString();
    MessageContext messageContext = MessageContext.getCurrentMessageContext();
    if (messageContext != null) {
        Map headers = (Map) messageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        if (headers != null) {
            String correlationId = (String) headers.get(APIConstants.AM_ACTIVITY_ID);
            if (correlationId != null) {
                MDC.put(APIConstants.CORRELATION_ID, correlationId);
            }
        }
    }
    log.info((System.currentTimeMillis() - start) + "|METHOD|" +
            MethodSignature.class.cast(point.getSignature()).getDeclaringTypeName() + "|" +
            MethodSignature.class.cast(point.getSignature()).getMethod().getName()+ "|" + argString);
    return result;
}
 
Example 5
Source File: MultipleCredentialsUserProxy.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
/**
 * Gets logged in user of the server
 *
 * @return user name
 */
private String getLoggedInUser() {

    MessageContext context = MessageContext.getCurrentMessageContext();
    if (context != null) {
        HttpServletRequest request =
                (HttpServletRequest) context.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
        if (request != null) {
            HttpSession httpSession = request.getSession(false);
            return (String) httpSession.getAttribute(ServerConstants.USER_LOGGED_IN);
        }
    }
    return null;
}
 
Example 6
Source File: MethodTimeLogger.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * If the pointcuts results true, this method is invoked every time a method satisfies the
 * criteria given in the pointcut.
 *
 * @param point The JoinPoint before method execution
 * @return result of method execution
 * @throws Throwable
 */
@Around("isConfigEnabled() && (pointCut() || pointCutAll())")
public Object log(ProceedingJoinPoint point) throws Throwable {
    long start = System.currentTimeMillis();
    MethodSignature signature = (MethodSignature) point.getSignature();
    Object result = point.proceed();
    String[] args = signature.getParameterNames();

    String argString;
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("[");
    if (args != null && args.length != 0) {
        String delimiter = "";
        for (String arg : args) {
            stringBuilder.append(delimiter);
            delimiter = ", ";
            stringBuilder.append(arg);
        }
    }
    stringBuilder.append("]");
    argString = stringBuilder.toString();
    MessageContext messageContext = MessageContext.getCurrentMessageContext();
    if(MDC.get(APIConstants.CORRELATION_ID) == null) {
        if (messageContext != null) {
            Map headers =
                    (Map) messageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
            if (headers != null) {
                String correlationId = (String) headers.get(APIConstants.AM_ACTIVITY_ID);
                if (correlationId != null) {
                    MDC.put(APIConstants.CORRELATION_ID, correlationId);
                }
            }
        }
    }
    log.info((System.currentTimeMillis() - start) + "|METHOD|" +
            MethodSignature.class.cast(point.getSignature()).getDeclaringTypeName() + "|" +
            MethodSignature.class.cast(point.getSignature()).getMethod().getName()+ "|" + argString);
    return result;
}
 
Example 7
Source File: UserProfileAdmin.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
private boolean isAuthorized(String targetUser) throws UserStoreException, CarbonException {
    boolean isAuthrized = false;
    MessageContext msgContext = MessageContext.getCurrentMessageContext();
    HttpServletRequest request = (HttpServletRequest) msgContext
            .getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
    HttpSession httpSession = request.getSession(false);
    if (httpSession != null) {
        String userName = (String) httpSession.getAttribute(ServerConstants.USER_LOGGED_IN);
        isAuthrized = UserProfileUtil.isUserAuthorizedToConfigureProfile(getUserRealm(), userName, targetUser);
    }
    return isAuthrized;
}
 
Example 8
Source File: UserProfileAdmin.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
private boolean isAuthorized(String targetUser, String permissionString) throws UserStoreException,
        CarbonException {
    boolean isAuthrized = false;
    MessageContext msgContext = MessageContext.getCurrentMessageContext();
    HttpServletRequest request = (HttpServletRequest) msgContext
            .getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
    HttpSession httpSession = request.getSession(false);
    if (httpSession != null) {
        String userName = (String) httpSession.getAttribute(ServerConstants.USER_LOGGED_IN);
        isAuthrized = isUserAuthorizedToConfigureProfile(getUserRealm(), userName, targetUser, permissionString);
    }
    return isAuthrized;
}
 
Example 9
Source File: MultipleCredentialsUserProxy.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Gets logged in user of the server
 *
 * @return user name
 */
private String getLoggedInUser() {

    MessageContext context = MessageContext.getCurrentMessageContext();
    if (context != null) {
        HttpServletRequest request =
                (HttpServletRequest) context.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
        if (request != null) {
            HttpSession httpSession = request.getSession(false);
            return (String) httpSession.getAttribute(ServerConstants.USER_LOGGED_IN);
        }
    }
    return null;
}
 
Example 10
Source File: MethodTimeLogger.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * If the pointcuts results true, this method is invoked every time a method satisfies the
 * criteria given in the pointcut.
 *
 * @param point The JoinPoint before method execution
 * @return result of method execution
 * @throws Throwable
 */
@Around("isConfigEnabled() && (pointCut() || pointCutAll())")
public Object log(ProceedingJoinPoint point) throws Throwable {
    long start = System.currentTimeMillis();
    MethodSignature signature = (MethodSignature) point.getSignature();
    Object result = point.proceed();
    String[] args = signature.getParameterNames();

    String argString;
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("[");
    if (args != null && args.length != 0) {
        String delimiter = "";
        for (String arg : args) {
            stringBuilder.append(delimiter);
            delimiter = ", ";
            stringBuilder.append(arg);
        }
    }
    stringBuilder.append("]");
    argString = stringBuilder.toString();
    MessageContext messageContext = MessageContext.getCurrentMessageContext();
    if (messageContext != null) {
        Map headers = (Map) messageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        if (headers != null) {
            String correlationId = (String) headers.get(APIConstants.AM_ACTIVITY_ID);
            if (correlationId != null) {
                MDC.put(APIConstants.CORRELATION_ID, correlationId);
            }
        }
    }
    log.info((System.currentTimeMillis() - start) + "|METHOD|" +
            MethodSignature.class.cast(point.getSignature()).getDeclaringTypeName() + "|" +
            MethodSignature.class.cast(point.getSignature()).getMethod().getName()+ "|" + argString);
    return result;
}
 
Example 11
Source File: MethodTimeLogger.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * If the pointcuts results true, this method is invoked every time a method satisfies the
 * criteria given in the pointcut.
 *
 * @param point The JoinPoint before method execution
 * @return result of method execution
 * @throws Throwable
 */
@Around("isConfigEnabled() && (pointCut() || pointCutAll())")
public Object log(ProceedingJoinPoint point) throws Throwable {
    long start = System.currentTimeMillis();
    MethodSignature signature = (MethodSignature) point.getSignature();
    Object result = point.proceed();
    String[] args = signature.getParameterNames();

    String argString;
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("[");
    if (args != null && args.length != 0) {
        String delimiter = "";
        for (String arg : args) {
            stringBuilder.append(delimiter);
            delimiter = ", ";
            stringBuilder.append(arg);
        }
    }
    stringBuilder.append("]");
    argString = stringBuilder.toString();
    MessageContext messageContext = MessageContext.getCurrentMessageContext();
    if (messageContext != null) {
        Map headers = (Map) messageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        if (headers != null) {
            String correlationId = (String) headers.get(APIConstants.AM_ACTIVITY_ID);
            if (correlationId != null) {
                MDC.put(APIConstants.CORRELATION_ID, correlationId);
            }
        }
    }
    log.info((System.currentTimeMillis() - start) + "|METHOD|" +
            MethodSignature.class.cast(point.getSignature()).getDeclaringTypeName() + "|" +
            MethodSignature.class.cast(point.getSignature()).getMethod().getName()+ "|" + argString);
    return result;
}
 
Example 12
Source File: AbstractAdmin.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
protected HttpSession getHttpSession() {
    checkAdminService();
    MessageContext msgCtx = MessageContext.getCurrentMessageContext();
    HttpSession httpSession = null;
    if (msgCtx != null) {
        HttpServletRequest request =
                (HttpServletRequest) msgCtx.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
        httpSession = request.getSession();
    }
    return httpSession;
}
 
Example 13
Source File: AbstractAdmin.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
protected ConfigurationContext getConfigContext() {
    checkAdminService();
    if (configurationContext != null) {
        return configurationContext;
    }
    MessageContext msgContext = MessageContext.getCurrentMessageContext();
    if (msgContext != null) {
        ConfigurationContext mainConfigContext = msgContext.getConfigurationContext();

        return mainConfigContext;
    } else {
        return CarbonConfigurationContextFactory.getConfigurationContext();
    }
}
 
Example 14
Source File: DSSessionManager.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
/**
 * Save the given object in the session with the given name.
 */
private static void setSessionObject(String name, Object obj) {
	MessageContext messageContext = MessageContext.getCurrentMessageContext();
	if (messageContext != null) {
		ServiceContext serviceContext = messageContext.getServiceContext();
		if (serviceContext != null) {
			serviceContext.setProperty(name, obj);
		}			
	} else {
		threadLocalSession.get().put(name, obj);
	}
}
 
Example 15
Source File: DBUtils.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
public static String getCurrentContextUsername(DataService dataService) {
    MessageContext ctx = MessageContext.getCurrentMessageContext();
    if (ctx != null) {
        try {
            return dataService.getAuthorizationProvider().getUsername(ctx);
        } catch (DataServiceFault dataServiceFault) {
            return null;
        }
    } else {
        return null;
    }
}
 
Example 16
Source File: UserProfileAdmin.java    From carbon-identity-framework with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieve a claim of the authorized user.
 *
 * @param claimUri    Claim URI in wso2 dialect.
 * @param profileName User profile name.
 * @return Claim value.
 * @throws UserProfileException
 */
public String getUserClaim(String claimUri, String profileName) throws UserProfileException {

    if (StringUtils.isBlank(claimUri)) {
        throw new UserProfileException("Invalid input parameter. Claim URI cannot be null.");
    }
    if (StringUtils.isBlank(profileName)) {
        throw new UserProfileException("Invalid input parameter. Profile name cannot be null.");
    }
    String loggedInUsername = CarbonContext.getThreadLocalCarbonContext().getUsername();
    if (StringUtils.isBlank(loggedInUsername)) {
        throw new UserProfileException("Could not find a logged in user in the current carbon context.");
    }

    String claimValue = null;
    try {
        UserStoreManager userStoreManager = getUserRealm().getUserStoreManager();
        int index = loggedInUsername.indexOf(UserCoreConstants.DOMAIN_SEPARATOR);

        if (index < 0) {
            if (log.isDebugEnabled()) {
                log.debug("Logged in username : '" + loggedInUsername + "' does not contain domain name.");
            }
            /* if domain is not provided, this can be the scenario where user from a secondary user store
            logs in without domain name and tries to view his own profile. */
            MessageContext messageContext = MessageContext.getCurrentMessageContext();
            HttpServletRequest request = (HttpServletRequest) messageContext
                    .getProperty(TRANSPORT_HTTP_SERVLET_REQUEST);
            String domainName = (String) request.getSession().getAttribute(LOGGED_IN_DOMAIN);
            if (StringUtils.isNotBlank(domainName)) {
                loggedInUsername = domainName + UserCoreConstants.DOMAIN_SEPARATOR + loggedInUsername;
            }
        }
        index = loggedInUsername.indexOf(UserCoreConstants.DOMAIN_SEPARATOR);
        UserStoreManager secUserStoreManager = null;

        // Check whether we have a secondary UserStoreManager setup.
        if (index > 0) {
            // Using the short-circuit. User name comes with the domain name.
            String domain = loggedInUsername.substring(0, index);
            if (log.isDebugEnabled()) {
                log.debug("Domain name found in the logged in username. Domain name: " + domain);
            }
            if (userStoreManager instanceof AbstractUserStoreManager) {
                secUserStoreManager = ((AbstractUserStoreManager) userStoreManager)
                        .getSecondaryUserStoreManager(domain);
            }
        }
        Map<String, String> claimValues;
        if (secUserStoreManager != null) {
            claimValues = secUserStoreManager.getUserClaimValues(loggedInUsername, new String[]{claimUri},
                    profileName);
        } else {
            claimValues = userStoreManager.getUserClaimValues(loggedInUsername, new String[]{claimUri},
                    profileName);
        }
        if (claimValues != null) {
            claimValue = claimValues.get(claimUri);
        }
    } catch (UserStoreException e) {
        String message = String.format("An error occurred while getting the user claim '%s' in '%s' profile of " +
                "the user '%s'", claimUri, profileName, loggedInUsername);
        log.error(message, e);
        throw new UserProfileException(message, e);
    }
    return claimValue;
}
 
Example 17
Source File: XdsService.java    From openxds with Apache License 2.0 4 votes vote down vote up
public void useXop() {
	this.return_message_context = MessageContext.getCurrentMessageContext();
	if (return_message_context != null)
		return_message_context.getOptions().setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
}
 
Example 18
Source File: AppendixV.java    From openxds with Apache License 2.0 4 votes vote down vote up
public MessageContext getMessageContext() {
	return MessageContext.getCurrentMessageContext();
}
 
Example 19
Source File: OpenIDProviderService.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public OpenIDRememberMeDTO authenticateWithRememberMeCookie(String openID, String ipaddress, String cookie)
        throws Exception {
    String userName = OpenIDUtil.getUserName(openID);
    boolean isAutheticated = false;
    String hmac = null;
    OpenIDRememberMeDTO dto = new OpenIDRememberMeDTO();
    dto.setAuthenticated(false);

    if (cookie == null || "null".equals(cookie) || ipaddress == null) {
        return dto;
    }

    OpenIDRememberMeDO rememberMe = new OpenIDRememberMeDO();
    rememberMe.setOpenID(openID);
    rememberMe.setUserName(userName);

    OpenIDRememberMeTokenManager tokenManager = new OpenIDRememberMeTokenManager();
    String token = null;

    hmac = IdentityUtil.getHMAC(ipaddress, cookie);
    token = tokenManager.getToken(rememberMe);

    // if the authentication failed and no valid rememberMe cookie found, then failed.
    if (!isAutheticated && (token == null || !token.equals(hmac))) {
        return dto;
    }

    cookie = IdentityUtil.generateUUID();
    hmac = IdentityUtil.getHMAC(ipaddress, cookie);
    rememberMe.setToken(hmac);
    tokenManager.updateToken(rememberMe);
    dto.setNewCookieValue(cookie);
    dto.setAuthenticated(true);

    MessageContext msgContext = MessageContext.getCurrentMessageContext();

    if (msgContext != null) {
        HttpServletRequest request =
                (HttpServletRequest) msgContext.getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
        HttpSession httpSession = request.getSession(false);

        if (httpSession != null) {
            httpSession.setAttribute(OpenIDServerConstants.OPENID_LOGGEDIN_USER, userName);
        }
    }

    return dto;
}
 
Example 20
Source File: AttributeRequestProcessor.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
public ResponseToken process(RequestToken request) throws TrustException {

        MessageContext context = MessageContext.getCurrentMessageContext();
        SAMLPassiveTokenIssuer issuer = null;
        WSHandlerResult handlerResults = null;
        WSSecurityEngineResult engineResult = null;
        WSUsernameTokenPrincipal principal = null;
        Vector<WSSecurityEngineResult> wsResults = null;
        ResponseToken reponseToken = null;
        Vector<WSHandlerResult> handlerResultsVector = null;
        OMElement rstr = null;

        try {

            if (request.getAttributes() == null || request.getAttributes().trim().length() == 0) {
                throw new TrustException("attributesMissing");
            }

            principal = new WSUsernameTokenPrincipal(request.getUserName(), false);

            engineResult = new WSSecurityEngineResult(WSConstants.UT, principal, null, null, null);

            wsResults = new Vector<WSSecurityEngineResult>();
            wsResults.add(engineResult);

            handlerResults = new WSHandlerResult("", wsResults);

            handlerResultsVector = new Vector<WSHandlerResult>();
            handlerResultsVector.add(handlerResults);

            MessageContext.getCurrentMessageContext().setProperty(WSHandlerConstants.RECV_RESULTS,
                    handlerResultsVector);
            MessageContext.getCurrentMessageContext().setProperty(RahasConstants.PASSIVE_STS_RST,
                    getRST(request.getRealm(), request.getAttributes(), request.getDialect()));

            ConfigurationContext configurationContext = context.getConfigurationContext();
            configurationContext.setProperty(TokenStorage.TOKEN_STORAGE_KEY, PassiveSTSUtil.getTokenStorage());

            rahasData = new RahasData(context);
            issuer = new SAMLPassiveTokenIssuer();
            issuer.setAudienceRestrictionCondition(request.getRealm());
            issuer.setConfig(getSAMLTokenIssuerConfig(MessageContext.getCurrentMessageContext()
                    .getAxisService(), true));
            rstr = issuer.issuePassiveRSTR(rahasData);
            reponseToken = new ResponseToken();
            reponseToken.setResults(rstr.toStringWithConsume());

        } catch (Exception e) {
            throw new TrustException("errorWhileProcessingAttributeRequest", e);
        }

        return reponseToken;
    }