use of org.springframework.security.core.userdetails.UsernameNotFoundException in project spring-security-oauth by spring-projects.
the class ClientDetailsUserDetailsService method loadUserByUsername.
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
ClientDetails clientDetails;
try {
clientDetails = clientDetailsService.loadClientByClientId(username);
} catch (NoSuchClientException e) {
throw new UsernameNotFoundException(e.getMessage(), e);
}
String clientSecret = clientDetails.getClientSecret();
if (clientSecret == null || clientSecret.trim().length() == 0) {
clientSecret = emptyPassword;
}
return new User(username, clientSecret, clientDetails.getAuthorities());
}
use of org.springframework.security.core.userdetails.UsernameNotFoundException in project spring-security by spring-projects.
the class PasswordComparisonAuthenticatorTests method testFailedSearchGivesUserNotFoundException.
@Test
public void testFailedSearchGivesUserNotFoundException() throws Exception {
authenticator = new PasswordComparisonAuthenticator(getContextSource());
assertThat(authenticator.getUserDns("Bob")).withFailMessage("User DN matches shouldn't be available").isEmpty();
authenticator.setUserSearch(new MockUserSearch(null));
authenticator.afterPropertiesSet();
try {
authenticator.authenticate(new UsernamePasswordAuthenticationToken("Joe", "pass"));
fail("Expected exception on failed user search");
} catch (UsernameNotFoundException expected) {
}
}
use of org.springframework.security.core.userdetails.UsernameNotFoundException in project spring-security by spring-projects.
the class DigestAuthenticationFilter method doFilter.
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Digest ")) {
chain.doFilter(request, response);
return;
}
if (logger.isDebugEnabled()) {
logger.debug("Digest Authorization header received from user agent: " + header);
}
DigestData digestAuth = new DigestData(header);
try {
digestAuth.validateAndDecode(this.authenticationEntryPoint.getKey(), this.authenticationEntryPoint.getRealmName());
} catch (BadCredentialsException e) {
fail(request, response, e);
return;
}
// Lookup password for presented username
// NB: 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) {
if (logger.isDebugEnabled()) {
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 notFound) {
fail(request, response, new BadCredentialsException(this.messages.getMessage("DigestAuthenticationFilter.usernameNotFound", new Object[] { digestAuth.getUsername() }, "Username {0} not found")));
return;
}
// If digest is still incorrect, definitely reject authentication attempt
if (!serverDigestMd5.equals(digestAuth.getResponse())) {
if (logger.isDebugEnabled()) {
logger.debug("Expected response: '" + serverDigestMd5 + "' but received: '" + digestAuth.getResponse() + "'; is AuthenticationDao returning clear text passwords?");
}
fail(request, response, new BadCredentialsException(this.messages.getMessage("DigestAuthenticationFilter.incorrectResponse", "Incorrect response")));
return;
}
// but the request was otherwise appearing to be valid
if (digestAuth.isNonceExpired()) {
fail(request, response, new NonceExpiredException(this.messages.getMessage("DigestAuthenticationFilter.nonceExpired", "Nonce has expired/timed out")));
return;
}
if (logger.isDebugEnabled()) {
logger.debug("Authentication success for user: '" + digestAuth.getUsername() + "' with response: '" + 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 opennms by OpenNMS.
the class OpenNMSUserDetailsServiceTest method testGetUnknownUser.
public void testGetUnknownUser() {
SpringSecurityUserDao userDao = createMock(SpringSecurityUserDao.class);
OpenNMSUserDetailsService detailsService = new OpenNMSUserDetailsService();
detailsService.setUserDao(userDao);
expect(userDao.getByUsername("test_user")).andReturn(null);
replay(userDao);
ThrowableAnticipator ta = new ThrowableAnticipator();
ta.anticipate(new UsernameNotFoundException("Unable to locate test_user in the userDao"));
try {
detailsService.loadUserByUsername("test_user");
} catch (Throwable t) {
ta.throwableReceived(t);
}
verify(userDao);
ta.verifyAnticipated();
}
use of org.springframework.security.core.userdetails.UsernameNotFoundException in project midpoint by Evolveum.
the class MidpointRestAuthenticator method handleRequest.
public void handleRequest(AuthorizationPolicy policy, Message m, ContainerRequestContext requestCtx) {
if (policy == null) {
RestServiceUtil.createAbortMessage(requestCtx);
return;
}
T authenticationContext = createAuthenticationContext(policy, requestCtx);
if (authenticationContext == null) {
return;
}
String enteredUsername = authenticationContext.getUsername();
if (enteredUsername == null) {
RestServiceUtil.createAbortMessage(requestCtx);
return;
}
LOGGER.trace("Authenticating username '{}' to REST service", enteredUsername);
// We need to create task before attempting authentication. Task ID is also a session ID.
Task task = taskManager.createTaskInstance(ModelRestService.OPERATION_REST_SERVICE);
task.setChannel(SchemaConstants.CHANNEL_REST_URI);
ConnectionEnvironment connEnv = ConnectionEnvironment.create(SchemaConstants.CHANNEL_REST_URI);
connEnv.setSessionIdOverride(task.getTaskIdentifier());
UsernamePasswordAuthenticationToken token;
try {
token = getAuthenticationEvaluator().authenticate(connEnv, authenticationContext);
} catch (UsernameNotFoundException | BadCredentialsException e) {
LOGGER.trace("Exception while authenticating username '{}' to REST service: {}", enteredUsername, e.getMessage(), e);
requestCtx.abortWith(Response.status(Status.UNAUTHORIZED).header("WWW-Authenticate", "Basic authentication failed. Cannot authenticate user.").build());
return;
} catch (DisabledException | LockedException | CredentialsExpiredException | AccessDeniedException | AuthenticationCredentialsNotFoundException | AuthenticationServiceException e) {
LOGGER.trace("Exception while authenticating username '{}' to REST service: {}", enteredUsername, e.getMessage(), e);
requestCtx.abortWith(Response.status(Status.FORBIDDEN).build());
return;
}
UserType user = ((MidPointPrincipal) token.getPrincipal()).getUser();
task.setOwner(user.asPrismObject());
// m.put(RestServiceUtil.MESSAGE_PROPERTY_TASK_NAME, task);
if (!authorizeUser(user, null, enteredUsername, connEnv, requestCtx)) {
return;
}
String oid = requestCtx.getHeaderString("Switch-To-Principal");
OperationResult result = task.getResult();
if (StringUtils.isNotBlank(oid)) {
try {
PrismObject<UserType> authorizedUser = model.getObject(UserType.class, oid, null, task, result);
task.setOwner(authorizedUser);
if (!authorizeUser(AuthorizationConstants.AUTZ_REST_PROXY_URL, user, authorizedUser, enteredUsername, connEnv, requestCtx)) {
return;
}
if (!authorizeUser(authorizedUser.asObjectable(), null, authorizedUser.getName().getOrig(), connEnv, requestCtx)) {
return;
}
} catch (ObjectNotFoundException | SchemaException | SecurityViolationException | CommunicationException | ConfigurationException | ExpressionEvaluationException e) {
LOGGER.trace("Exception while authenticating user identified with '{}' to REST service: {}", oid, e.getMessage(), e);
requestCtx.abortWith(Response.status(Status.UNAUTHORIZED).header("WWW-Authenticate", "Proxy Authentication failed. Cannot authenticate user.").build());
return;
}
}
m.put(RestServiceUtil.MESSAGE_PROPERTY_TASK_NAME, task);
LOGGER.trace("Authorized to use REST service ({})", user);
}
Aggregations