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

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

Introduction

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

Prototype

public String getUsername() 

Source Link

Usage

From source file:org.schedoscope.metascope.service.MetascopeUserService.java

/**
 * Get the user object for the logged in user
 *
 * @return//w  w w  .ja v a2s  .c o m
 * @throws NamingException
 */
public MetascopeUser getUser() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null) {
        return null;
    }

    Object principal = authentication.getPrincipal();

    if (principal instanceof LdapUserDetailsImpl) {
        LdapUserDetailsImpl ldapUser = (LdapUserDetailsImpl) principal;
        MetascopeUser userEntity = metascopeUserRepository.findByUsername(ldapUser.getUsername());
        if (userEntity == null) {
            createUser(ldapUser.getUsername(), "", "", sha256("" + System.currentTimeMillis()), false, null);
        }

        // sync user with ldap
        userEntity = metascopeUserRepository.findByUsername(ldapUser.getUsername());
        DirContextAdapter dca = (DirContextAdapter) ldap.lookup(ldapUser.getDn());
        Attributes attr = dca.getAttributes();
        String mail = "";
        String fullname = "";
        try {
            mail = (String) attr.get("mail").get();
            fullname = (String) attr.get("displayName").get();
        } catch (NamingException e) {
            // if not found, ignore ..
        }
        boolean admin = false;
        for (GrantedAuthority authoritiy : ldapUser.getAuthorities()) {
            for (String adminGroup : config.getAdminGroups().split(",")) {
                String role = "ROLE_" + adminGroup.toUpperCase();
                if (authoritiy.getAuthority().equalsIgnoreCase(role)) {
                    admin = true;
                }
            }
        }

        boolean changes = false;
        if (userEntity.getEmail() == null || !userEntity.getEmail().equals(mail)) {
            userEntity.setEmail(mail);
            changes = true;
        }
        if (userEntity.getFullname() == null || !userEntity.getFullname().equals(fullname)) {
            userEntity.setFullname(fullname);
            changes = true;
        }

        if (admin) {
            if (!userEntity.isAdmin()) {
                changes = true;
            }
            userEntity.setUserrole(Role.ROLE_ADMIN);
        } else {
            if (userEntity.isAdmin()) {
                changes = true;
            }
            userEntity.setUserrole(Role.ROLE_USER);
        }

        if (changes) {
            metascopeUserRepository.save(userEntity);
        }
        return userEntity;
    } else if (principal instanceof User) {
        User userDetails = (User) principal;
        MetascopeUser user = metascopeUserRepository.findByUsername(userDetails.getUsername());

        if (user == null) {
            LOG.warn("User from session not found. username={}", userDetails.getUsername());
            return null;
        }

        return user;
    }

    return null;
}

From source file:org.sharetask.service.AuthenticationServiceTest.java

@Test
public void testPasswordEncoding() throws NoSuchAlgorithmException, NoSuchProviderException {
    final ArrayList<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
    list.add(new SimpleGrantedAuthority(Role.ROLE_USER.name()));
    list.add(new SimpleGrantedAuthority(Role.ROLE_ADMINISTRATOR.name()));
    final User u = new UserDetailsImpl("dev1@shareta.sk", "password",
            "6ef7a5723d302c64d65d02f5c6662dc61bebec930ea300620bc9ff7f12b49fda11e2e57933526fd3b73840b0693a7cf4abe05fbfe16223d4bd42eb3043cf5d24",
            list);/*from www  .  j  a  va  2s  .co  m*/
    final String password = passwordEncoder.encodePassword("password", saltSource.getSalt(u));
    final org.sharetask.entity.UserAuthentication user = userRepository.findOne(u.getUsername());
    assertEquals(password, user.getPassword());
    final Authentication authentication = new UsernamePasswordAuthenticationToken("dev1@shareta.sk",
            "password");
    try {
        authenticationManager.authenticate(authentication);
    } catch (final BadCredentialsException e) {
        fail("Problem with authentication: user/password");
    }
}

From source file:fr.xebia.springframework.security.core.userdetails.jdbc.ExtendedJdbcUserDetailsManager.java

@Override
protected UserDetails createUserDetails(String username, UserDetails userFromUserQuery,
        List<GrantedAuthority> combinedAuthorities) {
    final User user = (User) super.createUserDetails(username, userFromUserQuery, combinedAuthorities);
    List<UserDetails> users = getJdbcTemplate().query(selectUserExtraColumns, new String[] { username },
            new RowMapper<UserDetails>() {
                public UserDetails mapRow(ResultSet rs, int rowNum) throws SQLException {
                    ExtendedUser extendedUser = new ExtendedUser(user.getUsername(), user.getPassword(),
                            user.isEnabled(), user.isAccountNonExpired(), user.isCredentialsNonExpired(),
                            user.isAccountNonLocked(), user.getAuthorities());
                    extendedUser.setAllowedRemoteAddresses(rs.getString(1));
                    extendedUser.setComments(rs.getString(2));

                    return extendedUser;
                }/*from   www. j  av  a  2  s .c  o  m*/
            });
    if (users.size() == 0) {
        throw new UsernameNotFoundException(messages.getMessage("JdbcDaoImpl.notFound",
                new Object[] { username }, "Username {0} not found"), username);
    }
    return users.get(0);
}

