Search in sources :

Example 1 with TrustedClientCredentials

use of com.haulmont.cuba.security.auth.TrustedClientCredentials in project cuba by cuba-platform.

the class AnonymousSessionHolder method loginAsAnonymous.

protected UserSession loginAsAnonymous() {
    String login = portalConfig.getAnonymousUserLogin();
    String password = portalConfig.getTrustedClientPassword();
    UserSession userSession;
    try {
        String portalLocationString = getPortalNetworkLocation();
        String portalClientInfo = "Portal Anonymous Session";
        if (StringUtils.isNotBlank(portalLocationString)) {
            portalClientInfo += " (" + portalLocationString + ")";
        }
        TrustedClientCredentials credentials = new TrustedClientCredentials(login, password, messagesTools.getDefaultLocale());
        credentials.setClientType(ClientType.PORTAL);
        credentials.setClientInfo(portalClientInfo);
        credentials.setParams(ParamsMap.of(ClientType.class.getName(), AppContext.getProperty("cuba.clientType"), SessionParams.CLIENT_INFO.getId(), portalClientInfo));
        userSession = authenticationService.login(credentials).getSession();
    } catch (LoginException e) {
        throw new NoMiddlewareConnectionException("Unable to login as anonymous portal user", e);
    } catch (Exception e) {
        throw new NoMiddlewareConnectionException("Unable to connect to middleware services", e);
    }
    return userSession;
}
Also used : NoMiddlewareConnectionException(com.haulmont.cuba.portal.sys.exceptions.NoMiddlewareConnectionException) UserSession(com.haulmont.cuba.security.global.UserSession) LoginException(com.haulmont.cuba.security.global.LoginException) TrustedClientCredentials(com.haulmont.cuba.security.auth.TrustedClientCredentials) NoMiddlewareConnectionException(com.haulmont.cuba.portal.sys.exceptions.NoMiddlewareConnectionException) LoginException(com.haulmont.cuba.security.global.LoginException) NoUserSessionException(com.haulmont.cuba.security.global.NoUserSessionException)

Example 2 with TrustedClientCredentials

use of com.haulmont.cuba.security.auth.TrustedClientCredentials in project cuba by cuba-platform.

the class ConfigStorageCommon method getConfigValue.

/**
 * Method returns a result of config method invocation
 * @param classFQN fully qualified configuration interface name
 * @param methodName config getter method name
 * @param userLogin parameter is used for authentication if there is no security context bound to the current thread
 *                  and configuration method source is DATABASE
 * @param userPassword see userLogin parameter description
 * @return configuration method invocation result
 */
public String getConfigValue(String classFQN, String methodName, String userLogin, String userPassword) {
    Class<?> aClass;
    try {
        aClass = Class.forName(classFQN);
    } catch (ClassNotFoundException e) {
        return String.format("Class %s not found.\nPlease ensure that you entered a fully qualified class name and " + "that you class is in a proper application module (core, web or portal).", classFQN);
    }
    if (Config.class.isAssignableFrom(aClass)) {
        Config config = configuration.getConfig((Class<? extends Config>) aClass);
        Method method;
        boolean logoutRequired = false;
        try {
            method = aClass.getMethod(methodName);
            // DATABASE, then login attempt with 'userLogin' and 'userPassword' will be made
            if (AppContext.getSecurityContext() == null) {
                SourceType sourceType;
                Source methodSourceAnnotation = method.getAnnotation(Source.class);
                if (methodSourceAnnotation != null) {
                    sourceType = methodSourceAnnotation.type();
                } else {
                    Source classSourceAnnotation = aClass.getAnnotation(Source.class);
                    sourceType = classSourceAnnotation.type();
                }
                if (sourceType != null && sourceType == SourceType.DATABASE) {
                    if (Strings.isNullOrEmpty(userLogin)) {
                        return "No security context bound to the current thread. Please specify the user name.";
                    } else {
                        try {
                            Map<String, Locale> availableLocales = configuration.getConfig(GlobalConfig.class).getAvailableLocales();
                            Locale defaultLocale = availableLocales.values().iterator().next();
                            TrustedClientCredentials credentials = new TrustedClientCredentials(userLogin, userPassword, defaultLocale);
                            UserSession session = authenticationService.login(credentials).getSession();
                            AppContext.setSecurityContext(new SecurityContext(session));
                            logoutRequired = true;
                        } catch (LoginException e) {
                            log.error(ExceptionUtils.getStackTrace(e));
                            return "Login error: " + e.getMessage();
                        }
                    }
                }
            }
            Object result = method.invoke(config);
            return result == null ? null : result.toString();
        } catch (NoSuchMethodException e) {
            return String.format("Method %s() not found in class %s", methodName, classFQN);
        } catch (InvocationTargetException | IllegalAccessException e) {
            return ExceptionUtils.getStackTrace(e);
        } finally {
            if (logoutRequired) {
                try {
                    authenticationService.logout();
                } finally {
                    AppContext.setSecurityContext(null);
                }
            }
        }
    } else {
        return String.format("Class %s is not an implementation of Config interface", classFQN);
    }
}
Also used : GlobalConfig(com.haulmont.cuba.core.global.GlobalConfig) GlobalConfig(com.haulmont.cuba.core.global.GlobalConfig) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) UserSession(com.haulmont.cuba.security.global.UserSession) SecurityContext(com.haulmont.cuba.core.sys.SecurityContext) LoginException(com.haulmont.cuba.security.global.LoginException) TrustedClientCredentials(com.haulmont.cuba.security.auth.TrustedClientCredentials)

