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.login.SamlRemoteUaaController.java

@RequestMapping(value = "/oauth/token", method = RequestMethod.POST, params = "grant_type=password")
@ResponseBody// w w w .  ja  va  2 s .  c o m
public ResponseEntity<byte[]> tokenEndpoint(HttpServletRequest request, HttpEntity<byte[]> entity,
        @RequestParam Map<String, String> parameters, Map<String, Object> model, Principal principal)
        throws Exception {

    // Request has a password. Owner password grant with a UAA password
    if (null != request.getParameter("password")) {
        return passthru(request, entity, model);
    } else {
        //
        MultiValueMap<String, String> requestHeadersForClientInfo = new LinkedMultiValueMap<String, String>();
        requestHeadersForClientInfo.add(AUTHORIZATION, request.getHeader(AUTHORIZATION));

        ResponseEntity<byte[]> clientInfoResponse = getDefaultTemplate().exchange(
                getUaaBaseUrl() + "/clientinfo", HttpMethod.POST,
                new HttpEntity<MultiValueMap<String, String>>(null, requestHeadersForClientInfo), byte[].class);

        if (clientInfoResponse.getStatusCode() == HttpStatus.OK) {
            String path = extractPath(request);

            MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
            map.setAll(parameters);
            if (principal != null) {
                map.set("source", "login");
                map.set("client_id", getClientId(clientInfoResponse.getBody()));
                map.setAll(getLoginCredentials(principal));
                map.remove("credentials"); // legacy vmc might break otherwise
            } else {
                throw new BadCredentialsException("No principal found in authorize endpoint");
            }

            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.putAll(getRequestHeaders(requestHeaders));
            requestHeaders.remove(AUTHORIZATION.toLowerCase());
            requestHeaders.remove(ACCEPT.toLowerCase());
            requestHeaders.remove(CONTENT_TYPE.toLowerCase());
            requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            requestHeaders.remove(COOKIE);
            requestHeaders.remove(COOKIE.toLowerCase());

            ResponseEntity<byte[]> response = getAuthorizationTemplate().exchange(getUaaBaseUrl() + "/" + path,
                    HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(map, requestHeaders),
                    byte[].class);

            saveCookie(response.getHeaders(), model);

            byte[] body = response.getBody();
            if (body != null) {
                HttpHeaders outgoingHeaders = getResponseHeaders(response.getHeaders());
                return new ResponseEntity<byte[]>(response.getBody(), outgoingHeaders,
                        response.getStatusCode());
            }

            throw new IllegalStateException("Neither a redirect nor a user approval");
        } else {
            throw new BadCredentialsException(new String(clientInfoResponse.getBody()));
        }
    }
}

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

/**
 * Authentication fiware./*from w  ww.  j ava 2s. c  o m*/
 * 
 * @param token
 *            the token
 * @param tenantId
 *            the tenantId
 * @return the open stack user
 * @throws AuthenticationConnectionException
 */
@SuppressWarnings("deprecation")
public PaasManagerUser authenticationFiware(String token, String tenantId)
        throws AuthenticationConnectionException {

    DefaultHttpClient httpClient = new DefaultHttpClient();

    configureOpenStackAuthenticationToken(keystoneURL, adminUser, adminPass, adminTenant, thresholdString,
            httpClient);

    String[] credential = oSAuthToken.getCredentials();

    log.info("Keystone URL : " + keystoneURL);
    log.info("adminToken : " + credential[0]);

    WebTarget webResource = client.target(keystoneURL);
    try {

        Response response = webResource.path("tokens").path(token).request().header("Accept", "application/xml")
                .header("X-Auth-Token", credential[0]).get();

        if (response.getStatus() == CODE_200) {
            AuthenticateResponse authenticateResponse = response.readEntity(AuthenticateResponse.class);

            // Validate user's token
            return validateUserToken(token, tenantId, authenticateResponse);
        } else if (response.getStatus() == CODE_401) {

            // create new admin token
            configureOpenStackAuthenticationToken(keystoneURL, adminUser, adminPass, adminTenant,
                    thresholdString, httpClient);
            String[] newCredentials = oSAuthToken.getCredentials();
            // try validateUserToken
            WebTarget webResource2 = client.target(keystoneURL);
            return validateUserToken(token, tenantId,
                    webResource2.path("tokens").path(token).request().header("Accept", "application/xml")
                            .header("X-Auth-Token", newCredentials[0]).get(AuthenticateResponse.class));

        } else if ((response.getStatus() == CODE_403) || (response.getStatus() == CODE_404)) {
            throw new BadCredentialsException("Token not valid");
        }
        throw new AuthenticationServiceException("Token not valid");

    } catch (Exception e) {

        throw new AuthenticationServiceException("unknown problem", e);
    }
}

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

