Example usage for org.springframework.security.core.userdetails User User

List of usage examples for org.springframework.security.core.userdetails User User

Introduction

In this page you can find the example usage for org.springframework.security.core.userdetails User User.

Prototype

public User(String username, String password, boolean enabled, boolean accountNonExpired,
        boolean credentialsNonExpired, boolean accountNonLocked,
        Collection<? extends GrantedAuthority> authorities) 

Source Link

Document

Construct the User with the details required by org.springframework.security.authentication.dao.DaoAuthenticationProvider .

Usage

From source file:com.persistent.cloudninja.controller.AuthFilterUtils.java

/**
 * Creates a User object using tenantId and email address.
 * This is for identity provider which returns email address. 
 * /*from  w w w.  jav a 2  s  .  c o  m*/
 * @param tenantId
 * @param emailAddress
 * @return
 * @throws SystemException
 */
public static User createUserForIPUsingEmail(String tenantId, String emailAddress, String friendlyName)
        throws SystemException {
    User user = null;
    Member member = manageUsersDao.getMemberFromDb(tenantId, emailAddress);
    if (null != member) {
        String role = member.getRole();
        String userName = friendlyName;

        String userPassword = "";
        List<GrantedAuthority> userAuthorities = new ArrayList<GrantedAuthority>();
        userAuthorities.add(new GrantedAuthorityImpl(CloudNinjaConstants.ROLE_PREFIX + role));
        user = new User(userName, userPassword, true, true, true, true, userAuthorities);
    }
    return user;
}

From source file:com.persistent.cloudninja.controller.AuthFilterUtils.java

/**
 * Creates a User object using tenantId and GUID.
 * This is for identity provider which returns a GUID. 
 * /*from  w  w  w.  j  a v a 2 s. c  o m*/
 * @param tenantId
 * @param GUID
 * @return
 * @throws SystemException
 */
public static User createUserForIPUsingGUID(String tenantId, String GUID) throws SystemException {
    User user = null;
    Member member = manageUsersDao.getMemberFromDbUsingGUID(tenantId, GUID);
    if (null != member) {
        String role = member.getRole();
        String userName = member.getMemberCompoundKey().getMemberId();

        String userPassword = "";
        List<GrantedAuthority> userAuthorities = new ArrayList<GrantedAuthority>();
        userAuthorities.add(new GrantedAuthorityImpl(CloudNinjaConstants.ROLE_PREFIX + role));
        user = new User(userName, userPassword, true, true, true, true, userAuthorities);
    }
    return user;
}

From source file:org.syncope.core.scheduling.SyncJob.java

/**
 * Used to simulate authentication in order to perform updates through
 * AbstractUserWorkflowAdapter./*from w  w  w  .  j  a v a 2  s .  c  om*/
 */
private void setupSecurity() {
    final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

    for (Entitlement entitlement : entitlementDAO.findAll()) {
        authorities.add(new SimpleGrantedAuthority(entitlement.getName()));
    }

    final UserDetails userDetails = new User("admin", "FAKE_PASSWORD", true, true, true, true, authorities);

    SecurityContextHolder.getContext().setAuthentication(
            new UsernamePasswordAuthenticationToken(userDetails, "FAKE_PASSWORD", authorities));
}

From source file:org.ambraproject.wombat.config.SpringSecurityConfiguration.java

private AuthenticationUserDetailsService authenticationUserDetailsService() {
    return new AbstractCasAssertionUserDetailsService() {
        @Override/*from   w ww  .j a  v  a  2s  .  c  om*/
        protected UserDetails loadUserDetails(Assertion assertion) {
            final List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            return new User(assertion.getPrincipal().getName(), "NO_PASSWORD", true, true, true, true,
                    grantedAuthorities);
        }
    };
}

From source file:org.apache.ambari.server.security.authorization.AmbariLocalUserDetailsService.java

