Example usage for org.springframework.security.core.userdetails UserDetails isAccountNonExpired

List of usage examples for org.springframework.security.core.userdetails UserDetails isAccountNonExpired

Introduction

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

Prototype

boolean isAccountNonExpired();

Source Link

Document

Indicates whether the user's account has expired.

Usage

From source file:ch.silviowangler.dox.security.DoxUserDetailServiceTest.java

@Test
public void testLoadUserByUsername() throws Exception {

    DoxUser user = new DoxUser("silvio.wangler@email.ch", "a password", "silvio");
    when(repository.findByUsername("silvio")).thenReturn(user);

    UserDetails userDetails = userDetailService.loadUserByUsername("silvio");

    verify(repository).findByUsername("silvio");

    assertThat(userDetails, notNullValue());
    assertThat(userDetails.getUsername(), equalTo("silvio"));
    assertThat(userDetails.getPassword(), equalTo("a password"));
    assertThat(userDetails.isAccountNonExpired(), is(true));
    assertThat(userDetails.isAccountNonLocked(), is(true));
    assertThat(userDetails.isCredentialsNonExpired(), is(true));
    assertThat(userDetails.isEnabled(), is(true));
    assertThat(userDetails.getAuthorities().size(), is(equalTo(0)));
}

From source file:ch.silviowangler.dox.security.DoxUserDetailServiceTest.java

@Test
@SuppressWarnings("unchecked")
public void testLoadUserByUsernameWithGrantedAuthorities() throws Exception {

    DoxUser user = new DoxUser("silvio.wangler@email.ch", "a password", "silvio");

    Role roleAdmin = new Role("ADMIN");
    roleAdmin.getGrantedAuthorities().add(new GrantedAuthority("delete"));
    roleAdmin.getGrantedAuthorities().add(new GrantedAuthority("create"));
    roleAdmin.getGrantedAuthorities().add(new GrantedAuthority("update"));

    Role roleUser = new Role("USER");
    roleUser.getGrantedAuthorities().add(new GrantedAuthority("read"));
    user.getRoles().add(roleAdmin);/*w  w  w.  j  a v a  2 s. co  m*/
    user.getRoles().add(roleUser);

    when(repository.findByUsername("silvio")).thenReturn(user);

    UserDetails userDetails = userDetailService.loadUserByUsername("silvio");

    verify(repository).findByUsername("silvio");

    assertThat(userDetails, notNullValue());
    assertThat(userDetails.getUsername(), equalTo("silvio"));
    assertThat(userDetails.getPassword(), equalTo("a password"));
    assertThat(userDetails.isAccountNonExpired(), is(true));
    assertThat(userDetails.isAccountNonLocked(), is(true));
    assertThat(userDetails.isCredentialsNonExpired(), is(true));
    assertThat(userDetails.isEnabled(), is(true));
    assertThat(userDetails.getAuthorities().size(), is(equalTo(6)));
    assertThat((Iterable<SimpleGrantedAuthority>) userDetails.getAuthorities(),
            hasItems(new SimpleGrantedAuthority("read"), new SimpleGrantedAuthority("create"),
                    new SimpleGrantedAuthority("update"), new SimpleGrantedAuthority("delete"),
                    new SimpleGrantedAuthority("ROLE_USER"), new SimpleGrantedAuthority("ROLE_ADMIN")));
}

From source file:cn.net.withub.demo.bootsec.hello.security.CustomAuthenticationProvider.java

@Transactional
@Override//from   www . ja va 2s . c om
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String username = token.getName(); //???
    //?
    UserDetails userDetails = null;
    if (username != null) {
        userDetails = userDetailsService.loadUserByUsername(username);
    }

    if (userDetails == null) {
        return null;//null??
        //throw new UsernameNotFoundException("??/?");
    } else if (!userDetails.isEnabled()) {
        throw new DisabledException("?");
    } else if (!userDetails.isAccountNonExpired()) {
        throw new AccountExpiredException("?");
    } else if (!userDetails.isAccountNonLocked()) {
        throw new LockedException("??");
    } else if (!userDetails.isCredentialsNonExpired()) {
        throw new LockedException("?");
    }

    //??
    String encPass = userDetails.getPassword();

    //authentication?credentials
    if (!md5PasswordEncoder.isPasswordValid(encPass, token.getCredentials().toString(), null)) {
        throw new BadCredentialsException("Invalid username/password");
    }

    //?
    return new UsernamePasswordAuthenticationToken(userDetails, encPass, userDetails.getAuthorities());
}

From source file:grails.plugin.springsecurity.userdetails.DefaultPreAuthenticationChecks.java