/**
 * (non-Javadoc) @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
 * javax.servlet.FilterChain)./*from w  w w . jav  a 2 s  . co  m*/
 */
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 headerToken = request.getHeader(OPENSTACK_HEADER_TOKEN);
    String pathInfo = request.getPathInfo();
    logger.debug(headerToken);
    logger.debug(pathInfo);

    // first of all, check HTTP if exists accept header
    if (!validateAcceptHeader(request, response)) {
        return;
    }

    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 (headerToken == null) {
            headerToken = "";
        }

        try {
            String token = headerToken;
            if ("".equals(token)) {
                String str = "Missing token header";
                logger.info(str);
                throw new BadCredentialsException(str);
            }
            String tenantId = request.getHeader(OPENSTACK_HEADER_TENANTID);
            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:com.evolveum.midpoint.model.impl.security.AuthenticationEvaluatorImpl.java

@Override
public UserType checkCredentials(ConnectionEnvironment connEnv, T authnCtx)
        throws BadCredentialsException, AuthenticationCredentialsNotFoundException, DisabledException,
        LockedException, CredentialsExpiredException, AuthenticationServiceException, AccessDeniedException,
        UsernameNotFoundException {//from   w  ww  . j  av a  2  s . com

    checkEnteredCredentials(connEnv, authnCtx);

    MidPointPrincipal principal = getAndCheckPrincipal(connEnv, authnCtx.getUsername(), false);

    UserType userType = principal.getUser();
    CredentialsType credentials = userType.getCredentials();
    CredentialPolicyType credentialsPolicy = getCredentialsPolicy(principal, authnCtx);

    if (checkCredentials(principal, authnCtx, connEnv)) {
        return userType;
    } else {
        recordPasswordAuthenticationFailure(principal, connEnv, getCredential(credentials), credentialsPolicy,
                "password mismatch");

        throw new BadCredentialsException("web.security.provider.invalid");
    }
}

From source file:com.ar.dev.tierra.api.controller.UsuariosController.java

@RequestMapping(value = "/detail", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Usuarios> detailsUsuario(OAuth2Authentication authentication) {
    User user = (User) authentication.getPrincipal();
    Usuarios u = facadeService.getUsuariosDAO().findUsuarioByUsername(user.getUsername());
    if (u == null) {
        throw new BadCredentialsException("Bad Credentials");
    } else {//from w ww  .j a  v  a  2s .c  om
        return new ResponseEntity(u, HttpStatus.OK);
    }
}

From source file:edu.zipcloud.cloudstreetmarket.core.services.CommunityServiceImpl.java

@Override
public User updateUser(User user) {
    Preconditions.checkNotNull(user);/*w  w w  . j  a  v  a 2s  .co m*/
    if (AuthenticationUtil.isThePrincipal(user.getId()) || AuthenticationUtil.userHasRole(ROLE_ADMIN)) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userRepository.save(user);
    } else {
        throw new BadCredentialsException("You are not authorized to perfom this operation!");
    }
}