From source file:com.persistent.cloudninja.web.security.CloudNinjaUserDetailsService.java

public String createCookieValueFromUser(User user) {
    Collection<GrantedAuthority> authorities = user.getAuthorities();
    int size = authorities.size();

    String role = "";
    StringBuffer sb = new StringBuffer();
    int i = -1;//from  ww  w .ja  v a  2  s  .c  o m

    for (GrantedAuthority grantedAuthority : authorities) {
        role = grantedAuthority.getAuthority();
        i = i + 1;
        if (i == 0 & size > 1) {
            role = role + ",";
        }
        sb.append(role);
    }
    String newCookieValue = user.getUsername() + "!" + sb.toString();
    return newCookieValue;
}

From source file:com.evidence.service.UserServiceTest.java

@Test
public void testCreateUser() {
    UserDTO userDTO = new UserDTO();
    String name = String.valueOf(System.currentTimeMillis()) + "@test.test";
    userDTO.setUserName(name);/*from   ww w  .jav a 2s.  c  o  m*/
    userDTO.setName("Test");
    userDTO.setPassword("password");
    userDTO.setSurName("Test Surname");
    userDTO.setTenantId(1L);
    try {
        userService.create(userDTO);
    } catch (TenantAlreadyExists e) {
        fail("Tenant " + userDTO.getTenantName() + " already exists!");
    } catch (UserAlreadyExists e) {
        fail("User " + userDTO.getUserName() + " already exists!");
    }

    com.tapas.evidence.entity.user.User user = userRepository.findByUsername(name);
    assertEquals(user.getEmail(), userDTO.getUserName());
    assertEquals(user.getName(), userDTO.getName());
    String password = passwordEncoder.encodePassword("password",
            saltSource.getSalt(new EvidenceUser(name, "password", new ArrayList<GrantedAuthority>())));
    assertEquals(user.getPassword(), password);
    assertEquals(user.getSurName(), userDTO.getSurName());
    assertEquals(user.getUsername(), userDTO.getUserName());
    assertTrue(user.getRoles().size() == 1);
}

From source file:com.orchestra.portale.externalauth.FbAuthenticationManager.java

public static User fbLoginJs(HttpServletRequest request, HttpServletResponse response,
        UserRepository userRepository) {

    //Get access_token from request
    String access_token = request.getParameter("access_token");
    User user = null;// www .  j  a  v  a2 s .c o  m

    if (StringUtils.isNotEmpty(access_token)) {

        try {

            Boolean validity = FacebookUtils.ifTokenValid(access_token);

            //if token is valid, retrieve userid and email from Facebook
            if (validity) {
                Map<String, String> userId_mail = FacebookUtils.getUserIDMail(access_token);
                String id = userId_mail.get("id");
                String email = userId_mail.get("email");

                try {
                    user = fbUserCheck(id, email, userRepository);
                } catch (UserNotFoundException ioex) {
                    /*Retrieve User Data to Registration*/
                    Map<String, String> userData = FacebookUtils.getUserData(access_token);

                    /*Create User*/
                    com.orchestra.portale.persistence.sql.entities.User new_user = new com.orchestra.portale.persistence.sql.entities.User();
                    new_user.setFbEmail(userData.get("email"));
                    new_user.setFbUser(userData.get("id"));
                    new_user.setUsername(userData.get("email"));
                    new_user.setFirstName(userData.get("firstName"));
                    new_user.setLastName(userData.get("lastName"));
                    new_user.setPassword(new BigInteger(130, new SecureRandom()).toString(32));

                    /*Create Role*/
                    com.orchestra.portale.persistence.sql.entities.Role new_user_role = new com.orchestra.portale.persistence.sql.entities.Role();
                    new_user_role.setRole("ROLE_USER");
                    new_user_role.setUser(new_user);
                    ArrayList<com.orchestra.portale.persistence.sql.entities.Role> new_user_roles = new ArrayList<com.orchestra.portale.persistence.sql.entities.Role>();
                    new_user_roles.add(new_user_role);
                    new_user.setRoles(new_user_roles);

                    /*Save User*/
                    userRepository.save(new_user);

                    //Save user image
                    try {
                        String img_url = userData.get("img");
                        String user_id_img = userRepository.findByUsername(new_user.getUsername()).getId()
                                .toString();

                        HttpSession session = request.getSession();
                        ServletContext sc = session.getServletContext();

                        String destination = sc.getRealPath("/") + "dist" + File.separator + "user"
                                + File.separator + "img" + File.separator + user_id_img + File.separator;

                        NetworkUtils.saveImageFromURL(img_url, destination, "avatar.jpg");

                    } catch (MalformedURLException ex) {
                        throw new FacebookException();
                    } catch (IOException ioexc) {
                        ioexc.getMessage();
                    }

                    /*Create Spring User*/
                    boolean enabled = true;
                    boolean accountNonExpired = true;
                    boolean credentialsNonExpired = true;
                    boolean accountNonLocked = true;

                    user = new User(new_user.getUsername(), new_user.getPassword().toLowerCase(), enabled,
                            accountNonExpired, credentialsNonExpired, accountNonLocked,
                            getAuthorities(new_user.getRoles()));

                }

            }

        } catch (FacebookException ioex) {
            ioex.printStackTrace();
        }

    }

    return user;
}

