Search in sources :

Example 6 with SecurityContext

use of com.haulmont.cuba.core.sys.SecurityContext 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 SecurityContext

use of com.haulmont.cuba.core.sys.SecurityContext 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 SecurityContext

use of com.haulmont.cuba.core.sys.SecurityContext 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 SecurityContext

use of com.haulmont.cuba.core.sys.SecurityContext 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 SecurityContext

use of com.haulmont.cuba.core.sys.SecurityContext 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

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