Example usage for org.springframework.security.authentication BadCredentialsException getMessage

List of usage examples for org.springframework.security.authentication BadCredentialsException getMessage

Introduction

In this page you can find the example usage for org.springframework.security.authentication BadCredentialsException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:io.dacopancm.jfee.managedController.LoginBean.java

public String login() {
    try {//from  ww w.j av  a 2s  .  c om
        Authentication request = new UsernamePasswordAuthenticationToken(this.getUserName(),
                this.getPassword());
        Authentication result = authenticationManager.authenticate(request);
        SecurityContextHolder.getContext().setAuthentication(result);

    } catch (BadCredentialsException bc) {
        log.info("jfee: " + bc.getMessage());
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                "Login Incorrecto", "Usuario o contrasea incorrecto"));
        usuarioService.failLoginUser(this.getUserName());
        return null;
    } catch (Exception e) {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
                "Login Incorrecto", "Cuenta inhabilitada o no confirmada."));
        return null;
    }

    User userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    FacesContext.getCurrentInstance().addMessage(null,
            new FacesMessage(FacesMessage.SEVERITY_INFO, "Bienvenido", "Hola, " + userDetails.getUsername()));
    return "correct";
}

From source file:org.osiam.auth.login.oauth.OsiamResourceOwnerPasswordTokenGranter.java

@Override
protected OAuth2Authentication getOAuth2Authentication(AuthorizationRequest clientToken) {

    Map<String, String> parameters = clientToken.getAuthorizationParameters();
    String username = parameters.get("username");
    String password = parameters.get("password");

    Authentication userAuth = new InternalAuthentication(username, password, new ArrayList<GrantedAuthority>());
    try {/*from   ww  w  .j  a  v a  2 s.  c om*/
        userAuth = authenticationManager.authenticate(userAuth);
    } catch (AccountStatusException ase) {
        // covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
        throw new InvalidGrantException(ase.getMessage(), ase);
    } catch (BadCredentialsException e) {
        // If the username/password are wrong the spec says we should send 400/bad grant
        throw new InvalidGrantException(e.getMessage(), e);
    }

    if (userAuth == null || !userAuth.isAuthenticated()) {
        throw new InvalidGrantException("Could not authenticate user: " + username);
    }

    DefaultAuthorizationRequest request = new DefaultAuthorizationRequest(clientToken);
    request.remove(Arrays.asList("password"));

    return new OAuth2Authentication(request, userAuth);
}

From source file:org.cloudfoundry.identity.uaa.scim.endpoints.PasswordResetEndpoints.java

private ResponseEntity<String> changePasswordUsernamePasswordAuthenticated(PasswordChange passwordChange) {
    List<ScimUser> results = scimUserProvisioning.query("userName eq '" + passwordChange.getUsername() + "'");
    if (results.isEmpty()) {
        return new ResponseEntity<String>(BAD_REQUEST);
    }//  w ww. j  a v  a  2s .  c om
    String oldPassword = passwordChange.getCurrentPassword();
    ScimUser user = results.get(0);
    try {
        scimUserProvisioning.changePassword(user.getId(), oldPassword, passwordChange.getNewPassword());
        publish(new PasswordChangeEvent("Password changed", getUaaUser(user),
                SecurityContextHolder.getContext().getAuthentication()));
        return new ResponseEntity<String>(user.getUserName(), OK);
    } catch (BadCredentialsException x) {
        publish(new PasswordChangeFailureEvent(x.getMessage(), getUaaUser(user),
                SecurityContextHolder.getContext().getAuthentication()));
        return new ResponseEntity<String>(UNAUTHORIZED);
    } catch (ScimResourceNotFoundException x) {
        publish(new PasswordChangeFailureEvent(x.getMessage(), getUaaUser(user),
                SecurityContextHolder.getContext().getAuthentication()));
        return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
    } catch (Exception x) {
        publish(new PasswordChangeFailureEvent(x.getMessage(), getUaaUser(user),
                SecurityContextHolder.getContext().getAuthentication()));
        return new ResponseEntity<String>(INTERNAL_SERVER_ERROR);
    }
}

From source file:org.cloudfoundry.identity.uaa.scim.endpoints.PasswordResetEndpoints.java

private ResponseEntity<String> changePasswordCodeAuthenticated(PasswordChange passwordChange) {
    ExpiringCode expiringCode = expiringCodeStore.retrieveCode(passwordChange.getCode());
    if (expiringCode == null) {
        return new ResponseEntity<String>(BAD_REQUEST);
    }/*from  w w  w  .j a v  a 2 s.c o  m*/
    String userId = expiringCode.getData();
    ScimUser user = scimUserProvisioning.retrieve(userId);
    try {
        scimUserProvisioning.changePassword(userId, null, passwordChange.getNewPassword());
        publish(new PasswordChangeEvent("Password changed", getUaaUser(user),
                SecurityContextHolder.getContext().getAuthentication()));
        return new ResponseEntity<String>(user.getUserName(), OK);
    } catch (BadCredentialsException x) {
        publish(new PasswordChangeFailureEvent(x.getMessage(), getUaaUser(user),
                SecurityContextHolder.getContext().getAuthentication()));
        return new ResponseEntity<String>(UNAUTHORIZED);
    } catch (ScimResourceNotFoundException x) {
        publish(new PasswordChangeFailureEvent(x.getMessage(), getUaaUser(user),
                SecurityContextHolder.getContext().getAuthentication()));
        return new ResponseEntity<String>(HttpStatus.NOT_FOUND);
    } catch (Exception x) {
        publish(new PasswordChangeFailureEvent(x.getMessage(), getUaaUser(user),
                SecurityContextHolder.getContext().getAuthentication()));
        return new ResponseEntity<String>(INTERNAL_SERVER_ERROR);
    }
}

