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.rockagen.gnext.service.spring.security.extension.ExAuthenticationHandler.java

/**
 * Failure register//ww  w  .  j  a  va  2 s . c  o  m
 *
 * @param uid     uid
 * @param request request
 */
private void failureRegister(String uid, HttpServletRequest request) {
    String currentIp = new ExWebAuthenticationDetails(request).getRemoteAddress();
    Optional<AuthUser> u = authUserServ.load(uid);

    if (u.filter(AuthUser::enabled).isPresent()) {
        AuthUser user = u.get();
        Date date = new Date();

        long now = date.getTime();

        // Failed attempts count ++
        Integer failedAttempts = user.getFailedAttempts();
        if (failedAttempts == null) {
            failedAttempts = 0;
        }
        user.setFailedAttempts(++failedAttempts);
        user.setLastSignInAt(user.getCurrentSignInAt());
        user.setCurrentSignInAt(date);
        user.setLastSignInIp(user.getCurrentSignInIp());
        user.setCurrentSignInIp(currentIp);
        Integer signCount = user.getSignInCount();
        if (signCount == null) {
            signCount = 0;
        }
        user.setSignInCount(++signCount);
        // Referer
        String referer = request.getHeader(userReferer);
        user.setLastUserReferer(getReferer(referer));

        if (user.getLastSignInAt() != null) {
            long lastTime = user.getLastSignInAt().getTime();
            // auto lock
            if (user.getFailedAttempts() >= maxFailedAttempts && (now - lastTime) <= lockedTime) {
                // Locked user
                user.setLockedAt(date);
                user.setEnabled(0);
            }
        }

        authUserServ.add(user);

        // locked?
        if (user.getEnabled() < 1) {
            throw new DisabledException(messages.getMessage("AccountStatusUserDetailsChecker.locked"));
        }

        int onlyCount = maxFailedAttempts - user.getFailedAttempts();
        throw new BadCredentialsException(
                messages.getMessage("AccountStatusUserDetailsChecker.onlyCount", new Object[] { onlyCount }));

    } else {
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }

}

From source file:org.glassmaker.spring.oauth.OAuth2AuthenticationProcessingFilter.java

private Authentication createAuthentication(HttpServletRequest request) throws BadCredentialsException {
    try {/*from  ww  w . ja  v  a 2  s  . c o  m*/
        if (request.getParameter("code") != null) {
            AuthorizationCodeFlow flow = oAuth2Util.newAuthorizationCodeFlow();
            TokenResponse tokenResponse = null;

            try {
                tokenResponse = oAuth2Util.newTokenRequest(flow, request.getParameter("code")).execute();
            } catch (TokenResponseException e) {
                if (e.getDetails().getError().contains("invalid_grant")) {
                    logger.warn("User disabled Glassware. Attempting to re-authenticate");
                    throw new BadCredentialsException("Start Login flow");
                }
            }

            // Extract the Google User ID from the ID token in the auth
            // response
            // String userId = ((GoogleTokenResponse)
            // tokenResponse).parseIdToken().getPayload().getUserId();
            String subject = ((GoogleTokenResponse) tokenResponse).parseIdToken().getPayload().getSubject();
            // String email = (String) ((GoogleTokenResponse)
            // tokenResponse).parseIdToken().getPayload().get("email");

            logger.info("Code exchange worked. User " + subject + " logged in.");
            Object mirrorCre = flow.createAndStoreCredential(tokenResponse, subject);

            UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(subject,
                    mirrorCre, (Collection<? extends GrantedAuthority>) new ArrayList<GrantedAuthority>());
            auth.setDetails(tokenResponse.getAccessToken());
            return this.getAuthenticationManager().authenticate(auth);
        }
        if (request.getParameter("error") != null) {
            logger.error("Something went wrong during auth: " + request.getParameter("error"));
            throw new AccessDeniedException(request.getParameter("error"));
        } else {
            Authentication auth = getAuthentication(request);
            if (auth == null)
                throw new BadCredentialsException("Start Login flow");
            else
                return auth;
        }
    } catch (IOException e) {
        logger.error(e);
        throw new BadCredentialsException("CreateAuthentication Failed", e);
    }
}

From source file:com.telefonica.euro_iaas.sdc.puppetwrapper.auth.OpenStackAuthenticationFilter.java

