Search in sources :

Example 1 with LoginException

use of com.haulmont.cuba.security.global.LoginException 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 LoginException

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

the class Authentication method begin.

/**
 * Begin authenticated block of code.
 *
 * @param sessionId {@link UserSession} id
 * @return true if the given session id is valid and authentication is successful
 */
public boolean begin(String sessionId) {
    UUID uuid;
    try {
        uuid = UuidProvider.fromString(sessionId);
    } catch (Exception e) {
        log.warn("Invalid user session ID: " + e.toString());
        return false;
    }
    UserSession session;
    try {
        session = trustedClientService.findSession(restApiConfig.getTrustedClientPassword(), uuid);
    } catch (LoginException e) {
        throw new RuntimeException("Unable to login with trusted client password");
    }
    if (session == null) {
        log.warn("User session " + uuid + " does not exist");
        return false;
    }
    if (!session.isSpecificPermitted(PERMISSION_NAME)) {
        log.warn(PERMISSION_NAME + " is not permitted for user " + session.getUser().getLogin());
        return false;
    }
    AppContext.setSecurityContext(new SecurityContext(session));
    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) UUID(java.util.UUID) LoginException(com.haulmont.cuba.security.global.LoginException)

Example 3 with LoginException

use of com.haulmont.cuba.security.global.LoginException 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 4 with LoginException

use of com.haulmont.cuba.security.global.LoginException 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 5 with LoginException

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

the class IdpController method authenticate.

@PostMapping(value = "/auth", produces = "application/json; charset=UTF-8")
@ResponseBody
public AuthResponse authenticate(@RequestBody AuthRequest auth, @CookieValue(value = CUBA_IDP_COOKIE_NAME, defaultValue = "") String idpSessionCookie, HttpServletResponse response) {
    String serviceProviderUrl = auth.getServiceProviderUrl();
    if (!Strings.isNullOrEmpty(serviceProviderUrl) && !isValidRedirectURL(serviceProviderUrl)) {
        log.warn("Incorrect serviceProviderUrl {} passed, will be used default", serviceProviderUrl);
        serviceProviderUrl = null;
    }
    if (Strings.isNullOrEmpty(serviceProviderUrl)) {
        if (!idpConfig.getServiceProviderUrls().isEmpty()) {
            serviceProviderUrl = idpConfig.getServiceProviderUrls().get(0);
        } else {
            log.error("IDP property cuba.idp.serviceProviderUrls is not set");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return null;
        }
    }
    Locale sessionLocale = null;
    if (globalConfig.getLocaleSelectVisible() && auth.getLocale() != null) {
        Map<String, Locale> availableLocales = globalConfig.getAvailableLocales();
        Locale requestedLocale = Locale.forLanguageTag(auth.getLocale());
        if (availableLocales.containsValue(requestedLocale)) {
            sessionLocale = requestedLocale;
        }
    }
    if (sessionLocale == null) {
        sessionLocale = messageTools.getDefaultLocale();
    }
    if (!Strings.isNullOrEmpty(idpSessionCookie)) {
        boolean loggedOut = idpService.logout(idpSessionCookie);
        if (loggedOut) {
            log.info("Logged out IDP session {}", idpSessionCookie);
            logoutCallbackInvoker.performLogoutOnServiceProviders(idpSessionCookie);
        }
    }
    IdpService.IdpLoginResult loginResult;
    try {
        loginResult = idpService.login(auth.getUsername(), passwordEncryption.getPlainHash(auth.getPassword()), sessionLocale, ImmutableMap.of(ClientType.class.getName(), ClientType.WEB.name()));
    } catch (LoginException e) {
        // remove auth cookie
        Cookie cookie = new Cookie(CUBA_IDP_COOKIE_NAME, "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        log.warn("Unable to login user {}", auth.getUsername());
        return AuthResponse.failed("invalid_credentials");
    }
    if (loginResult.getSessionId() != null) {
        Cookie idpCookie = new Cookie(CUBA_IDP_COOKIE_NAME, loginResult.getSessionId());
        idpCookie.setMaxAge(idpConfig.getIdpCookieMaxAge());
        idpCookie.setHttpOnly(idpConfig.getIdpCookieHttpOnly());
        response.addCookie(idpCookie);
    }
    String serviceProviderRedirectUrl;
    try {
        URIBuilder uriBuilder = new URIBuilder(serviceProviderUrl);
        if ("client-ticket".equals(auth.getResponseType())) {
            uriBuilder.setFragment(CUBA_IDP_TICKET_PARAMETER + "=" + loginResult.getServiceProviderTicket());
        } else {
            uriBuilder.setParameter(CUBA_IDP_TICKET_PARAMETER, loginResult.getServiceProviderTicket());
        }
        serviceProviderRedirectUrl = uriBuilder.build().toString();
    } catch (URISyntaxException e) {
        return AuthResponse.failed("invalid_params");
    }
    log.info("Logged in IDP session with ticket {}, user: {}", loginResult.getServiceProviderTicket(), auth.getUsername());
    return AuthResponse.authenticated(serviceProviderRedirectUrl);
}
Also used : Locale(java.util.Locale) Cookie(javax.servlet.http.Cookie) ClientType(com.haulmont.cuba.core.global.ClientType) LoginException(com.haulmont.cuba.security.global.LoginException) URISyntaxException(java.net.URISyntaxException) IdpService(com.haulmont.cuba.security.idp.IdpService) URIBuilder(org.apache.http.client.utils.URIBuilder)

Aggregations

LoginException (com.haulmont.cuba.security.global.LoginException)32 UserSession (com.haulmont.cuba.security.global.UserSession)22 Locale (java.util.Locale)14 SecurityContext (com.haulmont.cuba.core.sys.SecurityContext)13 User (com.haulmont.cuba.security.entity.User)5 TrustedClientCredentials (com.haulmont.cuba.security.auth.TrustedClientCredentials)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 ServletRequestAttributes (org.springframework.web.context.request.ServletRequestAttributes)4 ClientType (com.haulmont.cuba.core.global.ClientType)3 AbstractClientCredentials (com.haulmont.cuba.security.auth.AbstractClientCredentials)3 LoginPasswordCredentials (com.haulmont.cuba.security.auth.LoginPasswordCredentials)3 UUID (java.util.UUID)3 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)3 AppContext.withSecurityContext (com.haulmont.cuba.core.sys.AppContext.withSecurityContext)2 AuthenticationService (com.haulmont.cuba.security.auth.AuthenticationService)2 SimpleAuthenticationDetails (com.haulmont.cuba.security.auth.SimpleAuthenticationDetails)2 SystemUserCredentials (com.haulmont.cuba.security.auth.SystemUserCredentials)2 AccountLockedException (com.haulmont.cuba.security.global.AccountLockedException)2 InternalAuthenticationException (com.haulmont.cuba.security.global.InternalAuthenticationException)2 RestApiAccessDeniedException (com.haulmont.cuba.security.global.RestApiAccessDeniedException)2