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:com.esquema.seguridad.AutenticacionPersonalizada.java

@Transactional
private s_user encuentra(String usuarioBD) {
    //jdbcTemplate.setDataSource(getSessionDataSource());

    s_user usuario = null;/* w  ww.  j a  va2 s .com*/

    try {
        // Hace uso de la conexion SQLServer, debido que es la conexion por defecto
        usuario = servicioUsuario.buscaPorUserlogin(usuarioBD);

        //DbContextHolder.setDbType(DbType.Oracle);
        //at04Control = at04ControlService.buscaPorCartera("AGRICOLA");
        /*
        s_user usuario = (s_user) jdbcTemplate.queryForObject(
        "select userlogin, passwd, enabled from s_user where userlogin = ?"
        ,new Object[] { usuarioBD }
        ,new BeanPropertyRowMapper(s_user.class));
        */
        return usuario;

    } catch (org.springframework.dao.EmptyResultDataAccessException e) {
        throw new BadCredentialsException("Usuario no existe");
    } finally {
        DbContextHolder.clearDbType();
    }

    /*new RowMapper<s_user>() {
    public s_user mapRow(ResultSet rs, int rowNum) throws SQLException {
        s_user usuario = new s_user();
        usuario.setUserlogin(rs.getString("userlogin"));
        usuario.setPasswd(rs.getString("passwd"));
        return usuario;
    }
    });*/

}

From source file:com.blstream.patronage.ctf.security.RestAuthenticationProvider.java

@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    Object salt = saltSource.getSalt(userDetails);

    if (authentication.getCredentials() == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("Authentication failed: no credentials provided");
        }// w w  w  . j  av a  2s. c  o  m
        throw new BadCredentialsException("Authentication failed: no credentials provided");
    }

    String presentedPassword = authentication.getCredentials().toString();

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("User %s credentials provided: %s, userDetails credentials: %s, salt: %s",
                userDetails.getUsername(), presentedPassword, userDetails.getPassword(), salt));
    }

    // TODO: make user's password encrypted!
    // if (!passwordEncoder.isPasswordValid(userDetails.getPassword(), presentedPassword, salt)) {
    if (!userDetails.getPassword().equals(presentedPassword)) {
        if (logger.isWarnEnabled()) {
            logger.warn("Authentication failed: password does not match stored value");
        }
        throw new BadCredentialsException("Authentication failed: password does not match stored value");
    }

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("User: %s authenticated successfully.", userDetails.getUsername()));
    }
}

From source file:com.erudika.para.security.PasswordAuthFilter.java

/**
 * Handles an authentication request./*from  w w w  . j a v a 2s  .c om*/
 * @param request HTTP request
 * @param response HTTP response
 * @return an authentication object that contains the principal object if successful.
 * @throws IOException ex
 * @throws ServletException ex
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String requestURI = request.getRequestURI();
    Authentication userAuth = null;
    User user = new User();

    if (requestURI.endsWith(PASSWORD_ACTION)) {
        user.setIdentifier(request.getParameter(EMAIL));
        user.setPassword(request.getParameter(PASSWORD));

        if (User.passwordMatches(user) && StringUtils.contains(user.getIdentifier(), "@")) {
            //success!
            user = User.readUserForIdentifier(user);
            userAuth = new UserAuthentication(new AuthenticatedUserDetails(user));
        }
    }

    if (userAuth == null || user == null || user.getIdentifier() == null) {
        throw new BadCredentialsException("Bad credentials.");
    } else if (!user.getActive()) {
        throw new LockedException("Account is locked.");
        //      } else {
        //         SecurityUtils.setAuthCookie(user, request, response);
    }
    return userAuth;
}

From source file:binky.reportrunner.service.impl.AuthenticationServiceImpl.java

public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    logger.info("authenticate service invoked");

    if (StringUtils.isBlank((String) authentication.getPrincipal())
            || StringUtils.isBlank((String) authentication.getCredentials())) {
        logger.debug("userName blank is " + StringUtils.isBlank((String) authentication.getPrincipal()
                + " password blank is " + StringUtils.isBlank((String) authentication.getCredentials())));
        throw new BadCredentialsException("Invalid username/password");

    }/* w w w  . j av  a 2  s. c  o  m*/

    String userName = (String) authentication.getPrincipal();
    String password = (String) authentication.getCredentials();

    RunnerUser user = userDao.get(userName);

    EncryptionUtil enc = new EncryptionUtil();

    List<GrantedAuthority> authorities = new LinkedList<GrantedAuthority>();
    try {
        if (user != null && user.getPassword().equals(enc.hashString(password))) {
            if (user.getIsAdmin()) {
                logger.info("admin login for user: " + userName);
                authorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
            } else {
                logger.info("user login for user: " + userName);
            }
            authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
        } else {
            logger.warn("login fail for user: " + userName);

            throw new BadCredentialsException("Invalid username/password");
        }
    } catch (Exception e) {

        logger.fatal(e.getMessage(), e);
        throw new AuthenticationServiceException(e.getMessage(), e);
    }

    return new UsernamePasswordAuthenticationToken(userName, authentication.getCredentials(), authorities);

}

