Search in sources :

Example 86 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project gocd by gocd.

the class BasicAuthHeaderExtractor method extractBasicAuthenticationCredentials.

public static UsernamePassword extractBasicAuthenticationCredentials(String authorizationHeader) {
    if (isBlank(authorizationHeader)) {
        return null;
    }
    final Matcher matcher = BASIC_AUTH_EXTRACTOR_PATTERN.matcher(authorizationHeader);
    if (matcher.matches()) {
        final String encodedCredentials = matcher.group(1);
        final byte[] decode = Base64.getDecoder().decode(encodedCredentials);
        String decodedCredentials = new String(decode, StandardCharsets.UTF_8);
        final int indexOfSeparator = decodedCredentials.indexOf(':');
        if (indexOfSeparator == -1) {
            throw new BadCredentialsException("Invalid basic authentication credentials specified in request.");
        }
        final String username = decodedCredentials.substring(0, indexOfSeparator);
        final String password = decodedCredentials.substring(indexOfSeparator + 1);
        return new UsernamePassword(username, password);
    }
    return null;
}
Also used : Matcher(java.util.regex.Matcher) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) UsernamePassword(com.thoughtworks.go.server.newsecurity.models.UsernamePassword)

Example 87 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project engine by craftercms.

the class ConfigAwareAuthenticationFailureHandlerTest method testProcessRequest.

@Test
public void testProcessRequest() throws Exception {
    HttpServletRequest request = RequestContext.getCurrent().getRequest();
    HttpServletResponse response = RequestContext.getCurrent().getResponse();
    handler.onAuthenticationFailure(request, response, new BadCredentialsException(""));
    assertEquals(config.getString(ConfigAwareAuthenticationFailureHandler.LOGIN_FAILURE_URL_KEY), ((MockHttpServletResponse) RequestContext.getCurrent().getResponse()).getRedirectedUrl());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Test(org.junit.Test)

Example 88 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project cas by apereo.

the class EndpointLdapAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    try {
        val username = authentication.getPrincipal().toString();
        val credentials = authentication.getCredentials();
        val password = Optional.ofNullable(credentials).map(Object::toString).orElse(null);
        if (StringUtils.isBlank(password)) {
            throw new IllegalArgumentException("Password cannot be blank");
        }
        LOGGER.debug("Preparing LDAP authentication request for user [{}]", username);
        val request = new AuthenticationRequest(username, new Credential(password), ReturnAttributes.ALL.value());
        LOGGER.debug("Executing LDAP authentication request for user [{}]", username);
        val response = this.authenticator.authenticate(request);
        LOGGER.debug("LDAP response: [{}]", response);
        if (response.isSuccess()) {
            val roles = securityProperties.getUser().getRoles();
            if (roles.isEmpty()) {
                LOGGER.info("No user security roles are defined to enable authorization. User [{}] is considered authorized", username);
                return generateAuthenticationToken(authentication, new ArrayList<>(0));
            }
            val entry = response.getLdapEntry();
            val profile = new CommonProfile();
            profile.setId(username);
            entry.getAttributes().forEach(a -> profile.addAttribute(a.getName(), a.getStringValues()));
            LOGGER.debug("Collected user profile [{}]", profile);
            val context = new JEEContext(HttpRequestUtils.getHttpServletRequestFromRequestAttributes(), HttpRequestUtils.getHttpServletResponseFromRequestAttributes());
            val authZGen = buildAuthorizationGenerator();
            authZGen.generate(context, JEESessionStore.INSTANCE, profile);
            LOGGER.debug("Assembled user profile with roles after generating authorization claims [{}]", profile);
            val authorities = profile.getRoles().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toCollection(ArrayList::new));
            LOGGER.debug("List of authorities remapped from profile roles are [{}]", authorities);
            val authorizer = new RequireAnyRoleAuthorizer(roles);
            LOGGER.debug("Executing authorization for expected admin roles [{}]", authorizer.getElements());
            if (authorizer.isAllAuthorized(context, JEESessionStore.INSTANCE, CollectionUtils.wrap(profile))) {
                return generateAuthenticationToken(authentication, authorities);
            }
            LOGGER.warn("User [{}] is not authorized to access the requested resource allowed to roles [{}]", username, authorizer.getElements());
        } else {
            LOGGER.warn("LDAP authentication response produced no results for [{}]", username);
        }
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
        throw new InsufficientAuthenticationException("Unexpected LDAP error", e);
    }
    throw new BadCredentialsException("Could not authenticate provided credentials");
}
Also used : lombok.val(lombok.val) Credential(org.ldaptive.Credential) CommonProfile(org.pac4j.core.profile.CommonProfile) JEEContext(org.pac4j.core.context.JEEContext) AuthenticationRequest(org.ldaptive.auth.AuthenticationRequest) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) RequireAnyRoleAuthorizer(org.pac4j.core.authorization.authorizer.RequireAnyRoleAuthorizer) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) AuthenticationException(org.springframework.security.core.AuthenticationException) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException)

Example 89 with BadCredentialsException

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

the class PhotoServiceImpl method getPhotosForCurrentUser.

public Collection<PhotoInfo> getPhotosForCurrentUser() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication.getPrincipal() instanceof UserDetails) {
        UserDetails details = (UserDetails) authentication.getPrincipal();
        String username = details.getUsername();
        ArrayList<PhotoInfo> infos = new ArrayList<PhotoInfo>();
        for (PhotoInfo info : getPhotos()) {
            if (username.equals(info.getUserId())) {
                infos.add(info);
            }
        }
        return infos;
    } else {
        throw new BadCredentialsException("Bad credentials: not a username/password authentication.");
    }
}
Also used : PhotoInfo(org.springframework.security.oauth.examples.sparklr.PhotoInfo) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) ArrayList(java.util.ArrayList) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 90 with BadCredentialsException

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

the class OAuth2ClientAuthenticationProcessingFilter method attemptAuthentication.

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
    OAuth2AccessToken accessToken;
    try {
        accessToken = restTemplate.getAccessToken();
    } catch (OAuth2Exception e) {
        BadCredentialsException bad = new BadCredentialsException("Could not obtain access token", e);
        publish(new OAuth2AuthenticationFailureEvent(bad));
        throw bad;
    }
    try {
        OAuth2Authentication result = tokenServices.loadAuthentication(accessToken.getValue());
        if (authenticationDetailsSource != null) {
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, accessToken.getValue());
            request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE, accessToken.getTokenType());
            result.setDetails(authenticationDetailsSource.buildDetails(request));
        }
        publish(new AuthenticationSuccessEvent(result));
        return result;
    } catch (InvalidTokenException e) {
        BadCredentialsException bad = new BadCredentialsException("Could not obtain user details from token", e);
        publish(new OAuth2AuthenticationFailureEvent(bad));
        throw bad;
    }
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) AuthenticationSuccessEvent(org.springframework.security.authentication.event.AuthenticationSuccessEvent) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Aggregations

BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)174 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)63 Authentication (org.springframework.security.core.Authentication)57 Test (org.junit.jupiter.api.Test)32 Test (org.junit.Test)26 AuthenticationException (org.springframework.security.core.AuthenticationException)24 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)22 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)21 UserDetails (org.springframework.security.core.userdetails.UserDetails)20 GrantedAuthority (org.springframework.security.core.GrantedAuthority)15 AuthenticationManager (org.springframework.security.authentication.AuthenticationManager)14 HttpServletRequest (javax.servlet.http.HttpServletRequest)13 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)13 AuthenticationServiceException (org.springframework.security.authentication.AuthenticationServiceException)12 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