/**
 * Loads Spring Security UserDetails from identity storage according to Configuration
 *
 * @param username username//from  w w w .  ja  v a  2  s.com
 * @return UserDetails
 * @throws UsernameNotFoundException when user not found or have empty roles
 */
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    log.info("Loading user by name: " + username);

    UserEntity user = userDAO.findLocalUserByName(username);

    if (user == null || !StringUtils.equals(user.getUserName(), username)) {
        //TODO case insensitive name comparison is a temporary solution, until users API will change to use id as PK
        log.info("user not found ");
        throw new UsernameNotFoundException("Username " + username + " not found");
    }

    // get all of the privileges for the user
    List<PrincipalEntity> principalEntities = new LinkedList<PrincipalEntity>();

    principalEntities.add(user.getPrincipal());

    List<MemberEntity> memberEntities = memberDAO.findAllMembersByUser(user);

    for (MemberEntity memberEntity : memberEntities) {
        principalEntities.add(memberEntity.getGroup().getPrincipal());
    }

    List<PrivilegeEntity> privilegeEntities = privilegeDAO.findAllByPrincipal(principalEntities);

    return new User(user.getUserName(), user.getUserPassword(), user.getActive(), true, true, true,
            authorizationHelper.convertPrivilegesToAuthorities(privilegeEntities));
}

From source file:org.cloudfoundry.identity.uaa.authentication.manager.ExternalLoginAuthenticationManager.java

protected UaaUser getUser(Authentication request, ExternalAuthenticationDetails authDetails) {
    UserDetails userDetails;/*from   www .j  ava  2s.  co m*/
    if (request.getPrincipal() instanceof UserDetails) {
        userDetails = (UserDetails) request.getPrincipal();
    } else if (request instanceof UsernamePasswordAuthenticationToken) {
        String username = request.getPrincipal().toString();
        String password = request.getCredentials() != null ? request.getCredentials().toString() : "";
        userDetails = new User(username, password, true, true, true, true, UaaAuthority.USER_AUTHORITIES);
    } else if (request.getPrincipal() == null) {
        logger.debug(this.getClass().getName() + "[" + name + "] cannot process null principal");
        return null;
    } else {
        logger.debug(this.getClass().getName() + "[" + name + "] cannot process request of type: "
                + request.getClass().getName());
        return null;
    }

    String name = userDetails.getUsername();
    String email = null;

    if (userDetails instanceof Mailable) {
        email = ((Mailable) userDetails).getEmailAddress();

        if (name == null) {
            name = email;
        }
    }

    if (email == null) {
        email = generateEmailIfNull(name);
    }

    String givenName = null;
    String familyName = null;
    if (userDetails instanceof Named) {
        Named names = (Named) userDetails;
        givenName = names.getGivenName();
        familyName = names.getFamilyName();
    }

    String phoneNumber = (userDetails instanceof DialableByPhone)
            ? ((DialableByPhone) userDetails).getPhoneNumber()
            : null;
    String externalId = (userDetails instanceof ExternallyIdentifiable)
            ? ((ExternallyIdentifiable) userDetails).getExternalId()
            : name;

    UaaUserPrototype userPrototype = new UaaUserPrototype().withUsername(name).withPassword("").withEmail(email)
            .withAuthorities(UaaAuthority.USER_AUTHORITIES).withGivenName(givenName).withFamilyName(familyName)
            .withCreated(new Date()).withModified(new Date()).withOrigin(origin).withExternalId(externalId)
            .withZoneId(IdentityZoneHolder.get().getId()).withPhoneNumber(phoneNumber);

    return new UaaUser(userPrototype);
}

From source file:org.codelabor.system.userdetails.services.UserDetailsServiceImpl.java

