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.haulmont.restapi.idp.IdpAuthController.java

protected OAuth2AccessTokenResult authenticate(String idpTicket, Locale locale, String ipAddress,
        Map<String, String> parameters) {
    IdpSession idpSession = getIdpSession(idpTicket);
    if (idpSession == null) {
        log.info("REST API authentication failed for IDP ticket: {} {}", idpTicket, ipAddress);
        throw new BadCredentialsException("Bad credentials");
    }/* w w w.  j a va2  s.com*/

    if (restApiConfig.getStandardAuthenticationUsers().contains(idpSession.getLogin())) {
        log.info("User {} is not allowed to use external login in REST API", idpSession.getLogin());
        throw new BadCredentialsException("Bad credentials");
    }

    OAuthTokenIssuer.OAuth2AccessTokenRequest tokenRequest = new OAuthTokenIssuer.OAuth2AccessTokenRequest();
    tokenRequest.setLogin(idpSession.getLogin());
    tokenRequest.setLocale(locale);
    tokenRequest.setTokenDetails(ImmutableMap.of(IDP_SESSION_ID_TOKEN_ATTRIBUTE, idpSession.getId()));

    return oAuthTokenIssuer.issueToken(tokenRequest);
}

From source file:com.ctb.prism.login.security.provider.AbstractUserDetailsAuthenticationProvider.java

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
                    "Only UsernamePasswordAuthenticationToken is supported"));

    // Determine username
    String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED" : authentication.getName();

    boolean cacheWasUsed = true;
    UserDetails user = this.userCache.getUserFromCache(username);

    if (user == null) {
        cacheWasUsed = false;//w  w w  . ja v a  2  s  .com

        try {
            user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
        } catch (UsernameNotFoundException notFound) {
            logger.debug("User '" + username + "' not found");

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

        Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
    }

    try {
        preAuthenticationChecks.check(user);
        additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication);
    } catch (AuthenticationException exception) {
        if (cacheWasUsed) {
            // There was a problem, so try again after checking
            // we're using latest data (i.e. not from the cache)
            cacheWasUsed = false;
            user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
            preAuthenticationChecks.check(user);
            additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken) authentication);
        } else {
            throw exception;
        }
    }

    postAuthenticationChecks.check(user);

    if (!cacheWasUsed) {
        this.userCache.putUserInCache(user);
    }

    Object principalToReturn = user;

    if (forcePrincipalAsString) {
        principalToReturn = user.getUsername();
    }

    return createSuccessAuthentication(principalToReturn, authentication, user);
}

From source file:org.brekka.pegasus.core.services.impl.CertificateAuthenticationServiceImpl.java

/**
 * @param subjectDN//from  w  w w.ja v a2s  . c o  m
 * @param allowedSubjectDistinguishedNamePatterns2
 */
protected Matcher matchAllowedSubjectDN(String subjectDN,
        List<Pattern> allowedSubjectDistinguishedNamePatterns) {
    Matcher positiveMatcher = null;
    for (Pattern pattern : allowedSubjectDistinguishedNamePatterns) {
        Matcher matcher = pattern.matcher(subjectDN);
        if (matcher.matches()) {
            positiveMatcher = matcher;
            break;
        }
    }
    if (positiveMatcher == null) {
        throw new BadCredentialsException(
                String.format("The subject DN '%s' is not allowed to access this system", subjectDN));
    }
    return positiveMatcher;
}

From source file:it.scoppelletti.programmerpower.web.security.CasClient.java

/**
 * Richiede un ticket di servizio.//from www .j  av a 2s  .  co  m
 * 
 * @param  ticketGrantingTicket Ticket di autenticazione.
 * @return                      Ticket di servizio.
 */
public String newServiceTicket(String ticketGrantingTicket) throws ProtocolException {
    String text, url;
    Client client;
    Request req;
    Response resp;
    Form form;
    Status status;
    WebResources res = new WebResources();
    SecurityResources secRes = new SecurityResources();

    if (Strings.isNullOrEmpty(ticketGrantingTicket)) {
        throw new ArgumentNullException("ticketGrantingTicket");
    }
    if (Strings.isNullOrEmpty(myServerUrl)) {
        throw new PropertyNotSetException(toString(), "serverUrl");
    }
    if (myServiceProps == null) {
        throw new PropertyNotSetException(toString(), "serviceProperties");
    }

    if (myServerUrl.endsWith("/")) {
        url = myServerUrl;
    } else {
        url = myServerUrl.concat("/");
    }
    url = url.concat(ticketGrantingTicket);

    form = new Form();
    form.add(myServiceProps.getServiceParameter(), myServiceProps.getService());

    req = new Request(Method.POST, url);
    req.setEntity(form.getWebRepresentation(CharacterSet.UTF_8));

    client = new Client(Protocol.HTTPS);
    resp = client.handle(req);

    status = resp.getStatus();
    if (status.equals(Status.CLIENT_ERROR_BAD_REQUEST)) {
        throw new BadCredentialsException(secRes.getFailedLoginException());
    }
    if (status.equals(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE)) {
        throw new ProtocolException(res.getUnsupportedMediaTypeException());
    }
    if (!status.equals(Status.SUCCESS_OK)) {
        throw new ProtocolException(
                res.getUnexpectedStatusCodeException(status.getCode(), status.getDescription()));
    }

    text = resp.getEntityAsText();
    if (Strings.isNullOrEmpty(text)) {
        throw new ProtocolException(res.getEmptyResponseException());
    }

    return text;
}

