Search in sources :

Example 6 with UserSession

use of com.haulmont.cuba.security.global.UserSession in project cuba by cuba-platform.

the class CubaAnonymousAuthenticationFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (restApiConfig.getRestAnonymousEnabled()) {
        if (SecurityContextHolder.getContext().getAuthentication() == null) {
            UserSession anonymousSession;
            try {
                anonymousSession = trustedClientService.getAnonymousSession(restApiConfig.getTrustedClientPassword());
            } catch (LoginException e) {
                throw new RuntimeException("Unable to obtain anonymous session for REST", e);
            }
            CubaAnonymousAuthenticationToken anonymousAuthenticationToken = new CubaAnonymousAuthenticationToken("anonymous", AuthorityUtils.createAuthorityList("ROLE_CUBA_ANONYMOUS"));
            SecurityContextHolder.getContext().setAuthentication(anonymousAuthenticationToken);
            AppContext.setSecurityContext(new SecurityContext(anonymousSession));
        } else {
            log.debug("SecurityContextHolder not populated with cuba anonymous token, as it already contained: '{}'", SecurityContextHolder.getContext().getAuthentication());
        }
    } else {
        log.trace("Anonymous access for CUBA REST API is disabled");
    }
    chain.doFilter(request, response);
}
Also used : UserSession(com.haulmont.cuba.security.global.UserSession) SecurityContext(com.haulmont.cuba.core.sys.SecurityContext) LoginException(com.haulmont.cuba.security.global.LoginException)

Example 7 with UserSession

use of com.haulmont.cuba.security.global.UserSession in project cuba by cuba-platform.

the class CubaUserAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    String ipAddress = request.getRemoteAddr();
    if (authentication instanceof UsernamePasswordAuthenticationToken) {
        RestApiConfig config = configuration.getConfig(RestApiConfig.class);
        if (!config.getStandardAuthenticationEnabled()) {
            log.debug("Standard authentication is disabled. Property cuba.rest.standardAuthenticationEnabled is false");
            throw new InvalidGrantException("Authentication disabled");
        }
        UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
        String login = (String) token.getPrincipal();
        UserSession session;
        try {
            String passwordHash = passwordEncryption.getPlainHash((String) token.getCredentials());
            LoginPasswordCredentials credentials = new LoginPasswordCredentials(login, passwordHash);
            credentials.setIpAddress(ipAddress);
            credentials.setClientType(ClientType.REST_API);
            credentials.setClientInfo(makeClientInfo(request.getHeader(HttpHeaders.USER_AGENT)));
            // if the locale value is explicitly passed in the Accept-Language header then set its value to the
            // credentials. Otherwise, the locale of the user should be used
            Locale locale = restAuthUtils.extractLocaleFromRequestHeader(request);
            if (locale != null) {
                credentials.setLocale(locale);
                credentials.setOverrideLocale(true);
            } else {
                credentials.setOverrideLocale(false);
            }
            session = authenticationService.login(credentials).getSession();
        } catch (AccountLockedException le) {
            log.info("Blocked user login attempt: login={}, ip={}", login, ipAddress);
            throw new LockedException("User temporarily blocked");
        } 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("REST API authentication failed: {} {}", login, ipAddress);
            throw new BadCredentialsException("Bad credentials");
        }
        AppContext.setSecurityContext(new SecurityContext(session));
        UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), getRoleUserAuthorities(authentication));
        @SuppressWarnings("unchecked") Map<String, String> details = (Map<String, String>) authentication.getDetails();
        details.put(SESSION_ID_DETAILS_ATTRIBUTE, session.getId().toString());
        result.setDetails(details);
        return result;
    }
    return null;
}
Also used : RestApiConfig(com.haulmont.restapi.config.RestApiConfig) Locale(java.util.Locale) AccountLockedException(com.haulmont.cuba.security.global.AccountLockedException) LockedException(org.springframework.security.authentication.LockedException) AccountLockedException(com.haulmont.cuba.security.global.AccountLockedException) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) LoginPasswordCredentials(com.haulmont.cuba.security.auth.LoginPasswordCredentials) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) InvalidGrantException(org.springframework.security.oauth2.common.exceptions.InvalidGrantException) 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) RestApiAccessDeniedException(com.haulmont.cuba.security.global.RestApiAccessDeniedException) Map(java.util.Map)

Example 8 with UserSession

use of com.haulmont.cuba.security.global.UserSession in project cuba by cuba-platform.