public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
        throws IOException, ServletException {

    final boolean info = logger.isInfoEnabled();
    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    String header = request.getHeader(OPENSTACK_HEADER_TOKEN);
    String pathInfo = request.getPathInfo();

    MDC.put("txId", ((HttpServletRequest) req).getSession().getId());

    if (pathInfo.equals("/") || pathInfo.equals("/extensions")) {
        /**/*from ww w . j av a 2s  .co  m*/
         * It is not needed to authenticate these operations
         */
        logger.info("Operation does not need to Authenticate");
    } else {

        if (header == null) {
            header = "";
        }

        try {
            String token = header;
            if ("".equals(token)) {
                String str = "Missing token header";
                logger.info(str);
                throw new BadCredentialsException(str);
            }
            String tenantId = request.getHeader(OPENSTACK_HEADER_TENANTID);
            String txId = request.getHeader("txId");
            if (txId != null) {
                MDC.put("txId", txId);

            }

            // String tenantId = request.getPathInfo().split("/")[3];

            if (info) {
                logger.info("OpenStack Authentication Authorization header " + "found for user '" + token
                        + "' and tenant " + tenantId);
            }

            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(token,
                    tenantId);
            authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
            Authentication authResult = authenticationManager.authenticate(authRequest);

            if (info) {
                logger.info("Authentication success: " + authResult);
            }

            PaasManagerUser user = (PaasManagerUser) authResult.getPrincipal();

            logger.info("User: " + user.getUsername());
            logger.info("Token: " + user.getToken());
            logger.info("Tenant: " + user.getTenantId());
            logger.info("TenantName - Org: " + user.getTenantName());

            SecurityContextHolder.getContext().setAuthentication(authResult);
            // SecurityContextHolder.setStrategyName("MODE_INHERITABLETHREADLOCAL");

            rememberMeServices.loginSuccess(request, response, authResult);

            onSuccessfulAuthentication(request, response, authResult);

        } catch (AuthenticationException failed) {
            SecurityContextHolder.clearContext();

            if (info) {
                logger.info("Authentication request for failed: " + failed);
            }

            rememberMeServices.loginFail(request, response);
            onUnsuccessfulAuthentication(request, response, failed);

            if (ignoreFailure) {
                chain.doFilter(request, response);
            } else {
                authenticationEntryPoint.commence(request, response, failed);
            }

            return;
        }

        response.addHeader("Www-Authenticate", "Keystone uri='" + keystoneURL + "'");
    }

    // TODO jesuspg: question:add APIException
    chain.doFilter(request, response);

}

From source file:com.telefonica.euro_iaas.sdc.rest.auth.OpenStackAuthenticationFilter.java

/**
 * (non-Javadoc) @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
 * javax.servlet.FilterChain).//from  w w w .j a  v a 2 s.c om
 */
public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
        throws IOException, ServletException {

    final boolean debug = logger.isDebugEnabled();

    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    String header = request.getHeader(OPENSTACK_HEADER_TOKEN);
    String pathInfo = request.getPathInfo();
    logger.debug(header);
    logger.debug(pathInfo);

    MDC.put("txId", ((HttpServletRequest) req).getSession().getId());

    if (pathInfo != null && (pathInfo.equals("/") || pathInfo.equals("/extensions"))) {
        /**
         * It is not needed to authenticate these operations
         */
        logger.debug("Operation does not need to Authenticate");
    } else {

        if (header == null) {
            header = "";
        }

        try {
            String token = header;
            if ("".equals(token)) {
                String str = "Missing token header";
                logger.info(str);
                throw new BadCredentialsException(str);
            }
            String tenantId = request.getHeader(OPENSTACK_HEADER_TENANTID);
            String txId = request.getHeader("txId");
            if (txId != null) {
                MDC.put("txId", txId);

            }

            logger.debug(tenantId);
            logger.debug(token);
            // String tenantId = request.getPathInfo().split("/")[3];

            if (debug) {
                logger.debug("OpenStack Authentication Authorization header " + "found for user '" + token
                        + "' and tenant " + tenantId);
            }

            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(token,
                    tenantId);
            authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
            Authentication authResult = authenticationManager.authenticate(authRequest);

            if (debug) {
                logger.debug("Authentication success: " + authResult);
            }

            // check AUTH-TOKEN and VDC are the same
            String uri = request.getRequestURI();
            logger.debug("URI: " + uri);
            if (uri.contains("vdc") && !uri.contains(tenantId)) {
                String str = "Bad credentials for requested VDC";
                logger.info(str);
                throw new AccessDeniedException(str);
            }

            UserDetails user = (UserDetails) authResult.getPrincipal();
            logger.debug("User: " + user.getUsername());
            logger.debug("Token: " + user.getPassword());
            if (authResult.isAuthenticated()) {
                SecurityContextHolder.getContext().setAuthentication(authRequest);

            }

            // SecurityContextHolder.setStrategyName("MODE_INHERITABLETHREADLOCAL");

            rememberMeServices.loginSuccess(request, response, authResult);

            onSuccessfulAuthentication(request, response, authResult);

        } catch (AuthenticationException failed) {
            SecurityContextHolder.clearContext();

            if (debug) {
                logger.debug("Authentication request for failed: " + failed);
            }

            rememberMeServices.loginFail(request, response);
            onUnsuccessfulAuthentication(request, response, failed);

            if (ignoreFailure) {
                chain.doFilter(request, response);
            } else {
                authenticationEntryPoint.commence(request, response, failed);
            }

            return;
        } catch (AccessDeniedException ex) {
            throw ex;
        } catch (Exception ex) {
            SecurityContextHolder.clearContext();

            if (debug) {
                logger.debug("Authentication exception: " + ex);
            }

            rememberMeServices.loginFail(request, response);

            if (ignoreFailure) {
                chain.doFilter(request, response);
            } else {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            }
            return;
        }

        String keystoneURL = systemPropertiesProvider.getProperty(SystemPropertiesProvider.KEYSTONE_URL);

        response.addHeader("Www-Authenticate", "Keystone uri='" + keystoneURL + "'");
    }

    // TODO jesuspg: question:add APIException
    chain.doFilter(request, response);

}

