Example usage for org.springframework.security.authentication BadCredentialsException BadCredentialsException

List of usage examples for org.springframework.security.authentication BadCredentialsException BadCredentialsException

Introduction

In this page you can find the example usage for org.springframework.security.authentication BadCredentialsException BadCredentialsException.

Prototype

public BadCredentialsException(String msg) 

Source Link

Document

Constructs a BadCredentialsException with the specified message.

Usage

From source file:org.cloudfoundry.identity.uaa.error.JsonAwareAuthenticationEntryPointTests.java

@Test
public void testCommenceWithJson() throws Exception {
    request.addHeader("Accept", MediaType.APPLICATION_JSON_VALUE);
    entryPoint.commence(request, response, new BadCredentialsException("Bad"));
    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
    assertEquals("{\"error\":\"Bad\"}", response.getContentAsString());
    assertEquals(null, response.getErrorMessage());
}

From source file:grails.plugin.springsecurity.web.authentication.preauth.x509.ClosureX509PrincipalExtractor.java

public Object extractPrincipal(X509Certificate clientCert) {
    String subjectDN = clientCert.getSubjectDN().getName();

    log.debug("Subject DN is '{}'", subjectDN);

    Object username = closure.call(subjectDN);

    if (username == null) {
        throw new BadCredentialsException(messages.getMessage("SubjectDnX509PrincipalExtractor.noMatching",
                new Object[] { subjectDN }, "No matching pattern was found in subject DN: {}"));
    }//  w w w.  j a va  2  s  .co m

    log.debug("Extracted Principal name is '{}'", username);

    return username;
}

From source file:org.carewebframework.security.spring.mock.MockAuthenticationProvider.java

@Override
protected IUser authenticate(String username, String password, ISecurityDomain domain,
        CWFAuthenticationDetails details) {
    if (!check("mock.username", username) || !check("mock.password", password)) {
        throw new BadCredentialsException("Authentication failed.");
    }//w ww.  j  a  va2 s. c o m

    return new MockUser(SpringUtil.getProperty("mock.userid"), SpringUtil.getProperty("mock.fullname"),
            username, domain);
}

From source file:com.spfsolutions.ioms.auth.UserAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    try {//from   w  ww  .  j ava  2s  . c o m
        UserEntity userEntity = userDao.queryForFirst(
                userDao.queryBuilder().where().eq("Username", authentication.getName()).prepare());

        String inputHash = MD5.encrypt(authentication.getCredentials().toString());
        if (userEntity == null || !userEntity.getPassword().equals(inputHash)) {
            throw new BadCredentialsException("Username or password incorrect.");
        } else if (!userEntity.isEnabled()) {
            throw new DisabledException("The username is disabled. Please contact your System Administrator.");
        }
        userEntity.setLastSuccessfulLogon(new DateTime(DateTimeZone.UTC).toDate());

        userDao.createOrUpdate(userEntity);

        Collection<SimpleGrantedAuthority> authorities = buildRolesFromUser(userEntity);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                authentication.getName(), authentication.getCredentials(), authorities);

        return token;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        userDao.getConnectionSource().closeQuietly();
    }
    return null;

}

From source file:security.MyAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
    String username = String.valueOf(auth.getPrincipal());
    String password = String.valueOf(auth.getCredentials());

    // 1. Use the username to load the data for the user, including authorities and password.
    User user = (User) userRepository.findOneByUsername(username);

    if (user == null)
        throw new BadCredentialsException("Bad Credentials");

    String saltPassword = Hashing.sha512().hashString(password + user.getSalt(), Charsets.UTF_8).toString();
    System.out.println("Salted pass: " + saltPassword);
    // 2. Check the passwords match.
    if (!user.getPassword().equals(saltPassword)) {
        throw new BadCredentialsException("Bad Credentials");
    }//from www.ja  v a2  s.c o m

    // 3. Preferably clear the password in the user object before storing in authentication object
    //user.clearPassword();

    // 4. Return an authenticated token, containing user data and authorities  
    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("ROLE_USER"));

    Authentication token = new UsernamePasswordAuthenticationToken(user, saltPassword, authorities);
    return token;
}

