Java org.springframework.security.authentication.BadCredentialsException 代码实例

・17 分钟阅读

以下是展示如何使用org.springframework.security.authentication.BadCredentialsException的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


/**
 * Login to the api.
 * 
 * Returns a json object with a token on correct login else throws an AuthenticationException. Clients can use this
 * token when calling the api.
 * 
 * Example:
 * 
 * Request: {username:admin,password:xxx}
 * 
 * Response: {token: b4fd94dc-eae6-4d9a-a1b7-dd4525f2f75d}
 * 
 * @param login
 * @param request
 * @return
 */
@RequestMapping(value = "/login", method = POST, produces = APPLICATION_JSON_VALUE)
@ResponseBody
@RunAsSystem
public LoginResponse login(@Valid @RequestBody LoginRequest login, HttpServletRequest request)
{
        if (login == null)
        {
                throw new HttpMessageNotReadableException("Missing login");
        }
        UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(login.getUsername(),
                        login.getPassword());
        authToken.setDetails(new WebAuthenticationDetails(request));
        // Authenticate the login
        Authentication authentication = authenticationManager.authenticate(authToken);
        if (!authentication.isAuthenticated())
        {
                throw new BadCredentialsException("Unknown username or password");
        }
        MolgenisUser user = dataService.findOne(MolgenisUser.ENTITY_NAME,
                        new QueryImpl().eq(MolgenisUser.USERNAME, authentication.getName()), MolgenisUser.class);
        // User authenticated, log the user in
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // Generate a new token for the user
        String token = tokenService.generateAndStoreToken(authentication.getName(), "Rest api login");
        return new LoginResponse(token, user.getUsername(), user.getFirstName(), user.getLastName());
}
 

实例 2


@Test(expected = BadCredentialsException.class)
public void testAuthenticateShouldFailIfWrontPassword() {
    String userName = "admin";
    String password = "admin";
    Mockito.when(ldapTemplate.authenticate("", getUserIdKey() + "=" + userName, password)).thenReturn(false);
    ldapAuthenticationProvider.authenticate(new UsernamePasswordAuthenticationToken(userName, password));
}
 

实例 3


/**
 * ???????????
 * @param name
 * @param pass
 * @param request
 */
public void authenticateUserAndSetSession(String name, String pass,HttpServletRequest request) {
    try {
            AuthUser authUser = mongoUserDao.getAuthUserByName(name);
                UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(name, pass,authUser.getAuthorities());
                // generate session if one doesn't exist
                request.getSession();
                token.setDetails(new WebAuthenticationDetails(request));
                Authentication authenticatedUser = authenticationManager.authenticate(token);
                SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
                AuthUser u = (AuthUser) LoginHelper.getUserDetails();
     } catch (BadCredentialsException e) {
            logger.error("BadCredentialsException: " + e.getLocalizedMessage());
     }
}
 

实例 4


@Test public void testUnknownUserAuthentication() {
    try {
        securityManager.authenticate(new User("John", "Doe"));
        fail("Should have thrown authentication exception");
    } catch(AuthenticationException ae) {
        assertTrue(
                "Expected com.gigaspaces.security.AuthenticationException: org.springframework.security.authentication.BadCredentialsException: Bad credentials",
                ae.getCause() instanceof BadCredentialsException);
    }
}
 

实例 5


@Test
public void onAuthenticationFailure_ShouldSetResponseStatusToUnauthorized() throws IOException, ServletException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    AuthenticationException ex = new BadCredentialsException("");
    failureHandler.onAuthenticationFailure(request, response, ex);
    assertEquals(MockHttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
    assertEquals(RestAuthenticationFailureHandler.STATUS_MESSAGE_AUTHENTICATION_FAILED, response.getErrorMessage());
}
 

实例 6


/**
 * Create a new {@link org.springframework.security.core.userdetails.UserDetails} by uid
 *
 * @param uid         uid
 * @param credentials Credentials(always was password)
 * @return {@link org.springframework.security.core.userdetails.UserDetails}
 * @throws org.springframework.security.authentication.BadCredentialsException if credentials invalid
 */
