Search in sources :

Example 11 with UsernameNotFoundException

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);
    }
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) IncorrectResultSizeDataAccessException(org.springframework.dao.IncorrectResultSizeDataAccessException) SearchControls(javax.naming.directory.SearchControls)

Example 12 with 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;
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UserDetails(org.springframework.security.core.userdetails.UserDetails) User(org.springframework.security.core.userdetails.User) Authentication(org.springframework.security.core.Authentication) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority)

Example 13 with UsernameNotFoundException

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 */
    }
}
Also used : AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) IAuthorizationPolicy(org.pentaho.platform.api.engine.IAuthorizationPolicy) Authentication(org.springframework.security.core.Authentication) Collection(java.util.Collection) LoginException(javax.security.auth.login.LoginException) IUserRoleListService(org.pentaho.platform.api.engine.IUserRoleListService) Subject(javax.security.auth.Subject) Test(org.junit.Test)

Example 14 with UsernameNotFoundException

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());
}
Also used : AuthenticationManager(org.springframework.security.authentication.AuthenticationManager) UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) IAuthorizationPolicy(org.pentaho.platform.api.engine.IAuthorizationPolicy) Authentication(org.springframework.security.core.Authentication) Collection(java.util.Collection) LoginException(javax.security.auth.login.LoginException) IUserRoleListService(org.pentaho.platform.api.engine.IUserRoleListService) Subject(javax.security.auth.Subject) Test(org.junit.Test)

Example 15 with UsernameNotFoundException

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);
}
Also used : UsernameNotFoundException(org.springframework.security.core.userdetails.UsernameNotFoundException) ITenant(org.pentaho.platform.api.mt.ITenant) UserRoleDaoUserDetailsService(org.pentaho.platform.security.userroledao.service.UserRoleDaoUserDetailsService) IPentahoUser(org.pentaho.platform.api.engine.security.userroledao.IPentahoUser) Test(org.junit.Test)

Aggregations

UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)132 GrantedAuthority (org.springframework.security.core.GrantedAuthority)40 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)39 UserDetails (org.springframework.security.core.userdetails.UserDetails)36 Authentication (org.springframework.security.core.Authentication)24 Transactional (org.springframework.transaction.annotation.Transactional)20 Logger (org.slf4j.Logger)18 LoggerFactory (org.slf4j.LoggerFactory)18 java.util (java.util)16 BadCredentialsException (org.springframework.security.authentication.BadCredentialsException)15 Collectors (java.util.stream.Collectors)14 UserDetailsService (org.springframework.security.core.userdetails.UserDetailsService)14 Component (org.springframework.stereotype.Component)14 User (org.springframework.security.core.userdetails.User)13 ArrayList (java.util.ArrayList)12 HashSet (java.util.HashSet)11 UserRepository (io.github.jhipster.sample.repository.UserRepository)9 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)9 User (io.github.jhipster.sample.domain.User)6 Date (java.util.Date)6