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.atomsphere.management.authentication.UserDetailsServiceImpl.java

@Override
public UserDetails loadUserByUsername(String userName) throws AuthenticationException, DataAccessException {
    User user = null;/*from   ww w  .ja  v a 2 s  .co  m*/

    try {
        // Return member from DB and populate roles.
        user = (User) userService.getUserByUserName(userName);

        if (user == null) {
            if (logger.isDebugEnabled()) {
                logger.debug("User name " + userName + " is missing in database !!!");
            }
            throw new BadCredentialsException(MessageSourceUtils.getMessage(authenticationMessageSource,
                    AuthenticationMessages.class, AuthenticationMessages.AUTHENTICATION_FAILED.name()));
        }

        user.setAuthorities(AuthenticationUtils.toGrantedAuthority((User) user));

        logger.trace("User: " + user.getUsername() + " grantedAuthorities: " + user.getAuthorities());
    } catch (CannotCreateTransactionException e) {

        logger.error("No connection to the database. Exception: " + e.getMessage());
        if (logger.isDebugEnabled()) {
            logger.debug("No connection to the database. Exception: " + e.getMessage(), e);
        }

        throw new NoDBConnectionException("No connection to the database. Exception: ", e);
    }
    return user;
}

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

@Test
public void testCommenceWithHtmlAccept() throws Exception {
    request.addHeader("Accept", MediaType.TEXT_HTML_VALUE);
    entryPoint.commence(request, response, new BadCredentialsException("Bad"));
    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
    assertEquals("Bad", response.getErrorMessage());
}

From source file:oauth2.authentication.DefaultUserAuthenticationStrategy.java

@Override
public void authenticate(User user, Object credentials) {
    checkNotNull(user);// www  .j  a v a2s.  com

    String userId = user.getUserId();
    if (!user.isEnabled()) {
        LOGGER.debug("User {} is disabled", userId);
        throw new DisabledException(
                messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"));
    }
    if (user.isAccountLocked()) {
        LOGGER.debug("User account {} is locked", userId);
        throw new LockedException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked",
                "User account is locked"));
    }
    if (credentials == null) {
        LOGGER.debug("Authentication for user {} failed: No credentials provided", userId);
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
    if (!passwordEncoder.matches(credentials.toString(), user.getPassword())) {
        LOGGER.debug("Authentication for user {} failed: Password does not match stored value", userId);
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
}

From source file:nc.noumea.mairie.appock.core.security.MockAuthenticationProvider.java

@Override
protected UserDetails retrieveUser(String s,
        final UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken)
        throws AuthenticationException {

    try {// w w w. ja  v  a  2 s  . c om
        AppUser appUser = appUserService.findByLogin(usernamePasswordAuthenticationToken.getName());
        if (appUser == null || !appUser.isActif()) {
            throw new BadCredentialsException("Connection  l'application APPOCK impossible");
        }
    } catch (NoResultException e) {
        throw new BadCredentialsException("Connection  l'application APPOCK impossible");
    }

    user = new UserDetails() {
        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            return appockAuthoritiesPopulator.getGrantedAuthorities(null,
                    usernamePasswordAuthenticationToken.getName());
        }

        @Override
        public String getPassword() {
            return null;
        }

        @Override
        public String getUsername() {
            return usernamePasswordAuthenticationToken.getName();
        }

        @Override
        public boolean isAccountNonExpired() {
            return true;
        }

        @Override
        public boolean isAccountNonLocked() {
            return true;
        }

        @Override
        public boolean isCredentialsNonExpired() {
            return true;
        }

        @Override
        public boolean isEnabled() {
            return true;
        }
    };

    return user;
}

From source file:eu.openanalytics.rsb.security.X509AuthenticationFilter.java