public void check(UserDetails user) {
    if (!user.isAccountNonLocked()) {
        log.debug("User account is locked");

        throw new LockedException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked",
                "User account is locked"));
    }/*from  ww w.ja  va  2s.  c o  m*/

    if (!user.isEnabled()) {
        log.debug("User account is disabled");

        throw new DisabledException(
                messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"));
    }

    if (!user.isAccountNonExpired()) {
        log.debug("User account is expired");

        throw new AccountExpiredException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired"));
    }
}

From source file:org.codehaus.groovy.grails.plugins.springsecurity.DefaultPreAuthenticationChecks.java

public void check(UserDetails user) {
    if (!user.isAccountNonLocked()) {
        log.debug("User account is locked");

        throw new LockedException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked",
                "User account is locked"), user);
    }//from  w  ww .jav  a  2  s. c o  m

    if (!user.isEnabled()) {
        log.debug("User account is disabled");

        throw new DisabledException(
                messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"),
                user);
    }

    if (!user.isAccountNonExpired()) {
        log.debug("User account is expired");

        throw new AccountExpiredException(messages.getMessage(
                "AbstractUserDetailsAuthenticationProvider.expired", "User account has expired"), user);
    }
}

From source file:fr.insalyon.creatis.vip.api.rest.security.apikey.ApikeyAuthenticationProvider.java

private void checkUserInfo(UserDetails user) {
    if (!user.isAccountNonLocked()) {
        logger.info("User account is locked");

        throw new LockedException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked",
                "User account is locked"));
    }// www .  ja  v  a 2  s .  com

    if (!user.isEnabled()) {
        logger.info("User account is disabled");

        throw new DisabledException(
                messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled"));
    }

    if (!user.isAccountNonExpired()) {
        logger.info("User account is expired");

        throw new AccountExpiredException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired"));
    }
    if (!user.isCredentialsNonExpired()) {
        logger.info("User account credentials have expired");

        throw new CredentialsExpiredException(
                messages.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired",
                        "User credentials have expired"));
    }
}

From source file:org.taverna.server.master.identity.StrippedDownAuthProvider.java

@PerfLogged
@Override/*from  ww w  .j a  va 2  s  .c om*/
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    if (!(authentication instanceof UsernamePasswordAuthenticationToken))
        throw new IllegalArgumentException("can only authenticate against username+password");
    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;

    // Determine username
    String username = (auth.getPrincipal() == null) ? "NONE_PROVIDED" : auth.getName();

    UserDetails user;

    try {
        user = retrieveUser(username, auth);
        if (user == null)
            throw new IllegalStateException(
                    "retrieveUser returned null - a violation of the interface contract");
    } catch (UsernameNotFoundException notFound) {
        if (logger.isDebugEnabled())
            logger.debug("User '" + username + "' not found", notFound);
        throw new BadCredentialsException("Bad credentials");
    }

    // Pre-auth
    if (!user.isAccountNonLocked())
        throw new LockedException("User account is locked");
    if (!user.isEnabled())
        throw new DisabledException("User account is disabled");
    if (!user.isAccountNonExpired())
        throw new AccountExpiredException("User account has expired");
    Object credentials = auth.getCredentials();
    if (credentials == null) {
        logger.debug("Authentication failed: no credentials provided");

        throw new BadCredentialsException("Bad credentials");
    }

    String providedPassword = credentials.toString();
    boolean matched = false;
    synchronized (authCache) {
        AuthCacheEntry pw = authCache.get(username);
        if (pw != null && providedPassword != null) {
            if (pw.valid(providedPassword))
                matched = true;
            else
                authCache.remove(username);
        }
    }
    // Auth
    if (!matched) {
        if (!passwordEncoder.matches(providedPassword, user.getPassword())) {
            logger.debug("Authentication failed: password does not match stored value");

            throw new BadCredentialsException("Bad credentials");
        }
        if (providedPassword != null)
            synchronized (authCache) {
                authCache.put(username, new AuthCacheEntry(providedPassword));
            }
    }

    // Post-auth
    if (!user.isCredentialsNonExpired())
        throw new CredentialsExpiredException("User credentials have expired");

    return createSuccessAuthentication(user, auth, user);
}