the class IdpSecurityContextInterceptor method preHandle.

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    // filter resource requests
    if (ClassUtils.isAssignableValue(ResourceHttpRequestHandler.class, handler)) {
        return true;
    }
    UserSession systemSession;
    try {
        systemSession = trustedClientService.getSystemSession(idpConfig.getTrustedClientPassword());
        AppContext.setSecurityContext(new SecurityContext(systemSession));
    } catch (LoginException e) {
        log.error("Unable to obtain system session", e);
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        return false;
    }
    return true;
}
Also used : UserSession(com.haulmont.cuba.security.global.UserSession) SecurityContext(com.haulmont.cuba.core.sys.SecurityContext) LoginException(com.haulmont.cuba.security.global.LoginException)

Example 9 with UserSession

use of com.haulmont.cuba.security.global.UserSession in project cuba by cuba-platform.

the class IdpSessionsWatchDog method cleanupExpiredSessions.

public void cleanupExpiredSessions() {
    if (!AppContext.isStarted()) {
        return;
    }
    List<String> serviceProviderUrls = idpConfig.getServiceProviderUrls();
    if (serviceProviderUrls.isEmpty()) {
        // there are no service providers registered
        return;
    }
    UserSession systemSession;
    try {
        systemSession = trustedClientService.getSystemSession(idpConfig.getTrustedClientPassword());
    } catch (LoginException e) {
        log.error("Unable to obtain system session", e);
        return;
    }
    AppContext.withSecurityContext(new SecurityContext(systemSession), () -> {
        List<String> loggedOutIdpSessionIds = idpService.processEviction(idpConfig.getSessionExpirationTimeoutSec(), idpConfig.getTicketExpirationTimeoutSec());
        for (String idpSessionId : loggedOutIdpSessionIds) {
            log.debug("IDP Session {} expired. Logout from service providers");
            logoutCallbackInvoker.performLogoutOnServiceProviders(idpSessionId);
        }
    });
}
Also used : UserSession(com.haulmont.cuba.security.global.UserSession) SecurityContext(com.haulmont.cuba.core.sys.SecurityContext) LoginException(com.haulmont.cuba.security.global.LoginException)

Example 10 with UserSession

use of com.haulmont.cuba.security.global.UserSession in project cuba by cuba-platform.

the class LogDownloadController method getSession.

protected UserSession getSession(String sessionId, HttpServletResponse response) throws IOException {
    UUID sessionUUID;
    try {
        sessionUUID = UUID.fromString(sessionId);
    } catch (Exception e) {
        log.error("Error parsing sessionId from URL param", e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return null;
    }
    AppContext.setSecurityContext(new SecurityContext(sessionUUID));
    try {
        UserSession session = userSessionService.getUserSession(sessionUUID);
        if (session == null)
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return session;
    } finally {
        AppContext.setSecurityContext(null);
    }
}
Also used : UserSession(com.haulmont.cuba.security.global.UserSession) SecurityContext(com.haulmont.cuba.core.sys.SecurityContext) UUID(java.util.UUID) LogFileNotFoundException(com.haulmont.cuba.core.sys.logging.LogFileNotFoundException) IOException(java.io.IOException)

Aggregations

UserSession (com.haulmont.cuba.security.global.UserSession)127 SecurityContext (com.haulmont.cuba.core.sys.SecurityContext)29 LoginWorker (com.haulmont.cuba.security.app.LoginWorker)25 TestUserSessionSource (com.haulmont.cuba.testsupport.TestUserSessionSource)24 LoginException (com.haulmont.cuba.security.global.LoginException)23 Test (org.junit.Test)19 User (com.haulmont.cuba.security.entity.User)17 UUID (java.util.UUID)16 IOException (java.io.IOException)14 NoUserSessionException (com.haulmont.cuba.security.global.NoUserSessionException)12 ArrayList (java.util.ArrayList)11 Locale (java.util.Locale)11 List (java.util.List)10 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)9 FileStorageException (com.haulmont.cuba.core.global.FileStorageException)7 LogFileNotFoundException (com.haulmont.cuba.core.sys.logging.LogFileNotFoundException)6 UserSessionSource (com.haulmont.cuba.core.global.UserSessionSource)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 ServletRequestAttributes (org.springframework.web.context.request.ServletRequestAttributes)5 FileDescriptor (com.haulmont.cuba.core.entity.FileDescriptor)4