Search in sources :

Example 31 with SecurityContext

use of com.haulmont.cuba.core.sys.SecurityContext in project cuba by cuba-platform.

the class LocalServiceInvokerImpl method invoke.

@Override
public LocalServiceInvocationResult invoke(LocalServiceInvocation invocation) {
    if (invocation == null) {
        throw new IllegalArgumentException("Invocation is null");
    }
    LocalServiceInvocationResult result = new LocalServiceInvocationResult();
    ClassLoader clientClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        ClassLoader classLoader = target.getClass().getClassLoader();
        Thread.currentThread().setContextClassLoader(classLoader);
        String[] parameterTypeNames = invocation.getParameterTypeNames();
        Class[] parameterTypes = new Class[parameterTypeNames.length];
        for (int i = 0; i < parameterTypeNames.length; i++) {
            Class<?> paramClass = ClassUtils.getClass(classLoader, parameterTypeNames[i]);
            parameterTypes[i] = paramClass;
        }
        byte[][] argumentsData = invocation.getArgumentsData();
        Object[] notSerializableArguments = invocation.getNotSerializableArguments();
        Object[] arguments;
        if (argumentsData == null) {
            arguments = null;
        } else {
            arguments = new Object[argumentsData.length];
            for (int i = 0; i < argumentsData.length; i++) {
                if (argumentsData[i] == null) {
                    if (notSerializableArguments[i] == null) {
                        arguments[i] = null;
                    } else {
                        arguments[i] = notSerializableArguments[i];
                    }
                } else {
                    arguments[i] = SerializationSupport.deserialize(argumentsData[i]);
                }
            }
        }
        SecurityContext targetSecurityContext = null;
        if (invocation.getSessionId() != null) {
            targetSecurityContext = new SecurityContext(invocation.getSessionId());
        }
        AppContext.setSecurityContext(targetSecurityContext);
        if (invocation.getLocale() != null) {
            Locale locale = Locale.forLanguageTag(invocation.getLocale());
            UserInvocationContext.setRequestScopeInfo(invocation.getSessionId(), locale, invocation.getTimeZone(), invocation.getAddress(), invocation.getClientInfo());
        }
        Method method = target.getClass().getMethod(invocation.getMethodName(), parameterTypes);
        Object data = method.invoke(target, arguments);
        if (invocation.canResultBypassSerialization()) {
            result.setNotSerializableData(data);
        } else {
            result.setData(SerializationSupport.serialize(data));
        }
        return result;
    } catch (Throwable t) {
        if (t instanceof InvocationTargetException)
            t = ((InvocationTargetException) t).getTargetException();
        result.setException(SerializationSupport.serialize(t));
        return result;
    } finally {
        Thread.currentThread().setContextClassLoader(clientClassLoader);
        AppContext.setSecurityContext(null);
        UserInvocationContext.clearRequestScopeInfo();
    }
}
Also used : Locale(java.util.Locale) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) SecurityContext(com.haulmont.cuba.core.sys.SecurityContext)

Example 32 with SecurityContext

use of com.haulmont.cuba.core.sys.SecurityContext in project cuba by cuba-platform.

the class ServerTokenStoreImpl method removeAccessTokenFromMemory.

protected void removeAccessTokenFromMemory(String tokenValue) {
    RestUserSessionInfo sessionInfo;
    lock.writeLock().lock();
    try {
        accessTokenValueToAccessTokenStore.remove(tokenValue);
        accessTokenValueToAuthenticationStore.remove(tokenValue);
        accessTokenValueToUserLoginStore.remove(tokenValue);
        String authenticationKey = accessTokenValueToAuthenticationKeyStore.remove(tokenValue);
        if (authenticationKey != null) {
            authenticationToAccessTokenStore.remove(authenticationKey);
        }
        sessionInfo = accessTokenValueToSessionInfoStore.remove(tokenValue);
    } finally {
        lock.writeLock().unlock();
    }
    if (sessionInfo != null) {
        try {
            UserSession session = userSessions.get(sessionInfo.getId());
            if (session != null) {
                AppContext.setSecurityContext(new SecurityContext(session));
                try {
                    authenticationManager.logout();
                } finally {
                    AppContext.setSecurityContext(null);
                }
            }
        } catch (NoUserSessionException ignored) {
        }
    }
}
Also used : UserSession(com.haulmont.cuba.security.global.UserSession) SecurityContext(com.haulmont.cuba.core.sys.SecurityContext) NoUserSessionException(com.haulmont.cuba.security.global.NoUserSessionException)

Example 33 with SecurityContext

use of com.haulmont.cuba.core.sys.SecurityContext in project cuba by cuba-platform.

the class Authentication method withUser.

/**
 * Execute code on behalf of the specified user.
 *
 * @param login     user login. If null, a value of {@code cuba.jmxUserLogin} app property is used.
 * @param operation code to execute
 * @return result of the execution
 */
public <T> T withUser(@Nullable String login, AuthenticatedOperation<T> operation) {
    SecurityContext previousSecurityContext = getSecurityContext();
    setSecurityContext(null);
    try {
        begin(login);
        return operation.call();
    } finally {
        setSecurityContext(previousSecurityContext);
    }
}
Also used : SecurityContext(com.haulmont.cuba.core.sys.SecurityContext) AppContext.getSecurityContext(com.haulmont.cuba.core.sys.AppContext.getSecurityContext) AppContext.setSecurityContext(com.haulmont.cuba.core.sys.AppContext.setSecurityContext)

