use of org.springframework.security.core.userdetails.UsernameNotFoundException in project spring-security by spring-projects.
the class PasswordComparisonAuthenticator method authenticate.
@Override
public DirContextOperations authenticate(final Authentication authentication) {
Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, "Can only process UsernamePasswordAuthenticationToken objects");
// locate the user and check the password
DirContextOperations user = null;
String username = authentication.getName();
String password = (String) authentication.getCredentials();
SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource());
for (String userDn : getUserDns(username)) {
try {
user = ldapTemplate.retrieveEntry(userDn, getUserAttributes());
} catch (NameNotFoundException ignore) {
logger.trace(LogMessage.format("Failed to retrieve user with %s", userDn), ignore);
}
if (user != null) {
break;
}
}
if (user == null) {
logger.debug(LogMessage.of(() -> "Failed to retrieve user with any user DNs " + getUserDns(username)));
}
if (user == null && getUserSearch() != null) {
logger.trace("Searching for user using " + getUserSearch());
user = getUserSearch().searchForUser(username);
if (user == null) {
logger.debug("Failed to find user using " + getUserSearch());
}
}
if (user == null) {
throw new UsernameNotFoundException("User not found: " + username);
}
if (logger.isTraceEnabled()) {
logger.trace(LogMessage.format("Comparing password attribute '%s' for user '%s'", this.passwordAttributeName, user.getDn()));
}
if (this.usePasswordAttrCompare && isPasswordAttrCompare(user, password)) {
logger.debug(LogMessage.format("Locally matched password attribute '%s' for user '%s'", this.passwordAttributeName, user.getDn()));
return user;
}
if (isLdapPasswordCompare(user, ldapTemplate, password)) {
logger.debug(LogMessage.format("LDAP-matched password attribute '%s' for user '%s'", this.passwordAttributeName, user.getDn()));
return user;
}
throw new BadCredentialsException(this.messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials"));
}
use of org.springframework.security.core.userdetails.UsernameNotFoundException in project spring-security by spring-projects.
the class DefaultAuthenticationEventPublisherTests method expectedDefaultMappingsAreSatisfied.
@Test
public void expectedDefaultMappingsAreSatisfied() {
this.publisher = new DefaultAuthenticationEventPublisher();
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
this.publisher.setApplicationEventPublisher(appPublisher);
Authentication a = mock(Authentication.class);
Exception cause = new Exception();
Object extraInfo = new Object();
this.publisher.publishAuthenticationFailure(new BadCredentialsException(""), a);
this.publisher.publishAuthenticationFailure(new BadCredentialsException("", cause), a);
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
reset(appPublisher);
this.publisher.publishAuthenticationFailure(new UsernameNotFoundException(""), a);
this.publisher.publishAuthenticationFailure(new UsernameNotFoundException("", cause), a);
this.publisher.publishAuthenticationFailure(new AccountExpiredException(""), a);
this.publisher.publishAuthenticationFailure(new AccountExpiredException("", cause), a);
this.publisher.publishAuthenticationFailure(new ProviderNotFoundException(""), a);
this.publisher.publishAuthenticationFailure(new DisabledException(""), a);
this.publisher.publishAuthenticationFailure(new DisabledException("", cause), a);
this.publisher.publishAuthenticationFailure(new LockedException(""), a);
this.publisher.publishAuthenticationFailure(new LockedException("", cause), a);
this.publisher.publishAuthenticationFailure(new AuthenticationServiceException(""), a);
this.publisher.publishAuthenticationFailure(new AuthenticationServiceException("", cause), a);
this.publisher.publishAuthenticationFailure(new CredentialsExpiredException(""), a);
this.publisher.publishAuthenticationFailure(new CredentialsExpiredException("", cause), a);
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureExpiredEvent.class));
verify(appPublisher).publishEvent(isA(AuthenticationFailureProviderNotFoundEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureLockedEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureServiceExceptionEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureCredentialsExpiredEvent.class));
verifyNoMoreInteractions(appPublisher);
}
use of org.springframework.security.core.userdetails.UsernameNotFoundException in project spring-security by spring-projects.
the class DigestAuthenticationFilter method doFilter.
private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Digest ")) {
chain.doFilter(request, response);
return;
}
logger.debug(LogMessage.format("Digest Authorization header received from user agent: %s", header));
DigestData digestAuth = new DigestData(header);
try {
digestAuth.validateAndDecode(this.authenticationEntryPoint.getKey(), this.authenticationEntryPoint.getRealmName());
} catch (BadCredentialsException ex) {
fail(request, response, ex);
return;
}
// Lookup password for presented username. N.B. DAO-provided password MUST be
// clear text - not encoded/salted (unless this instance's passwordAlreadyEncoded
// property is 'false')
boolean cacheWasUsed = true;
UserDetails user = this.userCache.getUserFromCache(digestAuth.getUsername());
String serverDigestMd5;
try {
if (user == null) {
cacheWasUsed = false;
user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername());
if (user == null) {
throw new AuthenticationServiceException("AuthenticationDao returned null, which is an interface contract violation");
}
this.userCache.putUserInCache(user);
}
serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
// If digest is incorrect, try refreshing from backend and recomputing
if (!serverDigestMd5.equals(digestAuth.getResponse()) && cacheWasUsed) {
logger.debug("Digest comparison failure; trying to refresh user from DAO in case password had changed");
user = this.userDetailsService.loadUserByUsername(digestAuth.getUsername());
this.userCache.putUserInCache(user);
serverDigestMd5 = digestAuth.calculateServerDigest(user.getPassword(), request.getMethod());
}
} catch (UsernameNotFoundException ex) {
String message = this.messages.getMessage("DigestAuthenticationFilter.usernameNotFound", new Object[] { digestAuth.getUsername() }, "Username {0} not found");
fail(request, response, new BadCredentialsException(message));
return;
}
// If digest is still incorrect, definitely reject authentication attempt
if (!serverDigestMd5.equals(digestAuth.getResponse())) {
logger.debug(LogMessage.format("Expected response: '%s' but received: '%s'; is AuthenticationDao returning clear text passwords?", serverDigestMd5, digestAuth.getResponse()));
String message = this.messages.getMessage("DigestAuthenticationFilter.incorrectResponse", "Incorrect response");
fail(request, response, new BadCredentialsException(message));
return;
}
// but the request was otherwise appearing to be valid
if (digestAuth.isNonceExpired()) {
String message = this.messages.getMessage("DigestAuthenticationFilter.nonceExpired", "Nonce has expired/timed out");
fail(request, response, new NonceExpiredException(message));
return;
}
logger.debug(LogMessage.format("Authentication success for user: '%s' with response: '%s'", digestAuth.getUsername(), digestAuth.getResponse()));
Authentication authentication = createSuccessfulAuthentication(request, user);
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
chain.doFilter(request, response);
}
use of org.springframework.security.core.userdetails.UsernameNotFoundException in project google-app-engine-jappstart by taylorleese.
the class UserDetailsServiceImpl method loadUserByUsername.
/**
* Locates the user based on the username.
*
* @param username string the username
* @return the user details
*/
@Override
public final UserDetails loadUserByUsername(final String username) {
final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
UserAccount user = (UserAccount) memcacheService.get(username);
if (user == null) {
final Query query = entityManager.createQuery("SELECT u FROM UserAccount u WHERE username = :username");
query.setParameter(USERNAME, username);
try {
user = (UserAccount) query.getSingleResult();
memcacheService.put(username, user, Expiration.byDeltaSeconds(DEFAULT_EXPIRATION));
} catch (NoResultException e) {
throw new UsernameNotFoundException("Username not found.", e);
}
}
authorities.add(new SimpleGrantedAuthority(user.getRole()));
return new EnhancedUser(user.getUsername(), user.getEmail(), user.getDisplayName(), user.getPassword(), user.getSalt(), user.isEnabled(), user.isAccountNonExpired(), user.isCredentialsNonExpired(), user.isAccountNonLocked(), authorities);
}
use of org.springframework.security.core.userdetails.UsernameNotFoundException in project google-app-engine-jappstart by taylorleese.
the class UserDetailsServiceImpl method activationEmailSent.
/**
* Updates the activation e-mail sent status.
*
* @param username the username
*/
@Override
@Transactional
public final void activationEmailSent(final String username) {
final Query query = entityManager.createQuery(SELECT_USER);
query.setParameter(USERNAME, username);
try {
final UserAccount user = (UserAccount) query.getSingleResult();
user.setActivationEmailSent(true);
entityManager.persist(user);
memcacheService.put(user.getUsername(), user, Expiration.byDeltaSeconds(DEFAULT_EXPIRATION));
} catch (NoResultException e) {
throw new UsernameNotFoundException("Username not found.", e);
}
}
Aggregations