Search in sources :

Example 1 with RestApiAccessDeniedException

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

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

SecurityContext (com.haulmont.cuba.core.sys.SecurityContext)2 LoginException (com.haulmont.cuba.security.global.LoginException)2 RestApiAccessDeniedException (com.haulmont.cuba.security.global.RestApiAccessDeniedException)2 UserSession (com.haulmont.cuba.security.global.UserSession)2 RestApiConfig (com.haulmont.restapi.config.RestApiConfig)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)2 ServletRequestAttributes (org.springframework.web.context.request.ServletRequestAttributes)2 AppContext.withSecurityContext (com.haulmont.cuba.core.sys.AppContext.withSecurityContext)1 LoginPasswordCredentials (com.haulmont.cuba.security.auth.LoginPasswordCredentials)1 TrustedClientCredentials (com.haulmont.cuba.security.auth.TrustedClientCredentials)1 AccountLockedException (com.haulmont.cuba.security.global.AccountLockedException)1 Locale (java.util.Locale)1 Map (java.util.Map)1 LockedException (org.springframework.security.authentication.LockedException)1 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)1 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)1 InvalidGrantException (org.springframework.security.oauth2.common.exceptions.InvalidGrantException)1