org.acegisecurity.userdetails.UserDetails Java Examples

The following examples show how to use org.acegisecurity.userdetails.UserDetails. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KualiCasAuthenticationProvider.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * This overridden method is differs from the super method by 
 * populating the user details by passing the full response
 * 
 * @see org.acegisecurity.providers.cas.CasAuthenticationProvider#authenticateNow(Authentication authentication)
 */
private CasAuthenticationToken authenticateNow(Authentication authentication) throws AuthenticationException {
    // Validate
    KualiTicketResponse response = (KualiTicketResponse)this.getTicketValidator().confirmTicketValid(authentication.getCredentials().toString());

    // Check proxy list is trusted
    this.getCasProxyDecider().confirmProxyListTrusted(response.getProxyList());
    if (logger.isDebugEnabled()) {
        logger.debug("authenticationNOW:" + response);
    }
    // Lookup user details      
    logger.debug("\n\npopulating authorities\n\n");
    UserDetails userDetails = ((KualiCasAuthoritiesPopulator)this.getCasAuthoritiesPopulator()).getUserDetails(response);        

    // Construct CasAuthenticationToken
    return new CasAuthenticationToken(this.getKey(), userDetails, authentication.getCredentials(),
        userDetails.getAuthorities(), userDetails, response.getProxyList(), response.getProxyGrantingTicketIou());
}
 
Example #2
Source File: SecurityService.java    From subsonic with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Locates the user based on the username.
 *
 * @param username The username presented to the {@link DaoAuthenticationProvider}
 * @return A fully populated user record (never <code>null</code>)
 * @throws UsernameNotFoundException if the user could not be found or the user has no GrantedAuthority.
 * @throws DataAccessException       If user could not be found for a repository-specific reason.
 */
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
    User user = getUserByName(username);
    if (user == null) {
        throw new UsernameNotFoundException("User \"" + username + "\" was not found.");
    }

    String[] roles = userDao.getRolesForUser(username);
    GrantedAuthority[] authorities = new GrantedAuthority[roles.length];
    for (int i = 0; i < roles.length; i++) {
        authorities[i] = new GrantedAuthorityImpl("ROLE_" + roles[i].toUpperCase());
    }

    // If user is LDAP authenticated, disable user. The proper authentication should in that case
    // be done by SubsonicLdapBindAuthenticator.
    boolean enabled = !user.isLdapAuthenticated();

    return new org.acegisecurity.userdetails.User(username, user.getPassword(), enabled, true, true, true, authorities);
}
 
Example #3
Source File: DebugDaoAuthenticationProvider.java    From webcurator with Apache License 2.0 6 votes vote down vote up
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    Object salt = null;

    System.out.println("User pwd: "+userDetails.getPassword());
    System.out.println("Auth pwd raw: "+authentication.getCredentials().toString());
    
    if (getSaltSource() != null) {
        salt = getSaltSource().getSalt(userDetails);
    }
    
    System.out.println("Auth pwd: "+getPasswordEncoder().encodePassword(authentication.getCredentials().toString().trim(), salt));
    
    System.out.println("Salt: "+salt);
    System.out.println("Encoder: "+getPasswordEncoder());

    if (!getPasswordEncoder().isPasswordValid(userDetails.getPassword(),
            authentication.getCredentials().toString(), salt)) {
        throw new BadCredentialsException(messages.getMessage(
                "AbstractUserDetailsAuthenticationProvider.badCredentials",
                "Bad credentials"), userDetails);
    }
}
 
Example #4
Source File: WCTDAOAuthenticationProvider.java    From webcurator with Apache License 2.0 6 votes vote down vote up
protected Object mapRow(ResultSet rs, int rownum)
    throws SQLException {
    String username = rs.getString(1);
    String password = rs.getString(2);
    boolean enabled = rs.getBoolean(3);
    boolean credentialsNonExpired = rs.getBoolean(4);
    
    if (password == null) {
        //set the password to blank for users authenticated by an external Authentication source
        password = "";
    }
    UserDetails user = new User(username, password, enabled, true,
            !credentialsNonExpired, true,
            new GrantedAuthority[] {new GrantedAuthorityImpl("HOLDER")});

    return user;
}
 