From source file:br.com.joaops.smt.security.SmtAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication a) throws AuthenticationException {
    String username = a.getName();
    String password = a.getCredentials().toString();

    UserDetails user = this.userDetails.loadUserByUsername(username);

    if (user == null) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",
                "AbstractUserDetailsAuthenticationProvider.badCredentials");
        throw new BadCredentialsException(message);
    }//from   ww w  .  ja  v a  2s .c  o m

    if (!user.getUsername().equals(username)) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",
                "AbstractUserDetailsAuthenticationProvider.badCredentials");
        throw new BadCredentialsException(message);
    }

    if (!passwordEncoder.matches(password, user.getPassword())) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials",
                "AbstractUserDetailsAuthenticationProvider.badCredentials");
        throw new BadCredentialsException(message);
    }

    if (user.isEnabled() == false) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.disabled",
                "AbstractUserDetailsAuthenticationProvider.disabled");
        throw new DisabledException(message);
    }

    if (user.isAccountNonLocked() == false) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.locked",
                "AbstractUserDetailsAuthenticationProvider.locked");
        throw new LockedException(message);
    }

    if (user.isAccountNonExpired() == false) {
        String message = this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.expired",
                "AbstractUserDetailsAuthenticationProvider.expired");
        throw new AccountExpiredException(message);
    }

    if (user.isCredentialsNonExpired() == false) {
        String message = this.messages.getMessage(
                "AbstractUserDetailsAuthenticationProvider.credentialsExpired",
                "AbstractUserDetailsAuthenticationProvider.credentialsExpired");
        throw new CredentialsExpiredException(message);
    }

    return new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
}

From source file:org.jamwiki.authentication.WikiUserDetails.java

/**
 * Private copy constructor./*from  ww  w .  j  a  va2s  .  c  om*/
 */
private WikiUserDetails(UserDetails userDetails) {
    this.username = userDetails.getUsername();
    this.password = userDetails.getPassword();
    this.enabled = userDetails.isEnabled();
    this.accountNonExpired = userDetails.isAccountNonExpired();
    this.credentialsNonExpired = userDetails.isCredentialsNonExpired();
    this.accountNonLocked = userDetails.isAccountNonLocked();
    this.setAuthorities(userDetails.getAuthorities());
}

From source file:org.opendatakit.common.security.spring.Oauth2AuthenticationProvider.java

/**
 * Handles the creation of the final <tt>Authentication</tt> object which will be returned by the provider.
 * <p>/*from  ww  w .  j a  v a 2 s . c o  m*/
 * The default implementation just creates a new OutOfBandAuthenticationToken from the original, but with the
 * UserDetails as the principal and including the authorities loaded by the UserDetailsService.
 *
 * @param userDetails the loaded UserDetails object
 * @param auth the token passed to the authenticate method, containing
 * @return the token which will represent the authenticated user.
 */
protected Authentication createSuccessfulAuthentication(UserDetails rawUserDetails,
        Oauth2AuthenticationToken auth) {
    String eMail = auth.getEmail();
    if (eMail == null) {
        logger.warn("User account attributes did not include an e-mail address! ");
        throw new UsernameNotFoundException("email address not supplied in User account attributes");
    }
    eMail = Oauth2AuthenticationProvider.normalizeMailtoAddress(eMail);
    String mailtoDomain = Oauth2AuthenticationProvider.getMailtoDomain(eMail);

    UserDetails userDetails = rawUserDetails;

    Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();

    authorities.addAll(userDetails.getAuthorities());
    // add the AUTH_GOOGLE_OAUTH2 granted authority,
    authorities.add(new SimpleGrantedAuthority(GrantedAuthorityName.AUTH_GOOGLE_OAUTH2.toString()));

    // attempt to look user up in registered users table...
    String username = null;
    UserDetails partialDetails = null;
    boolean noRights = false;
    try {
        partialDetails = wrappingUserDetailsService.loadUserByUsername(eMail);
        // found the user in the table -- fold in authorizations and get uriUser.
        authorities.addAll(partialDetails.getAuthorities());
        // users are blacklisted by registering them and giving them no rights.
        noRights = partialDetails.getAuthorities().isEmpty();
        username = partialDetails.getUsername();
    } catch (Exception e) {
        logger.warn("Oauth2 attribute e-mail: " + eMail + " did not match any known e-mail addresses! "
                + e.getMessage());
        throw new UsernameNotFoundException("account not recognized");
    }

    AggregateUser trueUser = new AggregateUser(username, partialDetails.getPassword(),
            UUID.randomUUID().toString(), // junk...
            mailtoDomain, partialDetails.isEnabled(), partialDetails.isAccountNonExpired(),
            partialDetails.isCredentialsNonExpired(), partialDetails.isAccountNonLocked(), authorities);
    if (noRights
            || !(trueUser.isEnabled() && trueUser.isAccountNonExpired() && trueUser.isAccountNonLocked())) {
        logger.warn("Oauth2 attribute e-mail: " + eMail + " account is blocked! ");
        throw new UsernameNotFoundException("account is blocked");
    }

    return new Oauth2AuthenticationToken(trueUser, trueUser.getAuthorities(), auth.getAccessToken(),
            auth.getEmail(), auth.getExpiration());
}