From source file:net.maritimecloud.identityregistry.security.MCAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();
    logger.debug("In authenticate");
    // The login name is the org shortname
    // Organization org = this.organizationService.getOrganizationByShortName(name);
    // if an org was found, test the password
    // if (org != null && (new BCryptPasswordEncoder().matches(password, org.getPasswordHash()))) {
    if (!password.isEmpty()) {
        List<GrantedAuthority> grantedAuths = new ArrayList<>();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
        Authentication auth = new UsernamePasswordAuthenticationToken(name, authentication.getCredentials(),
                grantedAuths);/*  w  w  w. j a va  2  s  . c  om*/
        logger.debug("Got authenticated: " + auth.isAuthenticated());
        return auth;
    } else {
        logger.debug("Didn't get authenticated");
        throw new BadCredentialsException("Bad Credentials");
    }
}

From source file:org.ligoj.app.http.security.DigestAuthenticationFilter.java

@Override
public Authentication attemptAuthentication(final HttpServletRequest request,
        final HttpServletResponse response) {
    final String token = request.getParameter("token");

    if (token != null) {
        // Token is the last part of URL

        // First get the cookie
        final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
        clientBuilder.setDefaultRequestConfig(
                RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build());

        // Do the POST
        try (CloseableHttpClient httpClient = clientBuilder.build()) {
            final HttpPost httpPost = new HttpPost(getSsoPostUrl());
            httpPost.setEntity(new StringEntity(token, StandardCharsets.UTF_8.name()));
            httpPost.setHeader("Content-Type", "application/json");
            final HttpResponse httpResponse = httpClient.execute(httpPost);
            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(
                        EntityUtils.toString(httpResponse.getEntity()), "N/A", new ArrayList<>()));
            }/* ww  w  . j  a  v  a 2s. c o m*/
        } catch (final IOException e) {
            log.warn("Local SSO server is not available", e);
        }

    }
    throw new BadCredentialsException("Invalid user or password");
}

From source file:org.exoplatform.acceptance.security.CrowdAuthenticationProviderMock.java

/**
 * {@inheritDoc}//w ww. ja  v a2 s.co  m
 * Performs authentication with the same contract as {@link
 * org.springframework.security.authentication.AuthenticationManager#authenticate(Authentication)}.
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();
    try {
        UserDetails user = crowdUserDetailsServiceMock.loadUserByUsername(name);
        if (user.getPassword().equals(password)) {
            return new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(),
                    user.getAuthorities());
        } else {
            throw new BadCredentialsException("Invalid username or password");
        }
    } catch (UsernameNotFoundException unnfe) {
        throw new BadCredentialsException("Invalid username or password", unnfe);
    }
}

From source file:org.shredzone.cilla.ws.cxf.CillaRemoteAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!(authentication.getPrincipal() instanceof RemoteUserDetails)) {
        throw new InsufficientAuthenticationException(
                "authentication must contain a RemoteUserDetails principal");
    }/*w  w  w  .  j  av a  2  s  .  com*/

    try {
        RemoteUserDetails userDetails = (RemoteUserDetails) authentication.getPrincipal();

        List<GrantedAuthority> authorities = loginWs.authenticate().getRights().stream()
                .map(SimpleGrantedAuthority::new).collect(toList());

        userDetails.setAuthorities(authorities);
        userDetails.setUser(userWs.fetchByLogin(userDetails.getUsername()));

        return new UsernamePasswordAuthenticationToken(userDetails, null, authorities);
    } catch (SOAPFaultException ex) {
        throw new BadCredentialsException(ex.getMessage());
    } catch (CillaServiceException ex) {
        throw new AuthenticationServiceException("couldn't get user details", ex);
    }
}

From source file:com.mothsoft.alexis.service.security.AlexisApiAuthenticationProvider.java

@Override
protected UserDetails retrieveUser(final String username, final UsernamePasswordAuthenticationToken token)
        throws AuthenticationException {
    return this.transactionTemplate.execute(new TransactionCallback<UserDetails>() {

        @Override//  w  w w. j  a v  a2s . co  m
        public UserDetails doInTransaction(TransactionStatus arg0) {
            final String apiToken = String.valueOf(token.getCredentials());
            final boolean valid = AlexisApiAuthenticationProvider.this.userDao.authenticate(username, apiToken);

            if (!valid) {
                throw new BadCredentialsException(username);
            }

            final UserDetails userDetails = AlexisApiAuthenticationProvider.this.userDetailsService
                    .loadUserByUsername(username);
            final UserDetails toReturn = new UserAuthenticationDetails((UserAuthenticationDetails) userDetails,
                    apiToken);
            return toReturn;
        }
    });

}