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.ebay.pulsar.analytics.resources.PermissionControlResource.java

@POST
@Path("user")
@Consumes(MediaType.APPLICATION_JSON)/* w ww  . j  a  va 2s.c  o m*/
@Produces(MediaType.APPLICATION_JSON)
public Response addUser(@Context HttpServletRequest request, DBUser user) {
    logger.info("Add User API called from IP: " + request.getRemoteAddr());
    try {
        if (isAnonymous()) {
            throw new BadCredentialsException("Bad credentials");
        }
        if (user == null) {
            throw new IllegalArgumentException("User List is Empty!");
        }
        if (userService.addUser(user) > 0) {
            return Response.ok(user).build();
        } else {
            return Response.status(Status.BAD_REQUEST).build();
        }
    } catch (Exception ex) {
        logger.warn("Response Error: " + ex.getMessage());
        return handleException(ex);
    }

}

From source file:com.ebay.pulsar.analytics.resources.PermissionControlResource.java

@DELETE
@Path("users")
@Consumes(MediaType.APPLICATION_JSON)/*from   w  ww . j a  v a  2  s .c  om*/
@Produces(MediaType.APPLICATION_JSON)
public Response deleteUser(@Context HttpServletRequest request, @QueryParam("batch") String userNames) {
    logger.info("Delete user API called from IP: " + request.getRemoteAddr());
    try {
        if (isAnonymous()) {
            throw new BadCredentialsException("Bad credentials");
        }
        if (userNames == null) {
            throw new IllegalArgumentException("No Users to Delete!");
        }
        long id = userService.deleteUsers(Lists.newArrayList(userNames.split(",")));
        if (id >= 0) {
            return Response.ok(ImmutableMap.of("deleted", id)).build();
        } else {
            return Response.status(Status.BAD_REQUEST).build();
        }
    } catch (Exception ex) {
        logger.warn("Response Error: " + ex.getMessage());
        return handleException(ex);
    }

}

From source file:com.ebay.pulsar.analytics.resources.PermissionControlResource.java

@GET
@Path("users")
@Produces(MediaType.APPLICATION_JSON)/*from www . j a  v  a 2 s.  c o m*/
public Response getAllUsers(@Context HttpServletRequest request) {
    logger.info("List users API called from IP: " + request.getRemoteAddr());
    try {
        if (isAnonymous()) {
            throw new BadCredentialsException("Bad credentials");
        }
        return Response.ok("get all users succeed!").entity(userService.getAllUsers()).build();
    } catch (Exception ex) {
        logger.warn("Response Error: " + ex.getMessage());
        return handleException(ex);
    }

}

From source file:com.ebay.pulsar.analytics.resources.PermissionControlResource.java

@GET
@Path("users/autocomplete")
@Produces(MediaType.APPLICATION_JSON)/*from   w w w.jav  a2 s.c o  m*/
public Response getuserFields(@Context HttpServletRequest request, @QueryParam("name") String name,
        @QueryParam("row") Integer row) {
    logger.info("List users API called from IP: " + request.getRemoteAddr());

    try {
        if (isAnonymous()) {
            throw new BadCredentialsException("Bad credentials");
        }
        List<String> userNames = userService.getAllUsers();
        List<String> result = new ArrayList<String>();
        for (String user : userNames) {
            if (row > 0 && user.startsWith(name)) {
                result.add(user);
                row--;
            }
        }
        return Response.ok(result).build();

    } catch (Exception ex) {
        logger.warn("Response Error: " + ex.getMessage());
        return handleException(ex);
    }

}

From source file:com.ebay.pulsar.analytics.resources.PermissionControlResource.java

@GET
@Path("rights")
@Produces(MediaType.APPLICATION_JSON)/*from   w  w w.j  ava 2s.  c o  m*/
public Response getUserRights(@Context HttpServletRequest request) {
    logger.info("List users API called from IP: " + request.getRemoteAddr());

    try {
        if (isAnonymous()) {
            throw new BadCredentialsException("Bad credentials");
        }
        List<String> allrights = userPermissions.getAllRightsForUser(getUserName());
        Set<String> result = Sets.newHashSet(allrights);
        return Response.ok(result).build();

    } catch (Exception ex) {
        logger.warn("Response Error: " + ex.getMessage());
        return handleException(ex);
    }
}