Example 3 with TrustedClientCredentials

use of com.haulmont.cuba.security.auth.TrustedClientCredentials in project cuba by cuba-platform.

the class ExternalUserLoginProvider method login.

@Nullable
@Override
public AuthenticationDetails login(Credentials credentials) throws LoginException {
    ExternalUserCredentials externalUserCredentials = (ExternalUserCredentials) credentials;
    if (webAuthConfig.getStandardAuthenticationUsers().contains(externalUserCredentials.getLogin())) {
        log.debug("User {} is not allowed to use external login");
        return null;
    }
    TrustedClientCredentials tcCredentials = new TrustedClientCredentials(externalUserCredentials.getLogin(), webAuthConfig.getTrustedClientPassword(), externalUserCredentials.getLocale(), externalUserCredentials.getParams());
    tcCredentials.setClientInfo(externalUserCredentials.getClientInfo());
    tcCredentials.setClientType(ClientType.WEB);
    tcCredentials.setIpAddress(externalUserCredentials.getIpAddress());
    tcCredentials.setOverrideLocale(externalUserCredentials.isOverrideLocale());
    tcCredentials.setSyncNewUserSessionReplication(externalUserCredentials.isSyncNewUserSessionReplication());
    Map<String, Serializable> sessionAttributes = externalUserCredentials.getSessionAttributes();
    Map<String, Serializable> targetSessionAttributes;
    if (sessionAttributes != null && !sessionAttributes.isEmpty()) {
        targetSessionAttributes = new HashMap<>(sessionAttributes);
        targetSessionAttributes.put(EXTERNAL_AUTH_USER_SESSION_ATTRIBUTE, true);
    } else {
        targetSessionAttributes = ImmutableMap.of(EXTERNAL_AUTH_USER_SESSION_ATTRIBUTE, true);
    }
    tcCredentials.setSessionAttributes(targetSessionAttributes);
    return loginMiddleware(tcCredentials);
}
Also used : ExternalUserCredentials(com.haulmont.cuba.web.security.ExternalUserCredentials) Serializable(java.io.Serializable) TrustedClientCredentials(com.haulmont.cuba.security.auth.TrustedClientCredentials) Nullable(javax.annotation.Nullable)

Example 4 with TrustedClientCredentials

use of com.haulmont.cuba.security.auth.TrustedClientCredentials in project cuba by cuba-platform.

the class ClientProxyTokenStore method processSession.

/**
 * Tries to find the session associated with the given {@code authentication}. If the session id is in the store and
 * exists then it is set to the {@link SecurityContext}. If the session id is not in the store or the session with
 * the id doesn't exist in the middleware, then the trusted login attempt is performed.
 */
protected void processSession(OAuth2Authentication authentication, String tokenValue) {
    RestUserSessionInfo sessionInfo = serverTokenStore.getSessionInfoByTokenValue(tokenValue);
    UUID sessionId = sessionInfo != null ? sessionInfo.getId() : null;
    if (sessionId == null) {
        @SuppressWarnings("unchecked") Map<String, String> userAuthenticationDetails = (Map<String, String>) authentication.getUserAuthentication().getDetails();
        // sessionId parameter was put in the CubaUserAuthenticationProvider
        String sessionIdStr = userAuthenticationDetails.get("sessionId");
        if (!Strings.isNullOrEmpty(sessionIdStr)) {
            sessionId = UUID.fromString(sessionIdStr);
        }
    }
    UserSession session = null;
    if (sessionId != null) {
        try {
            session = trustedClientService.findSession(restApiConfig.getTrustedClientPassword(), sessionId);
        } catch (LoginException e) {
            throw new RuntimeException("Unable to login with trusted client password");
        }
    }
    if (session == null) {
        @SuppressWarnings("unchecked") Map<String, String> userAuthenticationDetails = (Map<String, String>) authentication.getUserAuthentication().getDetails();
        String username = userAuthenticationDetails.get("username");
        if (Strings.isNullOrEmpty(username)) {
            throw new IllegalStateException("Empty username extracted from user authentication details");
        }
        Locale locale = sessionInfo != null ? sessionInfo.getLocale() : null;
        TrustedClientCredentials credentials = new TrustedClientCredentials(username, restApiConfig.getTrustedClientPassword(), locale);
        credentials.setClientType(ClientType.REST_API);
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            credentials.setIpAddress(request.getRemoteAddr());
            credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT)));
        } else {
            credentials.setClientInfo(makeClientInfo(""));
        }
        // if locale was not determined then use the user locale
        if (locale == null) {
            credentials.setOverrideLocale(false);
        }
        try {
            session = authenticationService.login(credentials).getSession();
        } catch (LoginException e) {
            throw new OAuth2Exception("Cannot login to the middleware", e);
        }
        log.debug("New session created for token '{}' since the original session has been expired", tokenValue);
    }
    if (session != null) {
        serverTokenStore.putSessionInfo(tokenValue, new RestUserSessionInfo(session));
        AppContext.setSecurityContext(new SecurityContext(session));
    }
}
Also used : ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) HttpServletRequest(javax.servlet.http.HttpServletRequest) UserSession(com.haulmont.cuba.security.global.UserSession) SecurityContext(com.haulmont.cuba.core.sys.SecurityContext) LoginException(com.haulmont.cuba.security.global.LoginException) RestUserSessionInfo(com.haulmont.cuba.restapi.RestUserSessionInfo) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception) TrustedClientCredentials(com.haulmont.cuba.security.auth.TrustedClientCredentials)

