Search in sources :

Example 66 with UsernameNotFoundException

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());
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) ClientDetails(org.springframework.security.oauth2.provider.ClientDetails) User(org.springframework.security.core.userdetails.User) NoSuchClientException(org.springframework.security.oauth2.provider.NoSuchClientException)

Example 67 with UsernameNotFoundException

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) {
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 68 with UsernameNotFoundException

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);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) HttpServletResponse(javax.servlet.http.HttpServletResponse) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) HttpServletRequest(javax.servlet.http.HttpServletRequest) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext)

Example 69 with UsernameNotFoundException

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();
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) ThrowableAnticipator(org.opennms.test.ThrowableAnticipator)

Example 70 with UsernameNotFoundException

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);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) Task(com.evolveum.midpoint.task.api.Task) AccessDeniedException(org.springframework.security.access.AccessDeniedException) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) SecurityViolationException(com.evolveum.midpoint.util.exception.SecurityViolationException) DisabledException(org.springframework.security.authentication.DisabledException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) ConfigurationException(com.evolveum.midpoint.util.exception.ConfigurationException) MidPointPrincipal(com.evolveum.midpoint.security.api.MidPointPrincipal) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) LockedException(org.springframework.security.authentication.LockedException) AuthenticationCredentialsNotFoundException(org.springframework.security.authentication.AuthenticationCredentialsNotFoundException) CredentialsExpiredException(org.springframework.security.authentication.CredentialsExpiredException) CommunicationException(com.evolveum.midpoint.util.exception.CommunicationException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) ConnectionEnvironment(com.evolveum.midpoint.security.api.ConnectionEnvironment) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) UserType(com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)

Aggregations

UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)132 GrantedAuthority (org.springframework.security.core.GrantedAuthority)40 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)39 UserDetails (org.springframework.security.core.userdetails.UserDetails)36 Authentication (org.springframework.security.core.Authentication)24 Transactional (org.springframework.transaction.annotation.Transactional)20 Logger (org.slf4j.Logger)18 LoggerFactory (org.slf4j.LoggerFactory)18 java.util (java.util)16 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)15 Collectors (java.util.stream.Collectors)14 UserDetailsService (org.springframework.security.core.userdetails.UserDetailsService)14 Component (org.springframework.stereotype.Component)14 User (org.springframework.security.core.userdetails.User)13 ArrayList (java.util.ArrayList)12 HashSet (java.util.HashSet)11 UserRepository (io.github.jhipster.sample.repository.UserRepository)9 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)9 User (io.github.jhipster.sample.domain.User)6 Date (java.util.Date)6