From source file:org.dspace.rest.authentication.DSpaceAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Context context = null;//from  w  w w  .  j  av a2s. co m

    try {
        context = new Context();
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
        HttpServletRequest httpServletRequest = new DSpace().getRequestService().getCurrentRequest()
                .getHttpServletRequest();
        List<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<>();

        int implicitStatus = authenticationService.authenticateImplicit(context, null, null, null,
                httpServletRequest);

        if (implicitStatus == AuthenticationMethod.SUCCESS) {
            log.info(LogManager.getHeader(context, "login", "type=implicit"));
            addSpecialGroupsToGrantedAuthorityList(context, httpServletRequest, grantedAuthorities);
            return createAuthenticationToken(password, context, grantedAuthorities);

        } else {
            int authenticateResult = authenticationService.authenticate(context, name, password, null,
                    httpServletRequest);
            if (AuthenticationMethod.SUCCESS == authenticateResult) {
                addSpecialGroupsToGrantedAuthorityList(context, httpServletRequest, grantedAuthorities);

                log.info(LogManager.getHeader(context, "login", "type=explicit"));

                return createAuthenticationToken(password, context, grantedAuthorities);

            } else {
                log.info(LogManager.getHeader(context, "failed_login",
                        "email=" + name + ", result=" + authenticateResult));
                throw new BadCredentialsException("Login failed");
            }
        }
    } catch (BadCredentialsException e) {
        throw e;
    } catch (Exception e) {
        log.error("Error while authenticating in the rest api", e);
    } finally {
        if (context != null && context.isValid()) {
            try {
                context.complete();
            } catch (SQLException e) {
                log.error(e.getMessage() + " occurred while trying to close", e);
            }
        }
    }

    return null;
}

From source file:com.devicehive.websockets.WebSocketResponseBuilder.java

public JsonObject buildResponse(JsonObject request, WebSocketSession session) {
    JsonObject response;//from w  w  w . j a v  a2 s  .c  o m
    try {
        response = requestProcessor.process(request, session).getResponseAsJson();
    } catch (BadCredentialsException ex) {
        logger.error("Unauthorized access", ex);
        response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_UNAUTHORIZED, "Invalid credentials").build();
    } catch (AccessDeniedException ex) {
        logger.error("Access to action is denied", ex);
        response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized").build();
    } catch (HiveException ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder.createError(ex).build();
    } catch (ConstraintViolationException ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage()).build();
    } catch (org.hibernate.exception.ConstraintViolationException ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_CONFLICT, ex.getMessage()).build();
    } catch (JsonParseException ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder.createErrorResponseBuilder(HttpServletResponse.SC_BAD_REQUEST,
                Messages.INVALID_REQUEST_PARAMETERS).build();
    } catch (OptimisticLockException ex) {
        logger.error("Error executing the request", ex);
        logger.error("Data conflict", ex);
        response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_CONFLICT, Messages.CONFLICT_MESSAGE).build();
    } catch (PersistenceException ex) {
        if (ex.getCause() instanceof org.hibernate.exception.ConstraintViolationException) {
            response = JsonMessageBuilder
                    .createErrorResponseBuilder(HttpServletResponse.SC_CONFLICT, ex.getMessage()).build();
        } else {
            response = JsonMessageBuilder
                    .createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage())
                    .build();
        }
    } catch (Exception ex) {
        logger.error("Error executing the request", ex);
        response = JsonMessageBuilder
                .createErrorResponseBuilder(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage())
                .build();
    }

    return new JsonMessageBuilder().addAction(request.get(JsonMessageBuilder.ACTION))
            .addRequestId(request.get(JsonMessageBuilder.REQUEST_ID)).include(response).build();
}

From source file:org.apache.atlas.web.security.FileAuthenticationTest.java

@Test
public void testInValidPasswordLogin() {

    when(authentication.getName()).thenReturn("admin");
    when(authentication.getCredentials()).thenReturn("wrongpassword");

    try {/*  w w  w.  j a  va  2  s  .c  om*/
        Authentication auth = authProvider.authenticate(authentication);
        LOG.debug(" {}", auth);
    } catch (BadCredentialsException bcExp) {
        Assert.assertEquals("Wrong password", bcExp.getMessage());
    }
}

From source file:org.yes.cart.web.page.AbstractWebPage.java

/**
 * Executes Http commands that are posted via http and are available from
 * this.getPageParameters() method. This method should be the first thing that
 * is executed if a page is using shopping cart.
 *
 * This method DOES NOT persist the cart to cookies.
 *
 * This method should only be called once per page request.
 *///from  ww w . ja v  a  2s  .  c o  m
public void executeHttpPostedCommands() {

    final ShoppingCart cart = ApplicationDirector.getShoppingCart();

    final PageParameters params = getPageParameters();
    final Map<String, String> paramsMap = wicketUtil.pageParametesAsMap(params);
    try {

        getShoppingCartCommandFactory().execute(cart, (Map) paramsMap);

        if (paramsMap.containsKey(ShoppingCartCommand.CMD_RESET_PASSWORD)) {
            info(getLocalizer().getString("newPasswordEmailSent", this));
        }

    } catch (BadCredentialsException bce) {

        if (Constants.PASSWORD_RESET_AUTH_TOKEN_INVALID.equals(bce.getMessage())) {
            error(getLocalizer().getString("newPasswordInvalidToken", this));
        }

    } catch (Exception exp) {

        ShopCodeContext.getLog(this).error("Could not execute shopping cart command", exp);

    }

}