private UserDetails loadUser(String uid, String credentials) {
    // Not empty
    if(CommUtil.isBlank(uid) || CommUtil.isBlank(credentials)) {
        throw new BadCredentialsException(messages.getMessage(
                "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
    // Load user
    Optional<AuthUser> u=authUserServ.load(uid);
    if(u.filter(x->x.enabled()).isPresent()){
        AuthUser user=u.get();
        // Check credentials
        checkCredentials(user.getPassword(), credentials, user.getSalt());
        // After authenticated handler
        afterAuthenticatedHandler(user);
        List<GrantedAuthority> authorities = new LinkedList<>();
        Set<AuthGroup> groups = user.getGroups();
        if (groups != null && groups.size() > 0) {
            groups.forEach(x -> x.getRoles().forEach(y -> authorities.add(new SimpleGrantedAuthority(y.getName().trim()))));
        }
        return new User(user.getUid(), user.getPassword(), true, true, true, true, authorities);
    }else{
        throw new UsernameNotFoundException(messages.getMessage("",
                new Object[]{uid}, "User {0} has no GrantedAuthority"));
    }
}
 

实例 7


/**
 * {@inheritDoc}
 */
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
 AuthenticationException failed) throws IOException, ServletException {
    // handle the failure and redirect user to the right page
    if (failed instanceof BadCredentialsException) {
        SecurityUtils.redirectToErrorLoginPage(request, response);
        return;
    } else if (failed instanceof AuthenticationServiceException) {
        SecurityUtils.redirectToErrorDBLoginPage(request, response);
        return;
    }
    HttpSession session = request.getSession(true);
    Object openId = session.getAttribute(HttpCookies.UNKNOWN_ID_KEY);
    if (openId != null && failed instanceof UsernameNotFoundException) {
        SecurityUtils.redirectToRegisterPage(request, response);
    }
}
 

实例 8


@Test
public void testNonUAAZoneUaaActiveUaaAuthenticationFailure() throws Exception {
    IdentityZoneHolder.set(ZONE);
    when(providerProvisioning.retrieveByOrigin(Origin.UAA, ZONE.getId())).thenReturn(uaaActive);
    when(providerProvisioning.retrieveByOrigin(Origin.LDAP, ZONE.getId())).thenReturn(ldapActive);
    DynamicZoneAwareAuthenticationManager manager = getDynamicZoneAwareAuthenticationManager(true);
    when(uaaAuthenticationMgr.authenticate(any(Authentication.class))).thenThrow(new BadCredentialsException("mock"));
    DynamicLdapAuthenticationManager mockManager = manager.getLdapAuthenticationManager(null, null);
    when(mockManager.authenticate(any(Authentication.class))).thenReturn(success);
    assertSame(success, manager.authenticate(success));
}
 

实例 9


@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = (String) authentication.getPrincipal();
    String password = (String) authentication.getCredentials();
    UserInstance userInstance;
    try {
        userInstance = userService.authenticateUser(username, password);
    } catch (Throwable e) {
        if (e.getMessage().contains("wrong username") || e.getMessage().contains("No user instance"))
            throw new BadCredentialsException("Bad username or password.");
        String msg = "An error occurred while authenticating user '" + Strings.defaultString(username) + "': " + e.getMessage();
        logger.debug(msg, e);
        throw new BadCredentialsException(msg, e);
    }
    Authentication auth = new C4sUserAuthentication(loadUserByUsername(username).getAuthorities(), authentication, userInstance.getUriId());
    auth.setAuthenticated(true);
    return auth;
}
 

实例 10


@SuppressWarnings("unchecked")
private void testFailedAuth(FilterTestEnv env) throws Exception {
        env.filter.setFilterProcessesUrl(env.req.getRequestURI());
        env.filter.setPostLoginUrl("/success");
        ConnectionFactory<Object> factory = mock(MockConnectionFactory.class);
        when(factory.getProviderId()).thenReturn("mock");
        env.req.setRequestURI(env.req.getRequestURI() + "/" + factory.getProviderId());
        SocialAuthenticationService<Object> authService = mock(SocialAuthenticationService.class);
        when(authService.getConnectionCardinality()).thenReturn(ConnectionCardinality.ONE_TO_ONE);
        when(authService.getConnectionFactory()).thenReturn(factory);
        when(authService.getAuthToken(env.req, env.res)).thenReturn(env.auth);
        env.addAuthService(authService);
        when(env.authManager.authenticate(env.auth)).thenThrow(new BadCredentialsException("Failed"));
        assertNull(SecurityContextHolder.getContext().getAuthentication());
        env.doFilter();
        assertNull(SecurityContextHolder.getContext().getAuthentication());
        assertEquals("http://localhost/register", env.res.getRedirectedUrl());
}
 

实例 11


@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token =
            (UsernamePasswordAuthenticationToken) authentication;
    String login = token.getName();
    UserDetails user = userDetailsService.loadUserByUsername(login);
    if (user == null) {
        throw new UsernameNotFoundException("User does not exists");
    }
    String password = user.getPassword();
    String tokenPassword = (String) token.getCredentials();
    if (!passwordEncoder.matches(tokenPassword, password)) {
        throw new BadCredentialsException("Invalid username/password");
    }
    return new UsernamePasswordAuthenticationToken(user, password,
        user.getAuthorities());
}
 