From source file:com.blstream.patronage.ctf.security.RestUserDetailsService.java

private User prepareUser(final PortalUser portalUser) {
    User user;

    if (logger.isDebugEnabled()) {
        logger.debug("---- prepareUser");
    }/*from w ww . j  a  v  a 2 s.  c  o  m*/

    user = new User(portalUser.getUsername(), portalUser.getPassword(), portalUser.isEnabled(),
            portalUser.isAccountNonExpired(), portalUser.isCredentialsNonExpired(),
            portalUser.isAccountNonLocked(), portalUser.getRoles());

    if (logger.isInfoEnabled()) {
        logger.info(String.format(
                "Security user was prepared: "
                        + "[username: %s, password: *************, isEnabled: %s, isAccountNonExpired: %s, "
                        + "isCredentialsNonExpired: %s, isAccountNonLocked: %s, roles: %s]",
                user.getUsername(), user.isAccountNonExpired(), user.isCredentialsNonExpired(),
                user.isAccountNonExpired(), user.isAccountNonLocked(), user.getAuthorities()));
    }

    return user;
}

From source file:com.blstream.patronage.ctf.security.PasswordEncoderService.java

/**
 * Prepares security user object based on portal user instance.
 * @param portalUser/*from  w  w w  .  j  a  v a 2  s  .  c om*/
 * @return User
 */
private User prepareUser(final PortalUser portalUser) {
    User user;

    if (logger.isDebugEnabled()) {
        logger.debug("---- prepareUser");
    }

    user = new User(portalUser.getUsername(), portalUser.getPassword(), portalUser.isEnabled(),
            portalUser.isAccountNonExpired(), portalUser.isCredentialsNonExpired(),
            portalUser.isAccountNonLocked(), portalUser.getRoles());

    if (logger.isInfoEnabled()) {
        logger.info(String.format(
                "Security user was prepared: "
                        + "[username: %s, password: *************, isEnabled: %s, isAccountNonExpired: %s, "
                        + "isCredentialsNonExpired: %s, isAccountNonLocked: %s, roles: %s]",
                user.getUsername(), user.isAccountNonExpired(), user.isCredentialsNonExpired(),
                user.isAccountNonExpired(), user.isAccountNonLocked(), user.getAuthorities()));
    }

    return user;
}

From source file:org.apigw.authserver.svc.impl.TokenServicesImpl.java

@Override
@Transactional(propagation = Propagation.REQUIRED)
public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {
    try {//from  w  ww .ja  va  2 s. com
        User user = (User) authentication.getPrincipal();
        String logsafeSSN = citizenLoggingUtil.getLogsafeSSN(user.getUsername());
        log.debug("createAccessToken authentication:{}", logsafeSSN);
    } catch (ClassCastException ignored) {
    }

    String authenticationKey = authenticationKeyGenerator.extractKey(authentication);
    log.debug("createAccessToken -> authenticationKey:{}", authenticationKey);
    AuthorizationGrant grant = authorizationGrantRepository.findByAuthenticationKey(authenticationKey);

    ExpiringOAuth2RefreshToken refreshToken = null;
    if (grant != null && isExpired(grant.getAccessTokenExpires())) { // Timestamp
        if (supportRefreshToken) {
            refreshToken = new DefaultExpiringOAuth2RefreshToken(grant.getRefreshToken(),
                    grant.getGrantExpires());
        }
    } else {
        // grant is either null, or unexpired
        refreshToken = buildRefreshToken(authentication);
    }
    grant = buildAuthorizationGrant(grant, refreshToken, authentication);
    grant = authorizationGrantRepository.save(grant);
    OAuth2AccessToken token = buildAccessTokenFromAuthorizationGrant(grant, false);
    log.debug("Returning from createAccessToken");
    return token;
}