Example #5
Source File: DaoSupportImpl.java    From ramus with GNU General Public License v3.0 6 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username)
        throws UsernameNotFoundException, DataAccessException {
    com.ramussoft.net.common.User user = getUserFactory().getUser(username);

    if (user == null) {
        throw new UsernameNotFoundException(MessageFormat.format(
                "User {0} not found", username));
    }

    List<Group> list = user.getGroups();
    GrantedAuthority[] arrayAuths = new GrantedAuthority[list.size() + 1];
    for (int i = 0; i < list.size(); i++) {
        arrayAuths[i] = new GrantedAuthorityImpl("ROLE_"
                + list.get(i).getName().toUpperCase());
    }
    arrayAuths[list.size()] = new GrantedAuthorityImpl("ROLE_USER");

    return new User(user.getLogin(), user.getPassword(), true, true, true,
            true, arrayAuths);
}
 
Example #6
Source File: WCTDAOAuthenticationProvider.java    From webcurator with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
   public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
       List users = usersByUsernameMapping.execute(username);

       if (users.size() == 0) {
           throw new UsernameNotFoundException("User not found");
       }

       UserDetails user = (UserDetails) users.get(0); // contains no GrantedAuthority[]

       List dbAuths = authoritiesByUsernameMapping.execute(user.getUsername());

       if (dbAuths.size() == 0) {
           throw new UsernameNotFoundException("User has no GrantedAuthority");
       }

       GrantedAuthority[] arrayAuths = {};

       addCustomAuthorities(user.getUsername(), dbAuths);

       arrayAuths = (GrantedAuthority[]) dbAuths.toArray(arrayAuths);

       String returnUsername = user.getUsername();

       if (!isUsernameBasedPrimaryKey()) {
           returnUsername = username;
       }

       return new User(returnUsername, user.getPassword(), user.isEnabled(),
           true, true, true, arrayAuths);
   }
 
Example #7
Source File: LdapUserDetailsService.java    From rice with Educational Community License v2.0 5 votes vote down vote up
public UserDetails loadUserByUsername(String username)
{
    LdapUserDetails ldapUserDetails = ldapUserSearch.searchForUser(username);
    GrantedAuthority[] authorities = ldapAuthoritiesPopulator.getGrantedAuthorities(ldapUserDetails);

    return new User(username, "empty_password", true, true, true, true, authorities);
}
 
Example #8
Source File: KualiCasAuthoritiesPopulatorImpl.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * This overridden method is used to pass the Distributed Session 
 * Ticket around via the {@link KualiTicketResponse}
 * 
 * @see org.kuali.rice.kim.client.acegi.KualiCasAuthoritiesPopulator#getUserDetails(org.kuali.rice.kim.client.acegi.KualiTicketResponse)
 */
public UserDetails getUserDetails(KualiTicketResponse response) 
    throws AuthenticationException {
    if (logger.isDebugEnabled()) {
        logger.debug("getUserDetails(response)");
    }
    return this.userDetailsService.loadUserByTicketResponse(response);
}
 
Example #9
Source File: KualiCasAuthoritiesPopulatorImpl.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * This overridden method should never be used but is required by the 
 * UserDetails interface
 * 
 * @see org.acegisecurity.providers.cas.CasAuthoritiesPopulator#getUserDetails(java.lang.String)
 */
public UserDetails getUserDetails(String casUserId)
    throws AuthenticationException {
    if (logger.isDebugEnabled()) {
        logger.debug("getUserDetails(userID)");
    }
    return this.userDetailsService.loadUserByUsername(casUserId);
}
 
Example #10
Source File: KualiUserDetailsServiceImpl.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * This method is necessary for loading users by the ticket response
 * 
 * @param username
 * @param authorities
 * @return the UserDetails
 */