From source file:com.ebay.pulsar.analytics.resources.PermissionControlResource.java

@GET
@Path("sysrights")
@Produces(MediaType.APPLICATION_JSON)//from w  ww. j  a v a2 s  .c  om
public Response getUserSysRights(@Context HttpServletRequest request) {
    logger.info("List users API called from IP: " + request.getRemoteAddr());

    try {
        if (isAnonymous()) {
            throw new BadCredentialsException("Bad credentials");
        }
        List<String> allrights = userPermissions.getAllRightsForUser(getUserName());
        Set<String> result = Sets.newHashSet();
        for (String right : allrights) {
            if (PermissionConst.isSysPermission(right)) {
                result.add(right);
            }
        }
        return Response.ok(result).build();

    } catch (Exception ex) {
        logger.warn("Response Error: " + ex.getMessage());
        return handleException(ex);
    }
}

From source file:org.activiti.app.security.CustomDaoAuthenticationProvider.java

protected void additionalAuthenticationChecks(
        org.springframework.security.core.userdetails.UserDetails userDetails,
        org.springframework.security.authentication.UsernamePasswordAuthenticationToken authentication)
        throws org.springframework.security.core.AuthenticationException {

    // Overriding this method to catch empty/null passwords. This happens when users are synced with LDAP sync:
    // they will have an external id, but no password (password is checked against ldap).
    ///* w w  w. j a va 2  s  .  co  m*/
    // The default DaoAuthenticationProvider will choke on an empty password (an arrayIndexOutOfBoundsException 
    // somewhere deep in the bowels of password encryption), hence this override
    if (StringUtils.isEmpty(userDetails.getPassword())) {
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }

    super.additionalAuthenticationChecks(userDetails, authentication);

}

From source file:org.apache.ambari.server.security.authorization.jwt.JwtAuthenticationFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
        throws IOException, ServletException {

    if (jwtProperties == null) {
        //disable filter if not configured
        filterChain.doFilter(servletRequest, servletResponse);
        return;/*w  w  w  .j  a v  a2s  .c  o m*/
    }

    HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

    String serializedJWT = getJWTFromCookie(httpServletRequest);
    if (serializedJWT != null && isAuthenticationRequired(serializedJWT)) {
        SignedJWT jwtToken;
        try {
            jwtToken = SignedJWT.parse(serializedJWT);

            boolean valid = validateToken(jwtToken);

            if (valid) {
                String userName = jwtToken.getJWTClaimsSet().getSubject();
                User user = users.getUser(userName, UserType.JWT);
                if (user == null) {

                    //TODO this is temporary check for conflicts, until /users API will change to use user_id instead of name as PK
                    User existingUser = users.getAnyUser(userName);
                    if (existingUser != null && existingUser.getUserType() != UserType.JWT) {

                        LOG.error("Access for JWT user [{}] restricted. Detected conflict with local user ",
                                userName);

                        // directly send HTTP status 500 to avoid redirect loop, as jwt token is already confirmed to be valid
                        httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Cannot create JWT user: conflict detected");

                        //interrupt filter chain
                        return;
                    }

                    // create user in local database on first login, usually we cannot fetch all users
                    // from external authentication provider (as we do during ldap-sync process)
                    users.createUser(userName, null, UserType.JWT, true, false);
                    user = users.getUser(userName, UserType.JWT);
                }

                Collection<AmbariGrantedAuthority> userAuthorities = users
                        .getUserAuthorities(user.getUserName(), user.getUserType());

                JwtAuthentication authentication = new JwtAuthentication(serializedJWT, user, userAuthorities);
                authentication.setAuthenticated(true);

                SecurityContextHolder.getContext().setAuthentication(authentication);

            } else {
                //clear security context if authentication was required, but failed
                SecurityContextHolder.clearContext();

                LOG.warn("JWT authentication failed");
                if (ignoreFailure) {
                    filterChain.doFilter(servletRequest, servletResponse);
                } else {
                    //used to indicate authentication failure, not used here as we have more than one filter
                    entryPoint.commence(httpServletRequest, httpServletResponse,
                            new BadCredentialsException("Invalid JWT " + "token"));
                }
            }

        } catch (ParseException e) {
            LOG.warn("Unable to parse the JWT token", e);
        }
    } else {
        LOG.trace("No JWT cookie found, do nothing");
    }

    filterChain.doFilter(servletRequest, servletResponse);
}