From source file:com.telefonica.fiware.commons.openstack.auth.OpenStackKeystoneV2.java

/**
 * Check if token is valid for a tenant.
 * /*ww w  .  j  a  va 2  s.  c o  m*/
 * @param token
 * @param tenantId
 * @param response
 * @return
 */
@Override
public String[] checkToken(String token, String tenantId, Response response) {
    if (response.getStatus() == CODE_200) {
        JSONObject jsonObject = JSONObject.fromObject(response.readEntity(String.class));
        jsonObject = (JSONObject) jsonObject.get("access");
        JSONObject tokenJSONObject = (JSONObject) jsonObject.get("token");

        String responseTenantId = (String) ((JSONObject) tokenJSONObject.get("tenant")).get("id");
        String responseTenantName = (String) ((JSONObject) tokenJSONObject.get("tenant")).get("name");
        JSONObject userObject = (JSONObject) jsonObject.get("user");
        String responseUserName = (String) (userObject.get("username"));

        if (!tenantId.equals(responseTenantId)) {
            throw new AuthenticationServiceException(
                    "Token " + token + " not valid for the tenantId provided:" + tenantId);
        }

        return new String[] { responseUserName, responseTenantName };

    } else {
        log.warn("response status:" + response.getStatus());

        if (response.getStatus() == CODE_401) {
            throw new BadCredentialsException("Invalid token");
        }

        throw new AuthenticationServiceException("Invalid token");
    }
}

From source file:org.appverse.web.framework.backend.security.authentication.userpassword.filters.CustomUserNamePasswordAuthenticationFilter.java

private String[] extractUserNameAndPassword(HttpServletRequest request) throws IOException {
    String username = request.getParameter("username");
    String password = request.getParameter("password");

    if (username == null && password == null) {
        throw new BadCredentialsException("Invalid username and password parameters");
    }//  w w  w .j  a  va 2  s .  c o  m
    return new String[] { username, password };
}

From source file:com.telefonica.fiware.commons.openstack.auth.OpenStackKeystoneV3.java

/**
 * Check if token is valid for a tenant.
 * @param token//from   w  w w  .  j  a  v  a  2  s.co m
 * @param tenantId
 * @param response
 * @return
 */
public String[] checkToken(String token, String tenantId, Response response) {
    // Validate user's token
    if (response.getStatus() == CODE_200) {
        JSONObject jsonObject = JSONObject.fromObject(response.readEntity(String.class));
        jsonObject = (JSONObject) jsonObject.get("token");
        String responseTenantId = (String) ((JSONObject) jsonObject.get("project")).get("id");
        String responseTenantName = (String) ((JSONObject) jsonObject.get("project")).get("name");
        JSONObject userObject = (JSONObject) jsonObject.get("user");
        String responseUserName = (String) (userObject.get("name"));

        if (!tenantId.equals(responseTenantId)) {
            throw new AuthenticationServiceException(
                    "Token " + token + " not valid for the tenantId provided:" + tenantId);
        }
        return new String[] { responseUserName, responseTenantName };
    } else {
        log.warn("response status:" + response.getStatus() + " body: " + response.readEntity(String.class));

        if (response.getStatus() == CODE_401) {
            throw new BadCredentialsException("Invalid token");
        }

        throw new AuthenticationServiceException("Invalid token");
    }
}

From source file:com.gst.infrastructure.security.filter.TenantAwareBasicAuthenticationFilter.java

@Override
protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        Authentication authResult) throws IOException {
    super.onSuccessfulAuthentication(request, response, authResult);
    AppUser user = (AppUser) authResult.getPrincipal();

    String pathURL = request.getRequestURI();
    boolean isSelfServiceRequest = (pathURL != null && pathURL.contains("/self/"));

    boolean notAllowed = ((isSelfServiceRequest && !user.isSelfServiceUser())
            || (!isSelfServiceRequest && user.isSelfServiceUser()));

    if (notAllowed) {
        throw new BadCredentialsException("User not authorised to use the requested resource.");
    }// w w  w  .  j  ava  2  s  . co m
}

From source file:com.formkiq.core.service.SpringSecurityService.java

/**
 * Verify user has access to Client./*from w  w  w  .  ja  v a  2  s .  co m*/
 * @param clientid {@link String}
 */
public void verifyUserHasAccessToClient(final String clientid) {

    if (isAdmin() || clientid.equals(getClientId())) {
        return;
    }

    throw new BadCredentialsException("User does not have access to Client");
}

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

@Override
protected final UserDetails retrieveUser(final String username,
        final UsernamePasswordAuthenticationToken authentication) {

    if (null != authentication.getCredentials()) {
        String tenantId = authentication.getCredentials().toString();

        PaasManagerUser paasManagerUser = authenticationFiware(username, tenantId);

        UserDetails userDetails = new User(paasManagerUser.getUserName(), paasManagerUser.getToken(),
                new HashSet<GrantedAuthority>());
        return userDetails;
    } else {// w ww. j a v a 2  s .  c  o  m
        String str = "Missing tenantId header";
        log.info(str);
        throw new BadCredentialsException(str);
    }

}