public UserDetails loadUserByUsernameAndAuthorities(String username, GrantedAuthority[] authorities) {
    if (logger.isDebugEnabled()) {
        logger.debug("loadUserByUsernameAndAuthorities");
    }
    GrantedAuthority[] newAuthorities = new GrantedAuthority[authorities.length+1];
    System.arraycopy(authorities, 0, newAuthorities, 0, authorities.length);
    newAuthorities[authorities.length]= new GrantedAuthorityImpl("ROLE_KUALI_USER");
    logger.warn("setting granted authorities:" + newAuthorities.toString());
    UserDetails user = new User(username, "empty_password", true, true, true, true, newAuthorities);    
    return user;
}
 
Example #11
Source File: KualiUserDetailsServiceImpl.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * This overridden method ...
 * 
 * @see org.acegisecurity.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
 */
public UserDetails loadUserByUsername(String username)
{
    if (logger.isDebugEnabled()) {
        logger.debug("loadUserByUsername");
    }
    return loadUserByUsernameAndAuthorities(username, new GrantedAuthority[0]);        
}
 
Example #12
Source File: KualiUserDetailsServiceImpl.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * This overridden method appends the Distributed Session Ticket to the
 * granted authorities
 * 
 * @see org.kuali.rice.kim.client.acegi.KualiUserDetailsService#loadUserByTicketResponse(org.kuali.rice.kim.client.acegi.KualiTicketResponse)
 */
public UserDetails loadUserByTicketResponse(KualiTicketResponse response) {
    GrantedAuthority[] authorities = new GrantedAuthority[1];
    authorities[0]= new GrantedAuthorityImpl(response.getDistributedSessionToken());
    if (logger.isDebugEnabled()) {
        logger.debug("loadUserByTicketResponse:" + response.getDistributedSessionToken());
    }
    return loadUserByUsernameAndAuthorities(response.getUser(), authorities); 
}
 
Example #13
Source File: DatadogSecurityListener.java    From jenkins-datadog-plugin with MIT License 5 votes vote down vote up
@Override
protected void authenticated(@Nonnull UserDetails details) {
    try {
        final boolean emitSystemEvents = DatadogUtilities.getDatadogGlobalDescriptor().isEmitSecurityEvents();
        if (!emitSystemEvents) {
            return;
        }
        logger.fine("Start DatadogSecurityListener#authenticated");

        // Get Datadog Client Instance
        DatadogClient client = ClientFactory.getClient();

        // Get the list of global tags to apply
        Map<String, Set<String>> tags = DatadogUtilities.getTagsFromGlobalTags();

        // Send event
        DatadogEvent event = new UserAuthenticationEventImpl(details.getUsername(),
                UserAuthenticationEventImpl.LOGIN, tags);
        client.event(event);

        // Submit counter
        String hostname = DatadogUtilities.getHostname("null");
        client.incrementCounter("jenkins.user.authenticated", hostname, tags);

        logger.fine("End DatadogSecurityListener#authenticated");
    } catch (Exception e) {
        logger.warning("Unexpected exception occurred - " + e.getMessage());
    }
}
 
Example #14
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,
        DataAccessException {
    List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
    auths.add(AUTHENTICATED_AUTHORITY);
    Set<String> groups = groupsByUser.get(username);
    if (groups != null) {
        for (String g : groups) {
            auths.add(new GrantedAuthorityImpl(g));
        }
    }
    return new org.acegisecurity.userdetails.User(username,"",true,true,true,true, auths.toArray(new GrantedAuthority[0]));
}
 
