use of org.springframework.security.core.userdetails.UsernameNotFoundException in project kylo by Teradata.
the class ActiveDirectoryAuthenticationProvider method searchForUser.
private DirContextOperations searchForUser(DirContext context, String username) throws NamingException {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String bindPrincipal = createBindPrincipal(username);
String searchRoot = rootDn != null ? rootDn : searchRootFromPrincipal(bindPrincipal);
try {
return SpringSecurityLdapTemplate.searchForSingleEntryInternal(context, searchControls, searchRoot, searchFilter, new Object[] { bindPrincipal, username });
} catch (IncorrectResultSizeDataAccessException incorrectResults) {
// Search should never return multiple results if properly configured - just rethrow
if (incorrectResults.getActualSize() != 0) {
throw incorrectResults;
}
// If we found no results, then the username/password did not match
UsernameNotFoundException userNameNotFoundException = new UsernameNotFoundException("User " + username + " not found in directory.", incorrectResults);
throw badCredentials(userNameNotFoundException);
}
}
use of org.springframework.security.core.userdetails.UsernameNotFoundException in project pentaho-platform by pentaho.
the class SpringSecurityPrincipalProvider method internalGetUserDetails.
/**
* Gets user details. Checks cache first.
*/
protected UserDetails internalGetUserDetails(final String username) {
if (username != null && username.equals("administrators")) {
return null;
}
// optimization for when running in pre-authenticated mode (i.e. Spring Security filters have setup holder with
// current user meaning we don't have to hit the back-end again)
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
Object ssPrincipal = auth.getPrincipal();
if (ssPrincipal instanceof UserDetails) {
if (username.equals(((UserDetails) ssPrincipal).getUsername())) {
return (UserDetails) ssPrincipal;
}
}
}
UserDetails user = null;
// user cache not available or user not in cache; do lookup
List<GrantedAuthority> auths = null;
List<GrantedAuthority> authorities = null;
UserDetails newUser = null;
if (getUserDetailsService() != null) {
try {
user = getUserDetailsService().loadUserByUsername(username);
// Authentication object is null then we will get it from IUserRoleListService
if (auth == null || auth.getAuthorities() == null || auth.getAuthorities().size() == 0) {
if (logger.isTraceEnabled()) {
logger.trace("Authentication object from SecurityContextHolder is null," + " so getting the roles for [ " + user.getUsername() + // $NON-NLS-1$
" ] from IUserRoleListService ");
}
List<String> roles = getUserRoleListService().getRolesForUser(JcrTenantUtils.getCurrentTenant(), username);
authorities = new ArrayList<GrantedAuthority>(roles.size());
for (String role : roles) {
authorities.add(new SimpleGrantedAuthority(role));
}
} else {
authorities = new ArrayList<GrantedAuthority>(auth.getAuthorities().size());
authorities.addAll(auth.getAuthorities());
}
auths = new ArrayList<GrantedAuthority>(authorities.size());
// cache the roles while we're here
for (GrantedAuthority authority : authorities) {
String role = authority.getAuthority();
final String tenatedRoleString = JcrTenantUtils.getTenantedRole(role);
if (cacheManager != null) {
Object rolePrincipal = cacheManager.getFromRegionCache(ROLE_CACHE_REGION, role);
if (rolePrincipal == null) {
final SpringSecurityRolePrincipal ssRolePrincipal = new SpringSecurityRolePrincipal(tenatedRoleString);
cacheManager.putInRegionCache(ROLE_CACHE_REGION, role, ssRolePrincipal);
}
}
auths.add(new SimpleGrantedAuthority(tenatedRoleString));
}
if (logger.isTraceEnabled()) {
// $NON-NLS-1$
logger.trace("found user in back-end " + user.getUsername());
}
} catch (UsernameNotFoundException e) {
if (logger.isTraceEnabled()) {
logger.trace(// $NON-NLS-1$ //$NON-NLS-2$
"username " + username + " not in cache or back-end; returning null");
}
}
if (user != null) {
if (auths == null || auths.size() <= 0) {
logger.trace("Authorities are null, so creating an empty Auth array == " + user.getUsername());
// auth is null so we are going to pass an empty auths collection
auths = new ArrayList<GrantedAuthority>();
}
String password = user.getPassword() != null ? user.getPassword() : "";
newUser = new User(user.getUsername(), password, user.isEnabled(), ACCOUNT_NON_EXPIRED, CREDS_NON_EXPIRED, ACCOUNT_NON_LOCKED, auths);
}
}
return newUser;
}
use of org.springframework.security.core.userdetails.UsernameNotFoundException in project pentaho-platform by pentaho.
the class SpringSecurityLoginModuleTest method testExceptions.
@Test
public void testExceptions() throws Exception {
// clear any authentication
SecurityContextHolder.getContext().setAuthentication(null);
Subject subject = new Subject();
TestCallbackHandler testCallbackHandler = new TestCallbackHandler("joe");
SpringSecurityLoginModule loginModule = new SpringSecurityLoginModule();
AuthenticationManager authenticationManager = mock(AuthenticationManager.class);
IUserRoleListService userRoleListService = mock(IUserRoleListService.class);
IAuthorizationPolicy authorizationPolicy = mock(IAuthorizationPolicy.class);
Authentication authentication = mock(Authentication.class);
Collection authorities = Arrays.asList(new GrantedAuthority[] { new SimpleGrantedAuthority("Authenticated"), new SimpleGrantedAuthority("Administrator") });
Authentication authentication2 = mock(Authentication.class);
Collection authorities2 = Arrays.asList(new GrantedAuthority[] { new SimpleGrantedAuthority("Authenticated"), new SimpleGrantedAuthority("ceo") });
PentahoSystem.registerObject(userRoleListService, IUserRoleListService.class);
when(authorizationPolicy.isAllowed(AdministerSecurityAction.NAME)).thenReturn(true).thenReturn(true).thenReturn(false);
when(authentication.getAuthorities()).thenReturn(authorities);
when(authentication.getName()).thenReturn("joe");
when(authentication.isAuthenticated()).thenReturn(true);
when(authentication2.getAuthorities()).thenReturn(authorities2);
when(authentication2.getName()).thenReturn("pat");
when(authentication2.isAuthenticated()).thenReturn(true);
when(authenticationManager.authenticate(argThat(new AuthenticationManagerMatcher("joe")))).thenReturn(authentication);
when(authenticationManager.authenticate(argThat(new AuthenticationManagerMatcher("pat")))).thenReturn(authentication);
when(authenticationManager.authenticate(argThat(new AuthenticationManagerMatcher("suzy")))).thenThrow(new UsernameNotFoundException("Error"));
when(userRoleListService.getRolesForUser(null, "joe")).thenReturn(Arrays.<String>asList("Authenticated", "Administrator"));
when(userRoleListService.getRolesForUser(null, "pat")).thenReturn(Arrays.<String>asList("Authenticated", "ceo"));
loginModule.setAuthenticationManager(authenticationManager);
loginModule.setAuthorizationPolicy(authorizationPolicy);
// test a successful run
loginModule.initialize(subject, testCallbackHandler, Collections.emptyMap(), Collections.emptyMap());
loginModule.login();
loginModule.commit();
verify(authenticationManager).authenticate(argThat(new AuthenticationManagerMatcher("joe")));
assertEquals(4, subject.getPrincipals().size());
subject.getPrincipals().toArray()[3].equals("karaf_admin");
// now test exceptions
// Test with Authentication bound to thread
testCallbackHandler = new TestCallbackHandler("ioe");
loginModule.initialize(subject, testCallbackHandler, Collections.emptyMap(), Collections.emptyMap());
try {
loginModule.login();
fail("Should have thrown IOException");
} catch (LoginException ioe) {
/* No-op */
}
// UnsupportedCallbackException thrown by underlying system
testCallbackHandler = new TestCallbackHandler("unsupported");
loginModule.initialize(subject, testCallbackHandler, Collections.emptyMap(), Collections.emptyMap());
try {
loginModule.login();
fail("Should have thrown UnsupportedCallbackException");
} catch (LoginException ioe) {
/* No-op */
}
SecurityContextHolder.getContext().setAuthentication(null);
// IOException thrown by underlying system
testCallbackHandler = new TestCallbackHandler("ioe");
loginModule.initialize(subject, testCallbackHandler, Collections.emptyMap(), Collections.emptyMap());
try {
loginModule.login();
fail("Should have thrown IOException");
} catch (LoginException ioe) {
/* No-op */
}
testCallbackHandler = new TestCallbackHandler("unsupported");
loginModule.initialize(subject, testCallbackHandler, Collections.emptyMap(), Collections.emptyMap());
try {
loginModule.login();
fail("Should have thrown UnsupportedCallbackException");
} catch (LoginException ioe) {
/* No-op */
}
}
use of org.springframework.security.core.userdetails.UsernameNotFoundException in project pentaho-platform by pentaho.
the class SpringSecurityLoginModuleTest method testLogin.
@Test
public void testLogin() throws Exception {
// instances and mocks
Subject subject = new Subject();
TestCallbackHandler testCallbackHandler = new TestCallbackHandler("joe");
SpringSecurityLoginModule loginModule = new SpringSecurityLoginModule();
AuthenticationManager authenticationManager = mock(AuthenticationManager.class);
IUserRoleListService userRoleListService = mock(IUserRoleListService.class);
IAuthorizationPolicy authorizationPolicy = mock(IAuthorizationPolicy.class);
Authentication authentication = mock(Authentication.class);
Collection authorities = Arrays.asList(new GrantedAuthority[] { new SimpleGrantedAuthority("Authenticated"), new SimpleGrantedAuthority("Administrator") });
Authentication authentication2 = mock(Authentication.class);
Collection authorities2 = Arrays.asList(new GrantedAuthority[] { new SimpleGrantedAuthority("Authenticated"), new SimpleGrantedAuthority("ceo") });
//
PentahoSystem.registerObject(userRoleListService, IUserRoleListService.class);
when(authorizationPolicy.isAllowed(AdministerSecurityAction.NAME)).thenReturn(true).thenReturn(true).thenReturn(false);
when(authentication.getAuthorities()).thenReturn(authorities);
when(authentication.getName()).thenReturn("joe");
when(authentication.isAuthenticated()).thenReturn(true);
when(authentication2.getAuthorities()).thenReturn(authorities2);
when(authentication2.getName()).thenReturn("pat");
when(authentication2.isAuthenticated()).thenReturn(true);
when(authenticationManager.authenticate(argThat(new AuthenticationManagerMatcher("joe")))).thenReturn(authentication);
when(authenticationManager.authenticate(argThat(new AuthenticationManagerMatcher("pat")))).thenReturn(authentication);
when(authenticationManager.authenticate(argThat(new AuthenticationManagerMatcher("suzy")))).thenThrow(new UsernameNotFoundException("Error"));
when(userRoleListService.getRolesForUser(null, "joe")).thenReturn(Arrays.<String>asList("Authenticated", "Administrator"));
when(userRoleListService.getRolesForUser(null, "pat")).thenReturn(Arrays.<String>asList("Authenticated", "ceo"));
loginModule.setAuthenticationManager(authenticationManager);
loginModule.setAuthorizationPolicy(authorizationPolicy);
// start tests
loginModule.initialize(subject, testCallbackHandler, Collections.emptyMap(), Collections.emptyMap());
loginModule.login();
loginModule.commit();
// joe should get the extra karaf_admin role
verify(authenticationManager).authenticate(argThat(new AuthenticationManagerMatcher("joe")));
assertEquals(4, subject.getPrincipals().size());
subject.getPrincipals().toArray()[3].equals("karaf_admin");
loginModule.logout();
assertEquals(0, subject.getPrincipals().size());
loginModule.login();
loginModule.commit();
assertEquals(4, subject.getPrincipals().size());
// Suzy is not found
testCallbackHandler = new TestCallbackHandler("suzy");
loginModule.initialize(subject, testCallbackHandler, Collections.emptyMap(), Collections.emptyMap());
try {
loginModule.login();
fail("Should have thrown a UsernameNotFoundException exception");
} catch (LoginException ex) {
/* No-op */
}
// pat is found, but not an admin
testCallbackHandler = new TestCallbackHandler("pat");
loginModule.initialize(subject, testCallbackHandler, Collections.emptyMap(), Collections.emptyMap());
loginModule.logout();
loginModule.login();
loginModule.commit();
assertEquals(3, subject.getPrincipals().size());
assertTrue(loginModule.abort());
}
use of org.springframework.security.core.userdetails.UsernameNotFoundException in project pentaho-platform by pentaho.
the class UserRoleDaoUserDetailsServiceIT method testLoadUserByUsernameNoRoles.
@Test
public void testLoadUserByUsernameNoRoles() {
loginAsSysTenantAdmin();
ITenant mainTenant_1 = tenantManager.createTenant(systemTenant, MAIN_TENANT_1, tenantAdminRoleName, tenantAuthenticatedRoleName, ANONYMOUS_ROLE_NAME);
userRoleDao.createUser(mainTenant_1, USERNAME_ADMIN, PASSWORD, "", new String[] { tenantAdminRoleName });
login(USERNAME_ADMIN, mainTenant_1, new String[] { tenantAdminRoleName, tenantAuthenticatedRoleName });
IPentahoUser pentahoUser = userRoleDao.createUser(mainTenant_1, USER_2, PASSWORD_2, USER_DESCRIPTION_2, null);
UserRoleDaoUserDetailsService userDetailsService = new UserRoleDaoUserDetailsService();
userDetailsService.setUserRoleDao(userRoleDao);
try {
userDetailsService.loadUserByUsername(USER_2);
} catch (UsernameNotFoundException unnf) {
assertNotNull(unnf);
}
cleanupUserAndRoles(mainTenant_1);
}
Aggregations