@Override
protected Object getPreAuthenticatedPrincipal(final HttpServletRequest request) {
    final String clientDN = (String) getPreAuthenticatedCredentials(request);
    if (clientDN == null) {
        return null;
    }//from   ww w. j a  va2 s.c o m

    logger.debug("Client DN is '" + clientDN + "'");

    final Matcher matcher = subjectDnPattern.matcher(clientDN);

    if (!matcher.find()) {
        throw new BadCredentialsException("No matching pattern was found in client DN: " + clientDN);
    }

    if (matcher.groupCount() != 1) {
        throw new IllegalArgumentException("Regular expression must contain a single group ");
    }

    final String username = matcher.group(1);

    logger.debug("Extracted Principal name is '" + username + "'");

    return username;
}

From source file:com.mycompany.apps.oauth2.authentication.security.CustomUserAuthenticationProvider.java

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

    if (authentication.getPrincipal().equals("user") && authentication.getCredentials().equals("user")) {

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        CustomUserPasswordAuthenticationToken auth = new CustomUserPasswordAuthenticationToken(
                authentication.getPrincipal(), authentication.getCredentials(), grantedAuthorities);

        return auth;

    } else if (authentication.getPrincipal().equals("admin")
            && authentication.getCredentials().equals("admin")) {

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        CustomUserPasswordAuthenticationToken auth = new CustomUserPasswordAuthenticationToken(
                authentication.getPrincipal(), authentication.getCredentials(), grantedAuthorities);

        return auth;

    } else if (authentication.getPrincipal().equals("user1")
            && authentication.getCredentials().equals("user1")) {

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        CustomUserPasswordAuthenticationToken auth = new CustomUserPasswordAuthenticationToken(
                authentication.getPrincipal(), authentication.getCredentials(), grantedAuthorities);
        return auth;

    } else {//from   w  w  w  .j  av a  2  s .c om
        throw new BadCredentialsException("Bad User Credentials.");
    }
}

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

@Override
public Authentication authenticate(final Authentication authentication) {
    final String userpassword = StringUtils.defaultString(authentication.getCredentials().toString(), "");
    final String userName = StringUtils.lowerCase(authentication.getPrincipal().toString());

    // First get the cookie
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build());
    final HttpPost httpPost = new HttpPost(getSsoPostUrl());

    // Do the POST
    try (CloseableHttpClient httpClient = clientBuilder.build()) {
        final String content = String.format(getSsoPostContent(), userName, userpassword);
        httpPost.setEntity(new StringEntity(content, StandardCharsets.UTF_8));
        httpPost.setHeader("Content-Type", "application/json");
        final HttpResponse httpResponse = httpClient.execute(httpPost);
        if (HttpStatus.SC_NO_CONTENT == httpResponse.getStatusLine().getStatusCode()) {
            // Succeed authentication, save the cookies data inside the authentication
            return newAuthentication(userName, userpassword, authentication, httpResponse);
        }/* w  w w. j  a  v  a 2 s  . com*/
        log.info("Failed authentication of {}[{}] : {}", userName, userpassword.length(),
                httpResponse.getStatusLine().getStatusCode());
        httpResponse.getEntity().getContent().close();
    } catch (final IOException e) {
        log.warn("Remote SSO server is not available", e);
    }
    throw new BadCredentialsException("Invalid user or password");
}

From source file:org.awesomeagile.testing.hackpad.FakeHackpadController.java

