use of org.springframework.security.authentication.BadCredentialsException 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 org.springframework.security.authentication.BadCredentialsException in project ranger by apache.
the class RangerAuthenticationProvider method getJDBCAuthentication.
private Authentication getJDBCAuthentication(Authentication authentication, String encoder) throws AuthenticationException {
try {
ReflectionSaltSource saltSource = new ReflectionSaltSource();
saltSource.setUserPropertyToUse("username");
DaoAuthenticationProvider authenticator = new DaoAuthenticationProvider();
authenticator.setUserDetailsService(userDetailsService);
if (encoder != null && "SHA256".equalsIgnoreCase(encoder)) {
authenticator.setPasswordEncoder(new ShaPasswordEncoder(256));
} else if (encoder != null && "MD5".equalsIgnoreCase(encoder)) {
authenticator.setPasswordEncoder(new Md5PasswordEncoder());
}
authenticator.setSaltSource(saltSource);
String userName = "";
String userPassword = "";
if (authentication != null) {
userName = authentication.getName();
if (authentication.getCredentials() != null) {
userPassword = authentication.getCredentials().toString();
}
}
String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER");
if (userName != null && userPassword != null && !userName.trim().isEmpty() && !userPassword.trim().isEmpty()) {
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole));
final UserDetails principal = new User(userName, userPassword, grantedAuths);
final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, userPassword, grantedAuths);
authentication = authenticator.authenticate(finalAuthentication);
return authentication;
} else {
if (authentication != null && !authentication.isAuthenticated()) {
throw new BadCredentialsException("Bad credentials");
}
}
} catch (BadCredentialsException e) {
throw e;
} catch (AuthenticationServiceException e) {
throw e;
} catch (AuthenticationException e) {
throw e;
} catch (Exception e) {
throw e;
}
return authentication;
}
use of org.springframework.security.authentication.BadCredentialsException in project service-authorization by reportportal.
the class ActiveDirectoryAuthProvider method getDelegate.
@Override
protected AuthenticationProvider getDelegate() {
ActiveDirectoryConfig adConfig = authConfigRepository.findActiveDirectory(true).orElseThrow(() -> new BadCredentialsException("Active Directory is not configured"));
ActiveDirectoryLdapAuthenticationProvider adAuth = new ActiveDirectoryLdapAuthenticationProvider(adConfig.getDomain(), adConfig.getUrl(), adConfig.getBaseDn());
adAuth.setAuthoritiesMapper(new NullAuthoritiesMapper());
adAuth.setUserDetailsContextMapper(new DetailsContextMapper(ldapUserReplicator, adConfig.getSynchronizationAttributes()));
return adAuth;
}
use of org.springframework.security.authentication.BadCredentialsException in project service-authorization by reportportal.
the class LdapAuthProvider method getDelegate.
@Override
protected AuthenticationProvider getDelegate() {
LdapConfig ldap = authConfigRepository.findLdap(true).orElseThrow(() -> new BadCredentialsException("LDAP is not configured"));
DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(singletonList(ldap.getUrl()), ldap.getBaseDn());
ofNullable(ldap.getManagerPassword()).ifPresent(contextSource::setPassword);
ofNullable(ldap.getManagerDn()).ifPresent(contextSource::setUserDn);
contextSource.afterPropertiesSet();
LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder> builder = new LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder>().contextSource(contextSource).ldapAuthoritiesPopulator(new NullLdapAuthoritiesPopulator()).userDetailsContextMapper(new DetailsContextMapper(ldapUserReplicator, ldap.getSynchronizationAttributes()));
/*
* Basically, groups are not used
*/
ofNullable(ldap.getGroupSearchFilter()).ifPresent(builder::groupSearchFilter);
ofNullable(ldap.getGroupSearchBase()).ifPresent(builder::groupSearchBase);
ofNullable(ldap.getUserSearchFilter()).ifPresent(builder::userSearchFilter);
ofNullable(ldap.getPasswordEncoderType()).ifPresent(it -> {
LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder>.PasswordCompareConfigurer passwordCompareConfigurer = builder.passwordCompare();
if (!isNullOrEmpty(ldap.getPasswordAttribute())) {
passwordCompareConfigurer.passwordAttribute(ldap.getPasswordAttribute());
}
/*
* DIRTY HACK. If LDAP's password has solt, ldaptemplate.compare operation does not work
* since we don't know server's salt.
* To enable local password comparison, we need to provide password encoder from crypto's package
* This is why we just wrap old encoder with new one interface
* New encoder cannot be used everywhere since it does not have implementation for LDAP
*/
final PasswordEncoder delegate = ENCODER_MAPPING.get(ldap.getPasswordEncoderType());
builder.passwordEncoder(new org.springframework.security.crypto.password.PasswordEncoder() {
@Override
public String encode(CharSequence rawPassword) {
return delegate.encodePassword(rawPassword.toString(), null);
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return delegate.isPasswordValid(encodedPassword, rawPassword.toString(), null);
}
});
});
if (!isNullOrEmpty(ldap.getUserDnPattern())) {
builder.userDnPatterns(ldap.getUserDnPattern());
}
try {
return (AuthenticationProvider) Accessible.on(builder).method(LdapAuthenticationProviderConfigurer.class.getDeclaredMethod("build")).invoke();
} catch (Throwable e) {
throw new ReportPortalException("Cannot build LDAP auth provider", e);
}
}
use of org.springframework.security.authentication.BadCredentialsException in project nifi by apache.
the class LdapProvider method authenticate.
@Override
public final AuthenticationResponse authenticate(final LoginCredentials credentials) throws InvalidLoginCredentialsException, IdentityAccessException {
if (provider == null) {
throw new IdentityAccessException("The LDAP authentication provider is not initialized.");
}
try {
// perform the authentication
final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword());
final Authentication authentication = provider.authenticate(token);
// use dn if configured
if (IdentityStrategy.USE_DN.equals(identityStrategy)) {
// attempt to get the ldap user details to get the DN
if (authentication.getPrincipal() instanceof LdapUserDetails) {
final LdapUserDetails userDetails = (LdapUserDetails) authentication.getPrincipal();
return new AuthenticationResponse(userDetails.getDn(), credentials.getUsername(), expiration, issuer);
} else {
logger.warn(String.format("Unable to determine user DN for %s, using username.", authentication.getName()));
return new AuthenticationResponse(authentication.getName(), credentials.getUsername(), expiration, issuer);
}
} else {
return new AuthenticationResponse(authentication.getName(), credentials.getUsername(), expiration, issuer);
}
} catch (final BadCredentialsException | UsernameNotFoundException | AuthenticationException e) {
throw new InvalidLoginCredentialsException(e.getMessage(), e);
} catch (final Exception e) {
// there appears to be a bug that generates a InternalAuthenticationServiceException wrapped around an AuthenticationException. this
// shouldn't be the case as they the service exception suggestions that something was wrong with the service. while the authentication
// exception suggests that username and/or credentials were incorrect. checking the cause seems to address this scenario.
final Throwable cause = e.getCause();
if (cause instanceof AuthenticationException) {
throw new InvalidLoginCredentialsException(e.getMessage(), e);
}
logger.error(e.getMessage());
if (logger.isDebugEnabled()) {
logger.debug(StringUtils.EMPTY, e);
}
throw new IdentityAccessException("Unable to validate the supplied credentials. Please contact the system administrator.", e);
}
}
Aggregations