@SuppressWarnings("unchecked")
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
    String queryId = null;/*from  www. j  av  a 2 s . co  m*/
    UserDetails userDetails = null;
    try {
        // get username, password
        queryId = "system.userdetails.select.users.by.username";
        Collection userMapCollection = queryService.find(queryId, new Object[] { username });
        if (userMapCollection.size() == 0) {
            throw new UsernameNotFoundException(queryId);
        }
        Map userMap = (Map) userMapCollection.toArray()[0];
        String password = (String) userMap.get("password");
        boolean enabled = ((BigDecimal) userMap.get("enabled")).intValue() == 1 ? true : false;

        // get authorities
        queryId = "system.userdetails.select.authorities.by.username";
        Collection authorityCollection = queryService.find(queryId, new Object[] { username });
        Iterator authorityIterator = authorityCollection.iterator();
        List authorityList = new ArrayList();
        while (authorityIterator.hasNext()) {
            Map authorityMap = (Map) authorityIterator.next();
            if (log.isDebugEnabled()) {
                StringBuilder sb = new StringBuilder();
                sb.append("authorityMap: ").append(authorityMap);
                log.debug(sb.toString());
            }
            GrantedAuthority authority = new GrantedAuthorityImpl((String) authorityMap.get("authority"));
            authorityList.add(authority);
        }

        // create user details
        userDetails = new User(username, password, enabled, true, true, true, authorityList);
    } catch (QueryServiceException e) {
        e.printStackTrace();
        throw new UnkownQueryServiceException(e.getMessage());
    }
    return userDetails;
}

From source file:org.fracturedatlas.athena.admin.AthenaAdmin.java

public static void main(String[] args) {

    Console c = System.console();
    if (c == null) {
        System.exit(1);/*from   ww w . jav  a 2 s .co m*/
    }

    Properties props = new Properties();
    ClassPathResource cpr = new ClassPathResource("admin.properties");
    try {
        InputStream in = cpr.getInputStream();
        props.load(in);
        in.close();
    } catch (Exception e) {
        c.format("Could not read properties file admin.properties\n");
        System.exit(1);
    }

    ApplicationContext context = new ClassPathXmlApplicationContext("security.xml");
    JdbcUserDetailsManager userDao = (JdbcUserDetailsManager) context.getBean("userDao");
    Md5PasswordEncoder encoder = (Md5PasswordEncoder) context.getBean("passwordEncoder");

    //TODO: Props file
    String realmName = props.getProperty("athena.admin.realm");

    if (args.length == 0) {
        System.out.println("USAGE: admin [command]");
        System.out.println("Where [command] is one of: create-user");
        System.exit(1);
    }

    Boolean usernameGood = false;
    String login = null;
    while (!usernameGood) {
        login = c.readLine("Enter new username: ");
        if (StringUtils.isBlank(login)) {
            c.format("username cannot be blank, please try again\n");
        } else {
            usernameGood = true;
        }
    }
    Boolean match = false;
    char[] password = null;
    char[] confirmedPassword = null;
    while (!match) {
        password = c.readPassword("Enter password: ");
        confirmedPassword = c.readPassword("Enter password again: ");
        match = Arrays.equals(password, confirmedPassword);
        if (!match) {
            c.format("Passwords do not match please try again\n");
        }
    }

    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new GrantedAuthorityImpl("ROLE_CLIENT_APPLICATION"));
    String clearPassword = new String(password);
    String saltedClearPassword = login + ":" + realmName + ":" + clearPassword;
    String encryptedPassword = encoder.encodePassword(saltedClearPassword, null);
    User user = new User(login, encryptedPassword, true, true, true, true, authorities);
    try {
        userDao.createUser(user);
    } catch (org.springframework.dao.DuplicateKeyException dke) {
        System.out.println("Username [" + user.getUsername() + "] already exists.");
        System.exit(1);
    }

    System.out.println("Successfully created [" + user.getUsername() + "]");
}

From source file:org.josso.spring.security.JOSSOUserDetailsService.java

/**
 * This addapts JOSSO user informatio to ACEGI user details.
 * <p/>//from w  w w.  ja v  a  2s .  co  m
 * Some SSO properties retrieved by JOSSO could be mapped to specific user detail information
 * like account disabled, by subclasses.
 */
protected UserDetails toUserDetails(SSOUser user, SSORole[] roles) {
    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    for (int i = 0; i < roles.length; i++) {
        SSORole role = roles[i];
        authorities.add(new SimpleGrantedAuthority(role.getName()));
    }

    UserDetails ud = new User(user.getName(), "NOT AVAILABLE UNDER JOSSO", true, true, true, true, authorities);

    return ud;
}

