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.mastercard.test.spring.security.WithMockUserSecurityContextFactory.java

public SecurityContext createSecurityContext(WithMockUser withUser) {
    String username = StringUtils.hasLength(withUser.username()) ? withUser.username() : withUser.value();
    if (username == null) {
        throw new IllegalArgumentException(
                withUser + " cannot have null username on both username and value properites");
    }/*  ww  w. j a va2s . co  m*/

    List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
    for (String authority : withUser.authorities()) {
        grantedAuthorities.add(new SimpleGrantedAuthority(authority));
    }

    if (grantedAuthorities.isEmpty()) {
        for (String role : withUser.roles()) {
            if (role.startsWith("ROLE_")) {
                throw new IllegalArgumentException("roles cannot start with ROLE_ Got " + role);
            }
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + role));
        }
    } else if (!(withUser.roles().length == 1 && "USER".equals(withUser.roles()[0]))) {
        throw new IllegalStateException("You cannot define roles attribute " + Arrays.asList(withUser.roles())
                + " with authorities attribute " + Arrays.asList(withUser.authorities()));
    }

    User principal = new User(username, withUser.password(), true, true, true, true, grantedAuthorities);
    Authentication authentication = new UsernamePasswordAuthenticationToken(principal, principal.getPassword(),
            principal.getAuthorities());
    SecurityContext context = SecurityContextHolder.createEmptyContext();
    context.setAuthentication(authentication);
    return context;
}

From source file:net.navasoft.madcoin.backend.services.security.ProviderEmailMapper.java

/**
 * Map row.//from   w ww . j  av a  2s. com
 * 
 * @param rs
 *            the rs
 * @param arg1
 *            the arg1
 * @return the user
 * @throws SQLException
 *             the SQL exception
 * @since 17/08/2014, 06:20:43 PM
 */
@Override
public User mapRow(ResultSet rs, int arg1) throws SQLException {
    String mail = rs.getString(USER_COLUMN);
    return new User(mail, rs.getString(PASSWORD_COLUMN), rs.getBoolean(ENABLED_COLUMN), true, true, true,
            getAuthorities(mail));
}

From source file:us.repasky.microblog.services.UserServiceImpl.java

/**
 * Hash the plain text password and create a new UserDetails instance that can be persisted.
 *///from ww w .ja va  2s  .  com
private UserDetails initializeUser(String username, String plainTextPassword) {
    String password = passwordEncoder.encode(plainTextPassword);
    return new User(username, password, ENABLED, ACCOUNT_NOT_EXPIRED, CREDENTIALS_NOT_EXPIRED,
            ACCOUNT_NOT_LOCKED, AUTHORITIES);
}

From source file:org.syncope.core.security.SyncopeUserDetailsService.java

@Override
public UserDetails loadUserByUsername(final String username)
        throws UsernameNotFoundException, DataAccessException {

    Set<SimpleGrantedAuthority> authorities = new HashSet<SimpleGrantedAuthority>();
    if (adminUser.equals(username)) {
        for (Entitlement entitlement : entitlementDAO.findAll()) {
            authorities.add(new SimpleGrantedAuthority(entitlement.getName()));
        }/*from  w w  w . j  a v a 2  s  .c  o m*/
    } else {
        final SyncopeUser user = userDAO.find(username);

        if (user == null) {
            throw new UsernameNotFoundException("Could not find any user with id " + username);
        }

        // Give entitlements based on roles owned by user,
        // considering role inheritance as well
        Set<SyncopeRole> roles = new HashSet<SyncopeRole>(user.getRoles());
        for (Long roleId : user.getRoleIds()) {
            roles.addAll(roleDAO.findChildren(roleId));
        }
        for (SyncopeRole role : roles) {
            for (Entitlement entitlement : role.getEntitlements()) {
                authorities.add(new SimpleGrantedAuthority(entitlement.getName()));
            }
        }
    }

    return new User(username, "<PASSWORD_PLACEHOLDER>", true, true, true, true, authorities);
}

From source file:net.navasoft.madcoin.backend.services.security.ProvidernameMapper.java

/**
 * Map row./*from w  w  w .j  av a  2 s .c o m*/
 * 
 * @param rs
 *            the rs
 * @param arg1
 *            the arg1
 * @return the user
 * @throws SQLException
 *             the SQL exception
 * @since 18/08/2014, 04:36:22 PM
 */
@Override
public User mapRow(ResultSet rs, int arg1) throws SQLException {
    String username = rs.getString(USER_COLUMN);
    return new User(username, rs.getString(PASSWORD_COLUMN), rs.getBoolean(ENABLED_COLUMN), true, true, true,
            getAuthorities(username));
}

From source file:org.socialsignin.springsocial.security.userdetails.SpringSocialSecurityUserDetailsService.java

/**
 * Uses a <code>SignUpService</code> implementation to check if a local user account for this username is available 
 * and if so, bases the user's authentication on the set of connections the user currently has to
 * 3rd party providers.  Allows provider-specific roles to be set for each user - uses a <code>UsersConnectionRepository</code>
 * to obtain list of connections the user has and a <code>SpringSocialSecurityAuthenticationFactory</code>
 * to obtain an authentication based on those connections.
 * //from w  w  w  .ja  v a2s .co  m
 */
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
    ConnectionRepository connectionRepository = usersConnectionRepository.createConnectionRepository(userName);
    SpringSocialProfile springSocialProfile = signUpService.getUserProfile(userName);
    List<Connection<?>> allConnections = getConnections(connectionRepository, userName);
    if (allConnections.size() > 0) {

        Authentication authentication = authenticationFactory.createAuthenticationForAllConnections(userName,
                springSocialProfile.getPassword(), allConnections);
        return new User(userName, authentication.getCredentials().toString(), true, true, true, true,
                authentication.getAuthorities());

    } else {
        throw new UsernameNotFoundException(userName);
    }

}