Example #15
Source File: OicSecurityRealm.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
@Override
public SecurityComponents createSecurityComponents() {
    return new SecurityComponents(
            new AuthenticationManager() {
                public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                    if (authentication instanceof AnonymousAuthenticationToken)
                        return authentication;
                    throw new BadCredentialsException("Unexpected authentication type: " + authentication);
                }
            },
            new UserDetailsService() {
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
		// Retrieve the OicUserProperty to get the list of groups that has to be set in the OicUserDetails object.
		LOGGER.fine("loadUserByUsername in createSecurityComponents called, username: " + username);
		User u = User.get(username, false, Collections.emptyMap());
		if (u == null) {
			LOGGER.fine("loadUserByUsername in createSecurityComponents called, no user '" + username + "' found");
			throw new UsernameNotFoundException(username);
		}
		LOGGER.fine("loadUserByUsername in createSecurityComponents called, user: " + u);
		List<UserProperty> props = u.getAllProperties();
		LOGGER.fine("loadUserByUsername in createSecurityComponents called, number of props: " + props.size());
		GrantedAuthority[] auths = new GrantedAuthority[0];
		for (UserProperty prop: props) {
			LOGGER.fine("loadUserByUsername in createSecurityComponents called, prop of type: " + prop.getClass().toString());
			if (prop instanceof OicUserProperty) {
				OicUserProperty oicProp = (OicUserProperty) prop;
				LOGGER.fine("loadUserByUsername in createSecurityComponents called, oic prop found with username: " + oicProp.getUserName());
				auths = oicProp.getAuthoritiesAsGrantedAuthorities();
				LOGGER.fine("loadUserByUsername in createSecurityComponents called, oic prop with auths size: " + auths.length);
			}
		}
		return new OicUserDetails(username, auths);
	}
}
    );
}
 
Example #16
Source File: GitLabSecurityRealm.java    From gitlab-oauth-plugin with MIT License 5 votes vote down vote up
@Override
public SecurityComponents createSecurityComponents() {
    return new SecurityComponents(new AuthenticationManager() {

        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {
            if (authentication instanceof GitLabAuthenticationToken) {
                return authentication;
            }
            if (authentication instanceof UsernamePasswordAuthenticationToken) {
                try {
                    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
                    GitLabAuthenticationToken gitlab = new GitLabAuthenticationToken(token.getCredentials().toString(), getGitlabApiUri(), TokenType.PRIVATE_TOKEN);
                    SecurityContextHolder.getContext().setAuthentication(gitlab);
                    return gitlab;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            throw new BadCredentialsException("Unexpected authentication type: " + authentication);
        }
    }, new UserDetailsService() {
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
            return GitLabSecurityRealm.this.loadUserByUsername(username);
        }
    });
}
 
Example #17
Source File: Listener.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,
        DataAccessException {
    List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
    auths.add(AUTHENTICATED_AUTHORITY);
    Set<String> groups = groupsByUser.get(username);
    if (groups != null) {
        for (String g : groups) {
            auths.add(new GrantedAuthorityImpl(g));
        }
    }
    return new org.acegisecurity.userdetails.User(username,"",true,true,true,true, auths.toArray(new GrantedAuthority[auths.size()]));
}
 
Example #18
Source File: JwtTokenVerifierImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
public JwtAuthentication(String subject) {
    User user = User.get(subject, false, Collections.emptyMap());
    if (user == null) {
        throw new ServiceException.UnauthorizedException("Invalid JWT token: subject " + subject + " not found");
    }
    //TODO: UserDetails call is expensive, encode it in token and create UserDetails from it
    UserDetails d = Jenkins.getInstance().getSecurityRealm().loadUserByUsername(user.getId());
    this.grantedAuthorities = d.getAuthorities();
    this.name = subject;
    super.setAuthenticated(true);
}
 
Example #19
Source File: JenkinsRule.java    From jenkins-test-harness with MIT License 4 votes vote down vote up
@Override
protected UserDetails authenticate(String username, String password) throws AuthenticationException {
    if (username.equals(password))
        return loadUserByUsername(username);
    throw new BadCredentialsException(username);
}
 
Example #20
Source File: UserDetailsServiceBasedAuthoritiesPopulator.java    From subsonic with GNU General Public License v3.0 4 votes vote down vote up
public GrantedAuthority[] getGrantedAuthorities(LdapUserDetails userDetails) throws LdapDataAccessException {
    UserDetails details = userDetailsService.loadUserByUsername(userDetails.getUsername());
    return details.getAuthorities();
}
 
Example #21
Source File: Listener.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Override
protected UserDetails authenticate(String username, String password) throws AuthenticationException {
    if (username.equals(password))
        return loadUserByUsername(username);
    throw new BadCredentialsException(username);
}
 
Example #22
Source File: PipelineBaseTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
protected User login(String userId, String fullName, String email) throws IOException {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());

    hudson.model.User bob = User.get(userId);

    bob.setFullName(fullName);
    if(email != null ) {
        bob.addProperty(new Mailer.UserProperty(email));
    }


    UserDetails d = Jenkins.getInstance().getSecurityRealm().loadUserByUsername(bob.getId());

    SecurityContextHolder.getContext().setAuthentication(new PrincipalAcegiUserToken(bob.getId(),bob.getId(),bob.getId(), d.getAuthorities(), bob.getId()));
    return bob;
}
 
