Search in sources :

Example 6 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project ORCID-Source by ORCID.

the class OrcidWebOauth2TokenEndPointFilter method attemptAuthentication.

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    if (request.getMethod().equals(RequestMethod.GET.name())) {
        InvalidRequestException ire = new InvalidRequestException(localeManager.resolveMessage("apiError.token_request_callmethod.exception"));
        throw new MethodNotAllowedException(localeManager.resolveMessage("apiError.token_request_callmethod.exception"), ire);
    }
    String clientId = request.getParameter("client_id");
    String clientSecret = request.getParameter("client_secret");
    // If the request is already authenticated we can assume that this
    // filter is not needed
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null && authentication.isAuthenticated()) {
        return authentication;
    }
    if (clientId == null) {
        throw new BadCredentialsException(localeManager.resolveMessage("apiError.client_credentials.exception"));
    }
    if (clientSecret == null) {
        clientSecret = "";
    }
    clientId = clientId.trim();
    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId, clientSecret);
    return this.getAuthenticationManager().authenticate(authRequest);
}
Also used : MethodNotAllowedException(org.orcid.core.security.MethodNotAllowedException) Authentication(org.springframework.security.core.Authentication) InvalidRequestException(org.springframework.security.oauth2.common.exceptions.InvalidRequestException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 7 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project libresonic by Libresonic.

the class LibresonicUserDetailsContextMapper method mapUserFromContext.

// ~ Methods
// ========================================================================================================
public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) {
    String dn = ctx.getNameInNamespace();
    logger.debug("Mapping user details from context with DN: " + dn);
    // User must be defined in Libresonic, unless auto-shadowing is enabled.
    User user = securityService.getUserByName(username, false);
    if (user == null && !settingsService.isLdapAutoShadowing()) {
        throw new BadCredentialsException("User does not exist.");
    }
    if (user == null) {
        User newUser = new User(username, "", null, true, 0L, 0L, 0L);
        newUser.setStreamRole(true);
        newUser.setSettingsRole(true);
        securityService.createUser(newUser);
        logger.info("Created local user '" + username + "' for DN " + dn);
        user = securityService.getUserByName(username, false);
    }
    // LDAP authentication must be enabled for the given user.
    if (!user.isLdapAuthenticated()) {
        throw new BadCredentialsException("LDAP authentication disabled for user.");
    }
    LdapUserDetailsImpl.Essence essence = new LdapUserDetailsImpl.Essence();
    essence.setDn(dn);
    Object passwordValue = ctx.getObjectAttribute(passwordAttributeName);
    if (passwordValue != null) {
        essence.setPassword(mapPassword(passwordValue));
    }
    essence.setUsername(user.getUsername());
    // Add the supplied authorities
    for (GrantedAuthority authority : securityService.getGrantedAuthorities(user.getUsername())) {
        essence.addAuthority(authority);
    }
    // Check for PPolicy data
    PasswordPolicyResponseControl ppolicy = (PasswordPolicyResponseControl) ctx.getObjectAttribute(PasswordPolicyControl.OID);
    if (ppolicy != null) {
        essence.setTimeBeforeExpiration(ppolicy.getTimeBeforeExpiration());
        essence.setGraceLoginsRemaining(ppolicy.getGraceLoginsRemaining());
    }
    return essence.createUserDetails();
}
Also used : User(org.libresonic.player.domain.User) LdapUserDetailsImpl(org.springframework.security.ldap.userdetails.LdapUserDetailsImpl) GrantedAuthority(org.springframework.security.core.GrantedAuthority) PasswordPolicyResponseControl(org.springframework.security.ldap.ppolicy.PasswordPolicyResponseControl) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 8 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project spring-boot by spring-projects.

the class AuthenticationAuditListenerTests method testDetailsAreIncludedInAuditEvent.

@Test
public void testDetailsAreIncludedInAuditEvent() throws Exception {
    Object details = new Object();
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken("user", "password");
    authentication.setDetails(details);
    AuditApplicationEvent event = handleAuthenticationEvent(new AuthenticationFailureExpiredEvent(authentication, new BadCredentialsException("Bad user")));
    assertThat(event.getAuditEvent().getType()).isEqualTo(AuthenticationAuditListener.AUTHENTICATION_FAILURE);
    assertThat(event.getAuditEvent().getData()).containsEntry("details", details);
}
Also used : AuditApplicationEvent(org.springframework.boot.actuate.audit.listener.AuditApplicationEvent) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationFailureExpiredEvent(org.springframework.security.authentication.event.AuthenticationFailureExpiredEvent) Test(org.junit.Test)

Example 9 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project spring-security by spring-projects.

the class OpenIDAuthenticationProvider method authenticate.

/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.springframework.security.authentication.AuthenticationProvider#authenticate
	 * (org.springframework.security.Authentication)
	 */
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    if (!supports(authentication.getClass())) {
        return null;
    }
    if (authentication instanceof OpenIDAuthenticationToken) {
        OpenIDAuthenticationToken response = (OpenIDAuthenticationToken) authentication;
        OpenIDAuthenticationStatus status = response.getStatus();
        // handle the various possibilities
        if (status == OpenIDAuthenticationStatus.SUCCESS) {
            // Lookup user details
            UserDetails userDetails = this.userDetailsService.loadUserDetails(response);
            return createSuccessfulAuthentication(userDetails, response);
        } else if (status == OpenIDAuthenticationStatus.CANCELLED) {
            throw new AuthenticationCancelledException("Log in cancelled");
        } else if (status == OpenIDAuthenticationStatus.ERROR) {
            throw new AuthenticationServiceException("Error message from server: " + response.getMessage());
        } else if (status == OpenIDAuthenticationStatus.FAILURE) {
            throw new BadCredentialsException("Log in failed - identity could not be verified");
        } else if (status == OpenIDAuthenticationStatus.SETUP_NEEDED) {
            throw new AuthenticationServiceException("The server responded setup was needed, which shouldn't happen");
        } else {
            throw new AuthenticationServiceException("Unrecognized return value " + status.toString());
        }
    }
    return null;
}
Also used : UserDetails(org.springframework.security.core.userdetails.UserDetails) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException)

Example 10 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project spring-security by spring-projects.

the class LdapAuthenticationProviderTests method testEmptyOrNullUserNameThrowsException.

@Test
public void testEmptyOrNullUserNameThrowsException() {
    LdapAuthenticationProvider ldapProvider = new LdapAuthenticationProvider(new MockAuthenticator(), new MockAuthoritiesPopulator());
    try {
        ldapProvider.authenticate(new UsernamePasswordAuthenticationToken(null, "password"));
        fail("Expected BadCredentialsException for empty username");
    } catch (BadCredentialsException expected) {
    }
    try {
        ldapProvider.authenticate(new UsernamePasswordAuthenticationToken("", "bobspassword"));
        fail("Expected BadCredentialsException for null username");
    } catch (BadCredentialsException expected) {
    }
}
Also used : UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Test(org.junit.Test)

Aggregations

BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)170 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)63 Authentication (org.springframework.security.core.Authentication)57 Test (org.junit.jupiter.api.Test)29 Test (org.junit.Test)27 AuthenticationException (org.springframework.security.core.AuthenticationException)23 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)20 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)20 UserDetails (org.springframework.security.core.userdetails.UserDetails)20 GrantedAuthority (org.springframework.security.core.GrantedAuthority)15 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)14 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)13 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)12 HttpServletRequest (javax.servlet.http.HttpServletRequest)11 FilterChain (jakarta.servlet.FilterChain)10 IOException (java.io.IOException)10 ArrayList (java.util.ArrayList)10 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)10 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)9 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)7