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);
}
}
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));
}
}
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);
}
Aggregations