From source file:org.mitre.oauth2.service.impl.DefaultClientUserDetailsService.java

@Override
public UserDetails loadUserByUsername(String clientId) throws UsernameNotFoundException {

    try {/*from  w w w .  j  a  v  a 2  s  .c o  m*/
        ClientDetailsEntity client = clientDetailsService.loadClientByClientId(clientId);

        if (client != null) {

            String password = Strings.nullToEmpty(client.getClientSecret());

            if (config.isHeartMode() || // if we're running HEART mode turn off all client secrets
                    (client.getTokenEndpointAuthMethod() != null
                            && (client.getTokenEndpointAuthMethod().equals(AuthMethod.PRIVATE_KEY)
                                    || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT)))) {

                // Issue a random password each time to prevent password auth from being used (or skipped)
                // for private key or shared key clients, see #715

                password = new BigInteger(512, new SecureRandom()).toString(16);
            }

            boolean enabled = true;
            boolean accountNonExpired = true;
            boolean credentialsNonExpired = true;
            boolean accountNonLocked = true;
            Collection<GrantedAuthority> authorities = new HashSet<>(client.getAuthorities());
            authorities.add(ROLE_CLIENT);

            return new User(clientId, password, enabled, accountNonExpired, credentialsNonExpired,
                    accountNonLocked, authorities);
        } else {
            throw new UsernameNotFoundException("Client not found: " + clientId);
        }
    } catch (InvalidClientException e) {
        throw new UsernameNotFoundException("Client not found: " + clientId);
    }

}

From source file:com.inkubator.sms.gateway.service.impl.UserDetailsServiceImpl.java

@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS, isolation = Isolation.READ_COMMITTED, timeout = 30)
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException, DataAccessException {
    System.out.println("user detail service");
    if (userName == null || userName.trim().isEmpty()) {
        throw new UsernameNotFoundException("Empty username");
    }/*from  w  w w  . j  a  v  a  2s .  c  o  m*/

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Security verification for user '" + userName + "'");
    }
    SmsGatewayUser spiUser = this.userDao.getByUserIdOrEmail(userName);
    if (spiUser == null) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("User " + userName + " could not be found");
        }
        throw new UsernameNotFoundException("user " + userName + " could not be found");
    } else {
        System.out.println("ketemu kokk");
    }
    //        List<SpiRole> spiRoles = new ArrayList<>();
    List<String> dataRole = new ArrayList<>();
    for (UserRole spiUserRole : userRoleDao.getByUserId(spiUser.getId())) {
        //            spiRoles.add(spiUserRole.getSpiRole());
        dataRole.add(spiUserRole.getRole().getRoleName());
    }
    Collection<GrantedAuthority> grantedAuthorities = toGrantedAuthorities(dataRole);
    String password = spiUser.getPassword();
    Boolean isActive = Boolean.FALSE;
    Boolean isLock = Boolean.FALSE;
    Boolean isExired = Boolean.FALSE;

    if (spiUser.getIsActive() == 1) {
        isActive = Boolean.TRUE;
    }
    if (spiUser.getIsExpired() == 1) {
        isExired = Boolean.TRUE;
    }
    if (spiUser.getIsLock() == 1) {
        isLock = Boolean.TRUE;
    }
    //        for (SpiRole spiRole : spiRoles) {
    //            dataRole.add(spiRole.getRoleName());
    //        }
    return new User(userName, password, isActive, true, !isExired, !isLock, grantedAuthorities);
}

From source file:miage.ecom.web.security.AdminAuthenticationProvider.java

@Override
protected UserDetails retrieveUser(String login, UsernamePasswordAuthenticationToken upat)
        throws AuthenticationException {

    Admin admin = null;//from w  w  w.  j a  va2 s  . c  o  m
    UserDetails user = null;
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new GrantedAuthorityImpl("ROLE_ADMIN"));

    if (login != null) {
        admin = adminFacade.findByLogin(login);
    }

    if (admin == null) {
        throw new UsernameNotFoundException("Nom d'utilisateur ou mot de passe incorrect");
    }

    user = new User(admin.getLogin(), admin.getPassword(), true, true, true, true, authorities);

    return user;
}

From source file:miage.ecom.web.security.UserAuthenticationProvider.java

@Override
protected UserDetails retrieveUser(String login, UsernamePasswordAuthenticationToken upat)
        throws AuthenticationException {

    Customer customer = customerFacade.findByLogin(login);
    UserDetails user;//w  ww  .j a  va2  s.  c  o  m
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new GrantedAuthorityImpl("ROLE_USER"));

    if (customer == null) {
        throw new UsernameNotFoundException("Nom d'utilisateur ou mot de passe incorrect");
    }

    user = new User(customer.getLogin(), customer.getPassword(), true, true, true, true, authorities);

    return user;
}