From source file:org.opencastproject.kernel.security.LtiLaunchAuthenticationHandler.java

/**
 * {@inheritDoc}/*from w w  w  .  j ava  2s  . c o  m*/
 * 
 * @see org.springframework.security.oauth.provider.OAuthAuthenticationHandler#createAuthentication(javax.servlet.http.HttpServletRequest,
 *      org.springframework.security.oauth.provider.ConsumerAuthentication,
 *      org.springframework.security.oauth.provider.token.OAuthAccessProviderToken)
 */
@Override
public Authentication createAuthentication(HttpServletRequest request, ConsumerAuthentication authentication,
        OAuthAccessProviderToken authToken) {
    // The User ID must be provided by the LTI consumer
    String userIdFromConsumer = request.getParameter(LTI_USER_ID_PARAM);

    if (StringUtils.isBlank(userIdFromConsumer)) {
        logger.warn("Received authentication request without user id ({})", LTI_USER_ID_PARAM);
        return null;
    }

    // Get the comser guid if provided
    String consumerGUID = request.getParameter(LTI_CONSUMER_GUID);
    //This is an optional field it could be blank
    if (StringUtils.isBlank(consumerGUID)) {
        consumerGUID = "UknownConsumer";
    }

    //We need to construct a complex ID to avoid confusion
    userIdFromConsumer = LTI_USER_ID_PREFIX + LTI_ID_DELIMITER + consumerGUID + LTI_ID_DELIMITER
            + userIdFromConsumer;

    //if this is a trusted consumer we trust their details
    String oaAuthKey = request.getParameter("oauth_consumer_key");
    if (highlyTrustedKeys.contains(oaAuthKey)) {
        logger.debug("{} is a trusted key", oaAuthKey);
        //If supplied we use the human readable name
        String suppliedEid = request.getParameter("lis_person_sourcedid");
        //This is an optional field it could be null
        if (suppliedEid != null) {
            userIdFromConsumer = suppliedEid;
        } else {
            //if no eid is set we use the supplied ID
            userIdFromConsumer = request.getParameter(LTI_USER_ID_PARAM);
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("LTI user id is : {}", userIdFromConsumer);
    }

    UserDetails userDetails = null;
    Collection<GrantedAuthority> userAuthorities = null;
    try {
        userDetails = userDetailsService.loadUserByUsername(userIdFromConsumer);
        userAuthorities = (Collection<GrantedAuthority>) userDetails.getAuthorities();
        //This list is potentially an modifiable collection
        userAuthorities = new HashSet<GrantedAuthority>(userAuthorities);
        //we still need to enrich this user with the LTI Roles
        String roles = request.getParameter(ROLES);
        String context = request.getParameter(CONTEXT_ID);
        enrichRoleGrants(roles, context, userAuthorities);
    } catch (UsernameNotFoundException e) {
        // This user is known to the tool consumer, but not to Matterhorn. Create a user "on the fly"
        userAuthorities = new HashSet<GrantedAuthority>();
        // We should add the authorities passed in from the tool consumer?
        userAuthorities.add(new GrantedAuthorityImpl("ROLE_ANONYMOUS"));
        String roles = request.getParameter(ROLES);
        String context = request.getParameter(CONTEXT_ID);
        enrichRoleGrants(roles, context, userAuthorities);
        //all users need the OATH ROLE, the user Role and the Anon Role
        userAuthorities.add(new GrantedAuthorityImpl(ROLE_OAUTH_USER));
        userAuthorities.add(new GrantedAuthorityImpl("ROLE_USER"));
        userAuthorities.add(new GrantedAuthorityImpl("ROLE_ANONYMOUS"));

        logger.info("Returning user with {} authorities", userAuthorities.size());

        userDetails = new User(userIdFromConsumer, "oauth", true, true, true, true, userAuthorities);
    }
    Authentication ltiAuth = new PreAuthenticatedAuthenticationToken(userDetails,
            authentication.getCredentials(), userAuthorities);
    SecurityContextHolder.getContext().setAuthentication(ltiAuth);
    return ltiAuth;
}