Example 5 with TrustedClientCredentials

use of com.haulmont.cuba.security.auth.TrustedClientCredentials in project cuba by cuba-platform.

the class ExternalOAuthTokenGranter method issueToken.

@Override
public OAuth2AccessTokenResult issueToken(OAuth2AccessTokenRequest tokenRequest) {
    RestApiConfig config = configuration.getConfig(RestApiConfig.class);
    String login = tokenRequest.getLogin();
    Locale locale = tokenRequest.getLocale();
    Map<String, String> parameters = new HashMap<>();
    parameters.put("username", login);
    parameters.put("client_id", config.getRestClientId());
    parameters.put("scope", "rest-api");
    parameters.put("grant", GRANT_TYPE);
    UserSession session;
    try {
        TrustedClientCredentials credentials = new TrustedClientCredentials(login, config.getTrustedClientPassword(), locale);
        credentials.setClientType(ClientType.REST_API);
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            credentials.setIpAddress(request.getRemoteAddr());
            credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT)));
        } else {
            credentials.setClientInfo(makeClientInfo(""));
        }
        credentials.setParams(tokenRequest.getLoginParams());
        session = authenticationService.login(credentials).getSession();
    } catch (RestApiAccessDeniedException ex) {
        log.info("User is not allowed to use the REST API {}", login);
        throw new BadCredentialsException("User is not allowed to use the REST API");
    } catch (LoginException e) {
        log.info("Unable to issue token for REST API: {}", login);
        throw new BadCredentialsException("Bad credentials");
    }
    parameters.put(SESSION_ID_DETAILS_ATTRIBUTE, session.getId().toString());
    for (Map.Entry<String, String> tokenParam : tokenRequest.getTokenDetails().entrySet()) {
        parameters.put(EXTENDED_DETAILS_ATTRIBUTE_PREFIX + tokenParam.getKey(), tokenParam.getValue());
    }
    // issue token using obtained Session, it is required for DB operations inside of persistent token store
    OAuth2AccessToken accessToken = withSecurityContext(new SecurityContext(session), () -> {
        ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(config.getRestClientId());
        TokenRequest tr = getRequestFactory().createTokenRequest(parameters, authenticatedClient);
        return grant(GRANT_TYPE, tr);
    });
    return new OAuth2AccessTokenResult(session, accessToken);
}
Also used : RestApiConfig(com.haulmont.restapi.config.RestApiConfig) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) HttpServletRequest(javax.servlet.http.HttpServletRequest) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) UserSession(com.haulmont.cuba.security.global.UserSession) SecurityContext(com.haulmont.cuba.core.sys.SecurityContext) AppContext.withSecurityContext(com.haulmont.cuba.core.sys.AppContext.withSecurityContext) LoginException(com.haulmont.cuba.security.global.LoginException) RestApiAccessDeniedException(com.haulmont.cuba.security.global.RestApiAccessDeniedException) TrustedClientCredentials(com.haulmont.cuba.security.auth.TrustedClientCredentials)

Aggregations

TrustedClientCredentials (com.haulmont.cuba.security.auth.TrustedClientCredentials)5 LoginException (com.haulmont.cuba.security.global.LoginException)4 UserSession (com.haulmont.cuba.security.global.UserSession)4 SecurityContext (com.haulmont.cuba.core.sys.SecurityContext)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 ServletRequestAttributes (org.springframework.web.context.request.ServletRequestAttributes)2 GlobalConfig (com.haulmont.cuba.core.global.GlobalConfig)1 AppContext.withSecurityContext (com.haulmont.cuba.core.sys.AppContext.withSecurityContext)1 NoMiddlewareConnectionException (com.haulmont.cuba.portal.sys.exceptions.NoMiddlewareConnectionException)1 RestUserSessionInfo (com.haulmont.cuba.restapi.RestUserSessionInfo)1 NoUserSessionException (com.haulmont.cuba.security.global.NoUserSessionException)1 RestApiAccessDeniedException (com.haulmont.cuba.security.global.RestApiAccessDeniedException)1 ExternalUserCredentials (com.haulmont.cuba.web.security.ExternalUserCredentials)1 RestApiConfig (com.haulmont.restapi.config.RestApiConfig)1 Serializable (java.io.Serializable)1 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 Method (java.lang.reflect.Method)1 Nullable (javax.annotation.Nullable)1 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)1 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)1