From source file:md.ibanc.rm.sessions.CustomAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    String username = authentication.getName();
    String password = authentication.getCredentials().toString();

    LoginFormValidator loginFormValidator = new LoginFormValidator();

    if (!loginFormValidator.isLoginValid(username)) {
        throw new BadCredentialsException("Numele de utilizator contine simboluri interzise");
    }/*from ww  w.  j a  v a  2 s  . c  o m*/

    if (!loginFormValidator.isValidPassword(password)) {
        throw new BadCredentialsException("Parola contine simboluri interzise");
    }

    Users users = usersService.findUserByEmail(username);

    if (users == null) {
        throw new UsernameNotFoundException("Asa utilizator nu exista in baza de date");
    }

    String hashPassword = UtilHashMD5.createMD5Hash(FormatPassword.CreatePassword(users.getId(), password));

    if (!hashPassword.equals(users.getPassword())) {
        throw new BadCredentialsException("Parola este gresita");
    }

    if (!users.getActive()) {
        throw new AccountExpiredException("Nu aveti drept sa accesati acest serviciu");
    }

    Collection<? extends GrantedAuthority> authoritiesRoles = getAuthorities(users);

    return new UsernamePasswordAuthenticationToken(username, hashPassword, authoritiesRoles);

}

From source file:org.joyrest.oauth2.BasicAuthenticator.java

public Authentication authenticate(Request<?> request) {
    String header = request.getHeader("Authorization")
            .orElseThrow(() -> new BadCredentialsException("There is no Authorization header"));

    if (isNull(header) || !header.startsWith("Basic ")) {
        throw new BadCredentialsException("Failed to decode basic authentication token");
    }/*from  w w w  . j  a v  a 2  s  .c om*/

    try {
        String[] tokens = extractAndDecodeHeader(header);
        String username = tokens[0];

        logger.debug(() -> "Basic Authentication Authorization header found for user '" + username + "'");

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,
                tokens[1]);

        Authentication authentication = authenticationManager.authenticate(authRequest);
        logger.debug(() -> "Authentication success: " + authentication);
        return authentication;
    } catch (IOException ex) {
        throw new BadCredentialsException("Failed to decode basic authentication token");
    }
}

From source file:com.wisemapping.security.AuthenticationProvider.java

@Override()
public Authentication authenticate(@NotNull final Authentication auth) throws AuthenticationException {

    // All your user authentication needs
    final String email = auth.getName();

    final UserDetails userDetails = getUserDetailsService().loadUserByUsername(email);
    final User user = userDetails.getUser();
    final String credentials = (String) auth.getCredentials();
    if (user == null || credentials == null
            || !encoder.isPasswordValid(user.getPassword(), credentials, null)) {
        throw new BadCredentialsException("Username/Password does not match for " + auth.getPrincipal());
    }/*  w w w .j a  v a 2s . co m*/
    userDetailsService.getUserService().auditLogin(user);
    return new UsernamePasswordAuthenticationToken(userDetails, credentials, userDetails.getAuthorities());
}

From source file:com.hp.autonomy.frontend.configuration.authentication.IdolPreAuthenticatedAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final Object principal = authentication.getPrincipal();

    if (principal == null) {
        throw new BadCredentialsException("Principal not supplied");
    }/*from  ww w. ja  v a2s. c  o  m*/

    final String username = principal.toString().toLowerCase();

    final UserRoles user = userService.getUser(username, true);

    final Collection<SimpleGrantedAuthority> grantedAuthorities = preAuthenticatedRoles.stream()
            .map(SimpleGrantedAuthority::new).collect(Collectors.toSet());

    final CommunityPrincipal communityPrincipal = new CommunityPrincipal(user.getUid(), username,
            user.getSecurityInfo(), Collections.emptySet());
    final Collection<? extends GrantedAuthority> authorities = authoritiesMapper
            .mapAuthorities(grantedAuthorities);
    return new UsernamePasswordAuthenticationToken(communityPrincipal, null, authorities);
}