实例 12


public ExpiringCode doRetrieveCode(String code) {
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.add("Accept", MediaType.APPLICATION_JSON_VALUE);
    HttpEntity<ExpiringCode> requestEntity = new HttpEntity<ExpiringCode>(null, requestHeaders);
    ResponseEntity<ExpiringCode> response = authorizationTemplate.exchange(getUaaBaseUrl() + "/Codes/" + code,
                    HttpMethod.GET,
                    requestEntity, ExpiringCode.class);
    if (response.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
        return null;
    } else if (response.getStatusCode() != HttpStatus.OK) {
        logger.warn("Request failed: " + requestEntity);
        // TODO throw exception with the correct error
        throw new BadCredentialsException("Unable to retrieve passcode:" + String.valueOf(response.getStatusCode()));
    }
    return response.getBody();
}
 

实例 13


@Test
public void testJdkMsKrb5OIDRegressionTweak() throws Exception {
        thrown.expect(BadCredentialsException.class);
        thrown.expectMessage(not(containsString("GSSContext name of the context initiator is null")));
        thrown.expectMessage(containsString("Kerberos validation not successful"));
        SunJaasKerberosTicketValidator validator = new SunJaasKerberosTicketValidator();
        byte[] kerberosTicket = Base64.decode(header.getBytes());
        validator.validateTicket(kerberosTicket);
}
 

实例 14


@Test
public void testAuthWrongPassword() throws BusinessException, NamingException, IOException {
        logger.info(LinShareTestConstants.BEGIN_TEST);
        Date date_before = new Date();
        User user = null;
        try {
                user = ldapQueryService.auth(ldapConn, baseDn, domainPattern, userMail1, "eeee");
        } catch (BadCredentialsException e) {
        }
        Date date_after = new Date();
        Assert.assertNull(user);
        logger.info("fin test : " + String.valueOf(date_after.getTime() - date_before.getTime()));
        logger.debug(LinShareTestConstants.END_TEST);
}
 

实例 15


public String login(String username, String password) {
    LOG.debug("Trying to authenticate " + username + " with Kerberos");
    String validatedUsername;
    try {
        LoginContext loginContext = new LoginContext("", null, new KerberosClientCallbackHandler(username, password),
                new LoginConfig(this.debug));
        loginContext.login();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Kerberos authenticated user: "+loginContext.getSubject());
        }
        validatedUsername = loginContext.getSubject().getPrincipals().iterator().next().toString();
        loginContext.logout();
    } catch (LoginException e) {
        throw new BadCredentialsException("Kerberos authentication failed", e);
    }
    return validatedUsername;
}
 
讨论
淘淘あ西西 profile image