Example #23
Source File: ProfileApiTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
@Test
public void testPermissionOfOtherUser() throws IOException {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());

    hudson.model.User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));


    hudson.model.User bob = User.get("bob");
    bob.setFullName("Bob Cooper");
    bob.addProperty(new Mailer.UserProperty("[email protected]"));

    UserDetails d = Jenkins.getInstance().getSecurityRealm().loadUserByUsername(bob.getId());

    SecurityContextHolder.getContext().setAuthentication(new PrincipalAcegiUserToken(bob.getId(),bob.getId(),bob.getId(), d.getAuthorities(), bob.getId()));

    Assert.assertNull(new UserImpl(Iterables.getFirst(OrganizationFactory.getInstance().list(), null), alice).getPermission());
}
 
Example #24
Source File: BaseTest.java    From blueocean-plugin with MIT License 3 votes vote down vote up
protected User login(String userId, String fullName, String email) throws IOException {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());

    hudson.model.User bob = User.get(userId);

    bob.setFullName(fullName);
    bob.addProperty(new Mailer.UserProperty(email));


    UserDetails d = Jenkins.getInstance().getSecurityRealm().loadUserByUsername(bob.getId());

    SecurityContextHolder.getContext().setAuthentication(new PrincipalAcegiUserToken(bob.getId(),bob.getId(),bob.getId(), d.getAuthorities(), bob.getId()));
    return bob;
}
 
Example #25
Source File: KualiCasAuthoritiesPopulator.java    From rice with Educational Community License v2.0 2 votes vote down vote up
/**
 * Obtains the granted authorities for the specified user.<P>May throw any
 * <code>AuthenticationException</code> or return <code>null</code> if the authorities are unavailable.</p>
 *
 * @param casUserId as obtained from the CAS validation service
 *
 * @return the details of the indicated user (at minimum the granted authorities and the username)
 *
 * @throws AuthenticationException DOCUMENT ME!
 */
UserDetails getUserDetails(KualiTicketResponse response)
    throws AuthenticationException;
 
Example #26
Source File: KualiUserDetailsService.java    From rice with Educational Community License v2.0 2 votes vote down vote up
/**
 * Locates the user based on the response. In the actual implementation, the search may possibly be case
 * insensitive, or case insensitive depending on how the implementaion instance is configured. In this case, the
 * <code>UserDetails</code> object that comes back may have a username that is of a different case than what was
 * actually requested.  Also populates the <code>Authentication Source</code> as a <code>GrantedAuthority</code>
 *
 * @param response the reponse from the TicketValidator presented to the {@link DaoAuthenticationProvider}
 *
 * @return a fully populated user record (never <code>null</code>)
 *
 * @throws UsernameNotFoundException if the user could not be found or the user has no GrantedAuthority
 * @throws DataAccessException if user could not be found for a repository-specific reason
 */
UserDetails loadUserByTicketResponse(KualiTicketResponse response)
    throws UsernameNotFoundException, DataAccessException;