From source file:org.appverse.web.framework.backend.frontfacade.rest.authentication.basic.services.presentation.BasicAuthenticationServiceImpl.java

private String[] obtainUserAndPasswordFromBasicAuthenticationHeader(HttpServletRequest httpServletRequest)
        throws Exception {
    // Authorization header
    String authHeader = httpServletRequest.getHeader("Authorization");

    if (authHeader == null) {
        throw new BadCredentialsException("Authorization header not found");
    }//from www  . j ava 2s.  c  o  m

    // Decode the authorization string
    String token;
    try {
        //Excluded "Basic " initial string
        byte[] decoded = Base64.decode(authHeader.substring(6).getBytes());
        token = new String(decoded);
    } catch (IllegalArgumentException e) {
        throw new BadCredentialsException("Failed to decode basic authentication token");
    }

    int separator = token.indexOf(":");

    if (separator == -1) {
        throw new BadCredentialsException("Invalid basic authentication token");
    }
    return new String[] { token.substring(0, separator), token.substring(separator + 1) };
}

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

/**
 * Handles an authentication request./*w w w.  jav a2 s  . c o  m*/
 * @param request HTTP request
 * @param response HTTP response
 * @return an authentication object that contains the principal object if successful.
 * @throws IOException ex
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    final String requestURI = request.getRequestURI();
    UserAuthentication userAuth = null;

    if (requestURI.endsWith(TWITTER_ACTION)) {
        String verifier = request.getParameter("oauth_verifier");

        if (verifier == null) {
            String callback = Utils.urlEncode(request.getRequestURL().toString());
            Map<String, String[]> params = new HashMap<String, String[]>();
            params.put("oauth_callback", new String[] { callback });

            HttpPost tokenPost = new HttpPost(FLOW_URL1);
            tokenPost.setHeader(HttpHeaders.AUTHORIZATION, OAuth1HmacSigner.sign("POST", FLOW_URL1, params,
                    Config.TWITTER_APP_ID, Config.TWITTER_SECRET, null, null));
            tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
            CloseableHttpResponse resp1 = httpclient.execute(tokenPost);

            if (resp1.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {
                String decoded = EntityUtils.toString(resp1.getEntity());
                for (String pair : decoded.split("&")) {
                    if (pair.startsWith("oauth_token")) {
                        response.sendRedirect(FLOW_URL2 + pair);
                        return null;
                    }
                }
            }
        } else {
            String token = request.getParameter("oauth_token");
            Map<String, String[]> params = new HashMap<String, String[]>();
            params.put("oauth_verifier", new String[] { verifier });

            HttpPost tokenPost = new HttpPost(FLOW_URL3);
            tokenPost.setEntity(new StringEntity("oauth_verifier=" + verifier));
            tokenPost.setHeader(HttpHeaders.AUTHORIZATION, OAuth1HmacSigner.sign("POST", FLOW_URL3, params,
                    Config.TWITTER_APP_ID, Config.TWITTER_SECRET, token, null));
            tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
            CloseableHttpResponse resp2 = httpclient.execute(tokenPost);

            if (resp2.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK) {
                String decoded = EntityUtils.toString(resp2.getEntity());
                String oauthToken = null;
                String oauthSecret = null;
                for (String pair : decoded.split("&")) {
                    if (pair.startsWith("oauth_token_secret")) {
                        oauthSecret = pair.substring(19);
                    } else if (pair.startsWith("oauth_token")) {
                        oauthToken = pair.substring(12);
                    }
                }
                userAuth = getOrCreateUser(null, oauthToken, oauthSecret);
            }
        }
    }

    User user = SecurityUtils.getAuthenticatedUser(userAuth);

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

From source file:org.taverna.server.master.identity.WorkflowInternalAuthProvider.java

/**
 * Check that the authentication request is actually valid for the given
 * user record.//from www. java2 s.c  o  m
 * 
 * @param userRecord
 *            as retrieved from the
 *            {@link #retrieveUser(String, UsernamePasswordAuthenticationToken)}
 *            or <code>UserCache</code>
 * @param principal
 *            the principal that is trying to authenticate (and that we're
 *            trying to bind)
 * @param credentials
 *            the credentials (e.g., password) presented by the principal
 * 
 * @throws AuthenticationException
 *             AuthenticationException if the credentials could not be
 *             validated (generally a <code>BadCredentialsException</code>,
 *             an <code>AuthenticationServiceException</code>)
 * @throws Exception
 *             If something goes wrong. Will be logged and converted to a
 *             generic AuthenticationException.
 */
protected void additionalAuthenticationChecks(UserDetails userRecord, @Nonnull Object principal,
        @Nonnull Object credentials) throws Exception {
    @Nonnull
    HttpServletRequest req = ((ServletRequestAttributes) currentRequestAttributes()).getRequest();

    // Are we coming from a "local" address?
    if (!req.getLocalAddr().equals(req.getRemoteAddr()) && !authorizedAddresses.contains(req.getRemoteAddr())) {
        if (logDecisions)
            log.info("attempt to use workflow magic token from untrusted address:" + " token="
                    + userRecord.getUsername() + ", address=" + req.getRemoteAddr());
        throw new BadCredentialsException("bad login token");
    }

    // Does the password match?
    if (!credentials.equals(userRecord.getPassword())) {
        if (logDecisions)
            log.info("workflow magic token is untrusted due to password mismatch:" + " wanted="
                    + userRecord.getPassword() + ", got=" + credentials);
        throw new BadCredentialsException("bad login token");
    }

    if (logDecisions)
        log.info("granted role " + SELF + " to user " + userRecord.getUsername());
}

From source file:com.devicehive.auth.rest.HttpAuthenticationFilter.java

private Pair<String, String> extractAndDecodeHeader(String header) throws UnsupportedEncodingException {
    byte[] base64Token = header.substring(6).getBytes("UTF-8");
    byte[] decoded;
    try {/*w ww.  ja v  a 2 s.co  m*/
        decoded = Base64.decode(base64Token);
    } catch (IllegalArgumentException e) {
        throw new BadCredentialsException("Failed to decode basic authentication token");
    }
    String token = new String(decoded, "UTF-8");
    int delim = token.indexOf(":");
    if (delim == -1) {
        throw new BadCredentialsException("Invalid basic authentication token");
    }
    return Pair.of(token.substring(0, delim), token.substring(delim + 1));
}

From source file:org.verinice.rest.security.VeriniceAuthenticationProvider.java

@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {

    if (authentication.getCredentials() == null) {
        LOG.debug("Authentication failed: no credentials provided");

        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }//from www  .  ja  v a 2s  .  co  m

    boolean rightPassword = checkPassword(userDetails, authentication);

    if (!rightPassword) {
        LOG.debug("Authentication failed: password does not match stored value");

        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
}

From source file:net.ljcomputing.ecsr.security.service.impl.JwtTokenServiceImpl.java

/**
 * @see net.ljcomputing.ecsr.security.service.impl.JwtTokenService
 *    #getTokenAuthentication(java.lang.String)
 */// ww w . j av  a 2s.c  om
@Override
public Authentication getTokenAuthentication(final String token) {
    if (token == null) {
        throw new BadCredentialsException("Token provided was invalid. NOT");
    }

    try {
        final Claims claims = Jwts.parser().setSigningKey(tokenSigningKey) // NOPMD
                .parseClaimsJws(token).getBody();

        final Collection<? extends GrantedAuthority> authorities = Arrays
                .asList(claims.get(WebSecurityConfiguration.AUTHORITIES_KEY) // NOPMD
                        .toString().split(","))
                .stream() // NOPMD
                .map(authority -> new SimpleGrantedAuthority(authority)).collect(Collectors.toList());

        final String subject = claims.getSubject(); // NOPMD
        final User principal = new User(subject, "", authorities);

        return new UsernamePasswordAuthenticationToken(principal, "", authorities);
    } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException
            | IllegalArgumentException | NullPointerException exception) {
        throw new BadCredentialsException("Token provided was invalid.");
    }
}