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