Search in sources :

Example 41 with SecurityContext

use of com.haulmont.cuba.core.sys.SecurityContext in project cuba by cuba-platform.

the class LoginServiceController method doLogin.

protected void doLogin(String username, String password, String localeStr, HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException {
    Locale locale = localeFromString(localeStr);
    AuthenticationService authenticationService = AppBeans.get(AuthenticationService.NAME);
    try {
        AbstractClientCredentials credentials = new LoginPasswordCredentials(username, passwordEncryption.getPlainHash(password), locale);
        UserSession userSession = authenticationService.login(credentials).getSession();
        if (!userSession.isSpecificPermitted(Authentication.PERMISSION_NAME)) {
            log.info(String.format("User %s is not allowed to use REST-API", username));
            AppContext.setSecurityContext(new SecurityContext(userSession));
            try {
                authenticationService.logout();
            } finally {
                AppContext.setSecurityContext(null);
            }
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        try {
            AppContext.setSecurityContext(new SecurityContext(userSession));
            setSessionInfo(request, userSession);
        } finally {
            AppContext.setSecurityContext(null);
        }
        response.setStatus(HttpServletResponse.SC_OK);
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8));
        writer.write(userSession.getId().toString());
        writer.close();
        log.debug(String.format("User %s logged in with REST-API, session id: %s", username, userSession.getId()));
    } catch (LoginException e) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
}
Also used : Locale(java.util.Locale) UserSession(com.haulmont.cuba.security.global.UserSession) LoginPasswordCredentials(com.haulmont.cuba.security.auth.LoginPasswordCredentials) SecurityContext(com.haulmont.cuba.core.sys.SecurityContext) AbstractClientCredentials(com.haulmont.cuba.security.auth.AbstractClientCredentials) LoginException(com.haulmont.cuba.security.global.LoginException) OutputStreamWriter(java.io.OutputStreamWriter) AuthenticationService(com.haulmont.cuba.security.auth.AuthenticationService) PrintWriter(java.io.PrintWriter)

Example 42 with SecurityContext

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

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