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