Example 34 with SecurityContext

use of com.haulmont.cuba.core.sys.SecurityContext in project cuba by cuba-platform.

the class Authentication method begin.

/**
 * Begin an authenticated code block.
 * <br>
 * If a valid current thread session exists, does nothing.
 * Otherwise sets the current thread session, logging in if necessary.
 * <br>
 * Subsequent {@link #end()} method must be called in "finally" section.
 *
 * @param login user login. If null, a value of {@code cuba.jmxUserLogin} app property is used.
 * @return new or cached instance of system user session
 */
public UserSession begin(@Nullable String login) {
    if (cleanupCounter.get() == null) {
        cleanupCounter.set(0);
    }
    // check if a current thread session exists, that is we got here from authenticated code
    SecurityContext securityContext = AppContext.getSecurityContext();
    if (securityContext != null) {
        UserSession userSession = userSessions.getAndRefresh(securityContext.getSessionId());
        if (userSession != null) {
            log.trace("Already authenticated, do nothing");
            cleanupCounter.set(cleanupCounter.get() + 1);
            if (log.isTraceEnabled()) {
                log.trace("New cleanup counter value: {}", cleanupCounter.get());
            }
            return userSession;
        }
    }
    // no current thread session or it is expired - need to authenticate
    if (StringUtils.isBlank(login)) {
        login = getSystemLogin();
    }
    UserSession session = null;
    log.trace("Authenticating as {}", login);
    UUID sessionId = sessions.get(login);
    if (sessionId != null) {
        session = userSessions.getAndRefresh(sessionId);
    }
    if (session == null) {
        // saved session doesn't exist or is expired
        synchronized (this) {
            // double check to prevent the same log in by subsequent threads
            sessionId = sessions.get(login);
            if (sessionId != null) {
                session = userSessions.get(sessionId);
            }
            if (session == null) {
                try {
                    session = authenticationManager.login(new SystemUserCredentials(login)).getSession();
                    session.setClientInfo("System authentication");
                } catch (LoginException e) {
                    throw new RuntimeException("Unable to perform system login", e);
                }
                sessions.put(login, session.getId());
            }
        }
    }
    AppContext.setSecurityContext(new SecurityContext(session));
    return session;
}
Also used : SystemUserCredentials(com.haulmont.cuba.security.auth.SystemUserCredentials) UserSession(com.haulmont.cuba.security.global.UserSession) SecurityContext(com.haulmont.cuba.core.sys.SecurityContext) AppContext.getSecurityContext(com.haulmont.cuba.core.sys.AppContext.getSecurityContext) AppContext.setSecurityContext(com.haulmont.cuba.core.sys.AppContext.setSecurityContext) LoginException(com.haulmont.cuba.security.global.LoginException) UUID(java.util.UUID)

Example 35 with SecurityContext

use of com.haulmont.cuba.core.sys.SecurityContext in project cuba by cuba-platform.

the class LoginWorkerBean method getSystemSession.

@Override
public UserSession getSystemSession(String trustedClientPassword) throws LoginException {
    if (!trustedLoginHandler.checkPassword(trustedClientPassword)) {
        Locale locale = messages.getTools().getDefaultLocale();
        throw new LoginException(messages.formatMessage(MSG_PACK, "LoginException.InvalidLoginOrPassword", locale, serverConfig.getJmxUserLogin()));
    }
    SecurityContext currentSecContext = AppContext.getSecurityContext();
    UserSession userSession;
    try {
        // we need to reset security context to prevent reusing current session
        AppContext.setSecurityContext(null);
        userSession = authentication.begin();
        authentication.end();
    } finally {
        AppContext.setSecurityContext(currentSecContext);
    }
    return userSession;
}
Also used : Locale(java.util.Locale) UserSession(com.haulmont.cuba.security.global.UserSession) SecurityContext(com.haulmont.cuba.core.sys.SecurityContext) LoginException(com.haulmont.cuba.security.global.LoginException)

Aggregations

SecurityContext (com.haulmont.cuba.core.sys.SecurityContext)43 UserSession (com.haulmont.cuba.security.global.UserSession)29 LoginException (com.haulmont.cuba.security.global.LoginException)13 UUID (java.util.UUID)10 NoUserSessionException (com.haulmont.cuba.security.global.NoUserSessionException)8 IOException (java.io.IOException)8 FileStorageException (com.haulmont.cuba.core.global.FileStorageException)6 AppContext.withSecurityContext (com.haulmont.cuba.core.sys.AppContext.withSecurityContext)6 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)6 FileDescriptor (com.haulmont.cuba.core.entity.FileDescriptor)5 Locale (java.util.Locale)5 Transaction (com.haulmont.cuba.core.Transaction)3 AppContext.getSecurityContext (com.haulmont.cuba.core.sys.AppContext.getSecurityContext)3 AppContext.setSecurityContext (com.haulmont.cuba.core.sys.AppContext.setSecurityContext)3 TrustedClientCredentials (com.haulmont.cuba.security.auth.TrustedClientCredentials)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 Nonnull (javax.annotation.Nonnull)3 LogFileNotFoundException (com.haulmont.cuba.core.sys.logging.LogFileNotFoundException)2 LoginPasswordCredentials (com.haulmont.cuba.security.auth.LoginPasswordCredentials)2 SystemUserCredentials (com.haulmont.cuba.security.auth.SystemUserCredentials)2