@RequestMapping(value = {
        "/api/1.0/pad/{padId}/content/latest.html" }, method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
@ResponseBody//w w w.ja  va2  s  .  c o  m
public String getHackpad(@PathVariable("padId") String padId, @RequestParam("oauth_consumer_key") String key) {
    if (!clientId.equals(key)) {
        throw new BadCredentialsException("Invalid client ID: " + key);
    }
    return hackpads.get(new PadIdentity(padId));
}

From source file:de.zib.gndms.gndms.security.HostAndUserDetailsService.java

@Override
public UserDetails loadUserDetails(
        final PreAuthenticatedAuthenticationToken preAuthenticatedAuthenticationToken)
        throws UsernameNotFoundException {

    String dn = (String) preAuthenticatedAuthenticationToken.getPrincipal();

    try {//from w ww .j  a  v  a2s  . c  o  m
        if (GridMapUserDetailsService.searchInGridMapfile(allowedHostsFileName, dn)) {
            if (reverseDNSTest)
                try {
                    if (!reverseDNSLookup(X509DnConverter.openSslDnExtractCn(dn),
                            preAuthenticatedAuthenticationToken.getDetails())) {
                        logger.info("Host-CN revers DNS lookup failed for: " + dn);
                        throw new BadCredentialsException("Host-CN reverse DNS lookup failed.");
                    }
                } catch (UnknownHostException e) {
                    throw new BadCredentialsException("", e);
                }
            GNDMSUserDetails userDetails = new GNDMSUserDetails();
            userDetails.setAuthorities(Collections.<GrantedAuthority>emptyList());
            userDetails.setDn(dn);
            userDetails.setIsUser(false);
            return userDetails;
        } else {
            final SecurityContext context = SecurityContextHolder.getContext();
            if (context != null && context.getAuthentication() != null) {
                final Object principal = context.getAuthentication().getPrincipal();
                if (principal instanceof GNDMSUserDetails) {
                    // now this must be the Request header authentication
                    final GNDMSUserDetails gndmsUserDetails = (GNDMSUserDetails) principal;
                    if (gndmsUserDetails.isUser())
                        // the x509 cert from the previous filter must have been a user cert
                        // check if the dn's match
                        if (!dn.equals(gndmsUserDetails.getUsername()))
                            throw new UsernameNotFoundException("Certificate vs HttpHeader: dn mismatch ('" + dn
                                    + "' vs. '" + gndmsUserDetails.getUsername() + "'.");
                }
            }
            return userDetailsService.loadUserByUsername(dn);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.devicehive.auth.rest.providers.JwtTokenAuthenticationProvider.java

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

    String token = (String) authentication.getPrincipal();
    try {/* w  w w . j a v a 2 s. c  o  m*/
        JwtPayload jwtPayload = jwtClientService.getPayload(token);

        if (jwtPayload == null
                || (jwtPayload.getExpiration() != null
                        && jwtPayload.getExpiration().before(timestampService.getDate()))
                || jwtPayload.getTokenType().equals(TokenType.REFRESH)) {
            throw new BadCredentialsException("Unauthorized");
        }
        logger.debug("Jwt token authentication successful");

        HivePrincipal principal = new HivePrincipal();
        if (jwtPayload.getUserId() != null) {
            UserVO userVO = userService.findById(jwtPayload.getUserId());
            principal.setUser(userVO);
        }

        Set<String> networkIds = jwtPayload.getNetworkIds();
        if (networkIds != null) {
            if (networkIds.contains("*")) {
                principal.setAllNetworksAvailable(true);
            } else {
                principal.setNetworkIds(networkIds.stream().map(Long::valueOf).collect(Collectors.toSet()));
            }
        }

        Set<String> deviceGuids = jwtPayload.getDeviceGuids();
        if (deviceGuids != null) {
            if (deviceGuids.contains("*")) {
                principal.setAllDevicesAvailable(true);
            } else {
                principal.setDeviceGuids(deviceGuids);
            }
        }

        Set<String> availableActions = jwtPayload.getActions();
        if (availableActions != null) {
            if (availableActions.contains("*")) {
                principal.setActions(AvailableActions.getAllHiveActions());
            } else if (availableActions.isEmpty()) {
                principal.setActions(AvailableActions.getClientHiveActions());
            } else {
                principal.setActions(
                        availableActions.stream().map(HiveAction::fromString).collect(Collectors.toSet()));
            }
        }

        return new HiveAuthentication(principal, AuthorityUtils.createAuthorityList(HiveRoles.JWT));

    } catch (Exception e) {
        throw new BadCredentialsException("Unauthorized");
    }
}