From source file:org.apache.ranger.service.PasswordComparisonAuthenticator.java

public DirContextOperations authenticate(final Authentication authentication) {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            "Can only process UsernamePasswordAuthenticationToken objects");
    // locate the user and check the password

    DirContextOperations user = null;//from w  w w  . j  a  v a 2  s.c o  m
    String username = authentication.getName();
    String password = (String) authentication.getCredentials();

    Iterator dns = getUserDns(username).iterator();

    SpringSecurityLdapTemplate ldapTemplate = new SpringSecurityLdapTemplate(getContextSource());

    while (dns.hasNext() && user == null) {
        final String userDn = (String) dns.next();

        try {
            user = ldapTemplate.retrieveEntry(userDn, getUserAttributes());
        } catch (NameNotFoundException ignore) {
        }
    }

    if (user == null && getUserSearch() != null) {
        user = getUserSearch().searchForUser(username);
    }

    if (user == null) {
        throw new UsernameNotFoundException("User not found: " + username, username);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Performing LDAP compare of password attribute '" + passwordAttributeName + "' for user '"
                + user.getDn() + "'");
    }

    String encodedPassword = passwordEncoder.encodePassword(password, null);
    byte[] passwordBytes = encodedPassword.getBytes();

    if (!ldapTemplate.compare(user.getDn().toString(), passwordAttributeName, passwordBytes)) {
        throw new BadCredentialsException(
                messages.getMessage("PasswordComparisonAuthenticator.badCredentials", "Bad credentials"));
    }

    return user;
}

From source file:org.apache.syncope.core.misc.security.SyncopeAuthenticationProvider.java

@Override
@Transactional(noRollbackFor = { BadCredentialsException.class, DisabledException.class })
public Authentication authenticate(final Authentication authentication) {
    boolean authenticated = false;
    User user = null;/*from   w w  w .j a  va  2  s. c om*/

    String username = authentication.getName();
    if (anonymousUser.equals(username)) {
        authenticated = authentication.getCredentials().toString().equals(anonymousKey);
    } else if (adminUser.equals(username)) {
        authenticated = encryptor.verify(authentication.getCredentials().toString(),
                CipherAlgorithm.valueOf(adminPasswordAlgorithm), adminPassword);
    } else {
        user = userDAO.find(username);

        if (user != null) {
            if (user.isSuspended() != null && user.isSuspended()) {
                throw new DisabledException("User " + user.getUsername() + " is suspended");
            }

            CPlainAttr authStatuses = confDAO.find("authentication.statuses");
            if (authStatuses != null && !authStatuses.getValuesAsStrings().contains(user.getStatus())) {
                throw new DisabledException("User " + user.getUsername() + " not allowed to authenticate");
            }

            authenticated = authenticate(user, authentication.getCredentials().toString());

            updateLoginAttributes(user, authenticated);
        }
    }

    UsernamePasswordAuthenticationToken token;
    if (authenticated) {
        token = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), null, userDetailsService
                .loadUserByUsername(authentication.getPrincipal().toString()).getAuthorities());

        token.setDetails(authentication.getDetails());

        auditManager.audit(AuditElements.EventCategoryType.REST, "AuthenticationController", null, "login",
                Result.SUCCESS, null, authenticated, authentication,
                "Successfully authenticated, with groups: " + token.getAuthorities());

        LOG.debug("User {} successfully authenticated, with groups {}", authentication.getPrincipal(),
                token.getAuthorities());
    } else {
        auditManager.audit(AuditElements.EventCategoryType.REST, "AuthenticationController", null, "login",
                Result.FAILURE, null, authenticated, authentication,
                "User " + authentication.getPrincipal() + " not authenticated");

        LOG.debug("User {} not authenticated", authentication.getPrincipal());

        throw new BadCredentialsException("User " + authentication.getPrincipal() + " not authenticated");
    }

    return token;
}