Search in sources :

Example 51 with BadCredentialsException

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

the class OAuth2TokenRelayFilterTests method unauthorizedWithRestTemplate.

@Test
public void unauthorizedWithRestTemplate() {
    OAuth2RestOperations restTemplate = Mockito.mock(OAuth2RestOperations.class);
    AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails();
    resource.setClientId("client");
    Mockito.when(restTemplate.getResource()).thenReturn(resource);
    Mockito.when(restTemplate.getAccessToken()).thenThrow(new RuntimeException());
    filter.setRestTemplate(restTemplate);
    assertNotNull(RequestContext.getCurrentContext());
    SecurityContextHolder.getContext().setAuthentication(auth);
    assertTrue(filter.shouldFilter());
    try {
        filter.run();
        fail("Expected BadCredentialsException");
    } catch (BadCredentialsException e) {
        assertEquals(401, RequestContext.getCurrentContext().get("error.status_code"));
    }
}
Also used : OAuth2RestOperations(org.springframework.security.oauth2.client.OAuth2RestOperations) AuthorizationCodeResourceDetails(org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) Test(org.junit.Test)

Example 52 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project credhub by cloudfoundry-incubator.

the class OAuth2ExtraValidationFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    Authentication authentication = tokenExtractor.extract(request);
    try {
        if (authentication != null) {
            String token = (String) authentication.getPrincipal();
            OAuth2AccessToken accessToken = tokenStore.readAccessToken(token);
            Map<String, Object> additionalInformation = accessToken.getAdditionalInformation();
            String issuer = (String) additionalInformation.getOrDefault("iss", "");
            if (!issuer.equals(oAuth2IssuerService.getIssuer())) {
                tokenStore.removeAccessToken(accessToken);
                String errorMessage = messageSourceAccessor.getMessage("error.oauth.invalid_issuer");
                throw new OAuth2Exception(errorMessage);
            // AuthenticationServiceException authException = new AuthenticationServiceException(errorMessage);
            // oAuth2AuthenticationExceptionHandler.commence(request, response, authException);
            }
        }
        filterChain.doFilter(request, response);
    } catch (OAuth2Exception exception) {
        SecurityContextHolder.clearContext();
        InsufficientAuthenticationException authException = new InsufficientAuthenticationException(exception.getMessage(), exception);
        eventPublisher.publishAuthenticationFailure(new BadCredentialsException(exception.getMessage(), exception), new PreAuthenticatedAuthenticationToken("access-token", "N/A"));
        oAuth2AuthenticationExceptionHandler.commence(request, response, authException);
    }
}
Also used : Authentication(org.springframework.security.core.Authentication) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) PreAuthenticatedAuthenticationToken(org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 53 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project ArTEMiS by ls1intum.

the class JiraAuthenticationProvider method getOrCreateUser.

/**
 * Gets or creates the user object for an JIRA user.
 *
 * @param authentication
 * @param skipPasswordCheck     Skip checking the password
 * @return
 */
@Override
public User getOrCreateUser(Authentication authentication, Boolean skipPasswordCheck) {
    String username = authentication.getName().toLowerCase();
    String password = authentication.getCredentials().toString();
    HttpEntity<Principal> entity = new HttpEntity<>(!skipPasswordCheck ? HeaderUtil.createAuthorization(username, password) : HeaderUtil.createAuthorization(JIRA_USER, JIRA_PASSWORD));
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<Map> authenticationResponse = null;
    try {
        authenticationResponse = restTemplate.exchange(JIRA_URL + "/rest/api/2/user?username=" + username + "&expand=groups", HttpMethod.GET, entity, Map.class);
    } catch (HttpStatusCodeException e) {
        if (e.getStatusCode().value() == 401) {
            throw new BadCredentialsException("Wrong credentials");
        } else if (e.getStatusCode().is5xxServerError()) {
            throw new ProviderNotFoundException("Could not authenticate via JIRA");
        }
    }
    if (authenticationResponse != null) {
        Map content = authenticationResponse.getBody();
        User user = userRepository.findOneByLogin((String) content.get("name")).orElseGet(() -> {
            return userService.createUser((String) content.get("name"), "", (String) content.get("displayName"), "", (String) content.get("emailAddress"), null, "en");
        });
        user.setGroups(getGroupStrings((ArrayList) ((Map) content.get("groups")).get("items")));
        user.setAuthorities(buildAuthoritiesFromGroups(getGroupStrings((ArrayList) ((Map) content.get("groups")).get("items"))));
        userRepository.save(user);
        if (!user.getActivated()) {
            userService.activateRegistration(user.getActivationKey());
        }
        Optional<User> matchingUser = userService.getUserWithAuthoritiesByLogin(username);
        if (matchingUser.isPresent()) {
            return matchingUser.get();
        } else {
            throw new UsernameNotFoundException("User " + username + " was not found in the " + "database");
        }
    } else {
        throw new InternalAuthenticationServiceException("JIRA Authentication failed for user " + username);
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) User(de.tum.in.www1.artemis.domain.User) InternalAuthenticationServiceException(org.springframework.security.authentication.InternalAuthenticationServiceException) HttpStatusCodeException(org.springframework.web.client.HttpStatusCodeException) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) ProviderNotFoundException(org.springframework.security.authentication.ProviderNotFoundException) RestTemplate(org.springframework.web.client.RestTemplate) Principal(java.security.Principal)

Example 54 with BadCredentialsException

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

the class LdapAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) {
    String login = authentication.getName();
    String password = authentication.getCredentials().toString();
    if (ldapUserDao.authenticate(login, password)) {
        List<? extends GrantedAuthority> emptyList = Lists.newArrayList();
        Authentication auth = new UsernamePasswordAuthenticationToken(login, password, emptyList);
        updateLdapUserRoles(login, auth);
        return auth;
    } else {
        log.debug("Wrong password for user <" + login + ">");
        throw new BadCredentialsException("Incorrect password for user <" + login + ">");
    }
}
Also used : Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

Example 55 with BadCredentialsException

use of org.springframework.security.authentication.BadCredentialsException in project atlas by apache.

the class AtlasFileAuthenticationProvider method authenticate.

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();
    if (username == null || username.isEmpty()) {
        logger.error("Username can't be null or empty.");
        throw new BadCredentialsException("Username can't be null or empty.");
    }
    if (password == null || password.isEmpty()) {
        logger.error("Password can't be null or empty.");
        throw new BadCredentialsException("Password can't be null or empty.");
    }
    UserDetails user = userDetailsService.loadUserByUsername(username);
    String encodedPassword = UserDao.getSha256Hash(password);
    if (!encodedPassword.equals(user.getPassword())) {
        logger.error("Wrong password " + username);
        throw new BadCredentialsException("Wrong password");
    }
    Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
    authentication = new UsernamePasswordAuthenticationToken(username, password, authorities);
    return authentication;
}
Also used : UserDetails(org.springframework.security.core.userdetails.UserDetails) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException)

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