private void mitigateAgainstTimingAttack(UsernamePasswordAuthenticationToken authentication) { if (authentication.getCredentials() != null) { String presentedPassword = authentication.getCredentials().toString(); this.passwordEncoder.matches(presentedPassword, this.userNotFoundEncodedPassword); } }
private void mitigateAgainstTimingAttack(UsernamePasswordAuthenticationToken authentication) { if (authentication.getCredentials() != null) { String presentedPassword = authentication.getCredentials().toString(); this.passwordEncoder.matches(presentedPassword, this.userNotFoundEncodedPassword); } }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; String username = String.valueOf(auth.getPrincipal()); String password = String.valueOf(auth.getCredentials()); logger.info("username:" + username); logger.info("password:" + password); // Don't log passwords in real app // 1. Use the username to load the data for the user, including authorities and password. YourUser user = .... // 2. Check the passwords match. if (!user.getPassword().equals(password)) { throw new BadCredentialsException("Bad Credentials"); } // 3. Preferably clear the password in the user object before storing in authentication object user.clearPassword(); // 4. Return an authenticated token, containing user data and authorities return UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()) ; }
@SuppressWarnings("deprecation") protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { if (authentication.getCredentials() == null) { logger.debug("Authentication failed: no credentials provided"); throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } String presentedPassword = authentication.getCredentials().toString(); if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) { logger.debug("Authentication failed: password does not match stored value"); throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } }
@SuppressWarnings("deprecation") protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { if (authentication.getCredentials() == null) { logger.debug("Authentication failed: no credentials provided"); throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } String presentedPassword = authentication.getCredentials().toString(); if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) { logger.debug("Authentication failed: password does not match stored value"); throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials")); } }
@Override public Authentication authenticate(Authentication authentication, HttpServletRequest request) throws AuthenticationException { UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication; // check if name is root if (GeoServerUser.ROOT_USERNAME.equals(token.getPrincipal()) == false) return null; // check password if (token.getCredentials() != null) { if (getSecurityManager().checkMasterPassword(token.getCredentials().toString())) { Collection<GrantedAuthority> roles = new ArrayList<GrantedAuthority>(); roles.add(GeoServerRole.ADMIN_ROLE); UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken( GeoServerUser.ROOT_USERNAME, null, roles); result.setDetails(token.getDetails()); return result; } } // not BadCredentialException is thrown, maybe there is another user with // the same name log(new BadCredentialsException("Bad credentials for: " + token.getPrincipal())); return null; } }
@Test public void authenticateSuccess() throws Exception { Authentication auth = provider.authenticate(token); assertThat(auth.getPrincipal()).isEqualTo(token.getPrincipal()); assertThat(auth.getCredentials()).isEqualTo(token.getCredentials()); assertThat(auth.isAuthenticated()).isEqualTo(true); assertThat(auth.getAuthorities().isEmpty()).isEqualTo(false); verify(publisher).publishEvent(isA(JaasAuthenticationSuccessEvent.class)); verifyNoMoreInteractions(publisher); }
@Override protected DirContextOperations doAuthentication( UsernamePasswordAuthenticationToken auth) { String username = auth.getName(); String password = (String) auth.getCredentials(); DirContext ctx = bindAsUser(username, password); try { return searchForUser(ctx, username); } catch (NamingException e) { logger.error("Failed to locate directory entry for authenticated user: " + username, e); throw badCredentials(e); } finally { LdapUtils.closeContext(ctx); } }
/** * Creates the final {@code Authentication} object which will be returned from the * {@code authenticate} method. * * @param authentication the original authentication request token * @param user the <tt>UserDetails</tt> instance returned by the configured * <tt>UserDetailsContextMapper</tt>. * @return the Authentication object for the fully authenticated user. */ protected Authentication createSuccessfulAuthentication( UsernamePasswordAuthenticationToken authentication, UserDetails user) { Object password = this.useAuthenticationRequestCredentials ? authentication.getCredentials() : user.getPassword(); UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken( user, password, this.authoritiesMapper.mapAuthorities(user.getAuthorities())); result.setDetails(authentication.getDetails()); return result; }
request.getPrincipal(), request.getCredentials(), new ArrayList<>(authorities), loginContext);
request.getPrincipal(), request.getCredentials(), new ArrayList<>(authorities), loginContext);
@Test public void testRespectsRolePrefix() throws Exception { UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken( "Test", "Password", AuthorityUtils.createAuthorityList("ONE", "TWO")); RunAsManagerImpl runAs = new RunAsManagerImpl(); runAs.setKey("my_password"); runAs.setRolePrefix("FOOBAR_"); Authentication result = runAs.buildRunAs(inputToken, new Object(), SecurityConfig.createList("RUN_AS_SOMETHING")); assertThat(result instanceof RunAsUserToken).withFailMessage( "Should have returned a RunAsUserToken").isTrue(); assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal()); assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials()); Set<String> authorities = AuthorityUtils.authorityListToSet( result.getAuthorities()); assertThat(authorities.contains("FOOBAR_RUN_AS_SOMETHING")).isTrue(); assertThat(authorities.contains("ONE")).isTrue(); assertThat(authorities.contains("TWO")).isTrue(); RunAsUserToken resultCast = (RunAsUserToken) result; assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode()); }
UsernamePasswordAuthenticationToken newAuth = new UsernamePasswordAuthenticationToken( auth.getPrincipal(), auth.getCredentials(), roles); newAuth.setDetails(auth.getDetails()); return newAuth;
@Test public void testReturnsAdditionalGrantedAuthorities() throws Exception { UsernamePasswordAuthenticationToken inputToken = new UsernamePasswordAuthenticationToken( "Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); RunAsManagerImpl runAs = new RunAsManagerImpl(); runAs.setKey("my_password"); Authentication result = runAs.buildRunAs(inputToken, new Object(), SecurityConfig.createList("RUN_AS_SOMETHING")); if (!(result instanceof RunAsUserToken)) { fail("Should have returned a RunAsUserToken"); } assertThat(result.getPrincipal()).isEqualTo(inputToken.getPrincipal()); assertThat(result.getCredentials()).isEqualTo(inputToken.getCredentials()); Set<String> authorities = AuthorityUtils.authorityListToSet( result.getAuthorities()); assertThat(authorities.contains("ROLE_RUN_AS_SOMETHING")).isTrue(); assertThat(authorities.contains("ROLE_ONE")).isTrue(); assertThat(authorities.contains("ROLE_TWO")).isTrue(); RunAsUserToken resultCast = (RunAsUserToken) result; assertThat(resultCast.getKeyHash()).isEqualTo("my_password".hashCode()); }
@Test public void gettersReturnCorrectData() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "Test", "Password", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); assertThat(token.getPrincipal()).isEqualTo("Test"); assertThat(token.getCredentials()).isEqualTo("Password"); assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities())).contains("ROLE_ONE"); assertThat(AuthorityUtils.authorityListToSet(token.getAuthorities())).contains("ROLE_TWO"); }
MockUserDetailsServiceUserRod userDetailsService = new MockUserDetailsServiceUserRod(); userDetailsService.password = encoder.encode( (CharSequence) foundUser.getCredentials()); provider.setUserDetailsService(userDetailsService);
@Test public void testAuthenticates() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "rod", "koala"); token.setDetails("192.168.0.1"); DaoAuthenticationProvider provider = createProvider(); provider.setUserDetailsService(new MockUserDetailsServiceUserRod()); provider.setUserCache(new MockUserCache()); Authentication result = provider.authenticate(token); if (!(result instanceof UsernamePasswordAuthenticationToken)) { fail("Should have returned instance of UsernamePasswordAuthenticationToken"); } UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result; assertThat(castResult.getPrincipal().getClass()).isEqualTo(User.class); assertThat(castResult.getCredentials()).isEqualTo("koala"); assertThat( AuthorityUtils.authorityListToSet(castResult.getAuthorities())).contains( "ROLE_ONE", "ROLE_TWO"); assertThat(castResult.getDetails()).isEqualTo("192.168.0.1"); }
@Test public void testUserNotFoundBCryptPasswordEncoder() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken( "missing", "koala"); PasswordEncoder encoder = new BCryptPasswordEncoder(); DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setHideUserNotFoundExceptions(false); provider.setPasswordEncoder(encoder); MockUserDetailsServiceUserRod userDetailsService = new MockUserDetailsServiceUserRod(); userDetailsService.password = encoder.encode( (CharSequence) token.getCredentials()); provider.setUserDetailsService(userDetailsService); try { provider.authenticate(token); fail("Expected Exception"); } catch (UsernameNotFoundException success) { } }
/** {@inheritDoc} */ @Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken token) throws AuthenticationException { if (!userDetails.getPassword().equals(token.getCredentials().toString())) { throw new BadCredentialsException(messages.getMessage( "AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"), userDetails); } }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication; String validatedUsername = kerberosClient.login(auth.getName(), auth.getCredentials().toString()); UserDetails userDetails = this.userDetailsService.loadUserByUsername(validatedUsername); UsernamePasswordAuthenticationToken output = new UsernamePasswordAuthenticationToken(userDetails, auth.getCredentials(), userDetails.getAuthorities()); output.setDetails(authentication.getDetails()); return output; }