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

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

Introduction

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

Prototype

public UsernameNotFoundException(String msg) 

Source Link

Document

Constructs a UsernameNotFoundException with the specified message.

Usage

From source file:org.apigw.authserver.shibboleth.ShibbolethSamlUserDetailsService.java

@Override
public UserDetails loadUserDetails(Authentication token) throws UsernameNotFoundException {
    final Map<String, String> principal = (Map) token.getPrincipal(); //TODO: principal should be something better
    final String subjectSerialNumber = principal.get("subjectSerialNumber");
    final String subjectCommonName = principal.get("subjectCommonName");
    if (subjectSerialNumber != null && ssnPattern.matcher(subjectSerialNumber).matches()) {
        final User user = new User(subjectSerialNumber, grantedAuthorities);
        user.setFullName(subjectCommonName);
        user.setEnabled(true);//from   ww w  .j  av  a  2s .co m
        logger.debug("returning user");
        return user;
    }
    throw new UsernameNotFoundException("expected subjectSerialNumber but couldn't find it");
}

From source file:org.pentaho.platform.spring.security.saml.groups.PentahoSamlNativeUserDetailsService.java

@Override
public Object loadUserBySAML(SAMLCredential credential) throws UsernameNotFoundException {

    if (credential == null || credential.getNameID() == null || credential.getNameID().getValue() == null) {
        throw new UsernameNotFoundException("invalid/null SAMLCredential");
    }/*from  ww w  .  j a v  a  2 s .com*/

    String username = credential.getNameID().getValue();

    try {
        // check the userDetailsMap for a UserDetails stored for this username. If we have one already, use it
        return loadUserByUsername(username);
    } catch (UsernameNotFoundException usernameNotFoundException) {

        // no UserDetails found = new user coming in, create a UserDetails for it and store it in the userDetailsMap

        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        // Add the defaultRole. default role is usually "Authenticated"
        authorities.add(Utils.getDefaultRole());

        // iterate the users attributes: if there's an attribute with the name 'getRoleRelatedUserAttributeName()',
        // iterate through its values' list and add those to the granted authorities list
        if (getRoleRelatedUserAttributeName() != null && !getRoleRelatedUserAttributeName().isEmpty()
                && credential.getAttribute(getRoleRelatedUserAttributeName()) != null) {

            authorities.addAll(roleRelatedAttributeToGrantedAuthorities(
                    credential.getAttribute(getRoleRelatedUserAttributeName())));
        }

        // create the UserDetails object

        UserDetails userDetails = new User(username, "ignored" /* password */, true /* isEnabled */,
                true /* isAccountNonExpired */, true /* isCredentialsNonExpired */,
                true /* isAccountNonExpired */, authorities);

        Utils.getUserMap().put(username, userDetails);

        return userDetails;
    }
}

From source file:com.cocktail.config.SecurityConfig.java

@Bean
UserDetailsService userDetailsService() {
    return new UserDetailsService() {

        @Override//from   w ww . j  av  a2s.  c om
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            User user = userRepository.findByUsername(username);
            if (user != null) {
                return new org.springframework.security.core.userdetails.User(user.getUsername(),
                        user.getPassword(), true, true, true, true, AuthorityUtils.createAuthorityList("USER"));
            } else {
                throw new UsernameNotFoundException("could not find the user '" + username + "'");
            }
        }

    };
}

From source file:org.deegree.securityproxy.authentication.basic.UserService.java

@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
    LOG.info("Search user " + userName);
    UserDetails user = userDao.retrieveUserByName(userName);
    if (user != null)
        return user;
    throw new UsernameNotFoundException("User with name " + userName + " not found!");
}

From source file:de.pksoftware.springstrap.basic.service.BasicUserDetailsService.java

/**
 * Loads the UserDetails by username/*from  w  ww .j  a  v a 2s  .c  om*/
 */
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    IAccount account;
    try {
        account = storeAccountService.loadAccountByUsernameOrEmail(username);
    } catch (NoSuchAccountException e) {
        throw new UsernameNotFoundException("Neither email nor username have been found!");
    }

    return account;
}

From source file:at.ac.univie.isc.asio.security.RoleUserService.java

@Override
public UserDetails loadUserByUsername(final String principal) throws UsernameNotFoundException {
    final String roleName = principal.toUpperCase(Locale.ENGLISH);
    final UserDetails user = users.get(roleName);
    if (user == null) {
        throw new UsernameNotFoundException("unknown role <" + principal + ">");
    }/*  w w  w .  j  a  va 2 s . c o m*/
    return user;
}

From source file:com.gisnet.cancelacion.web.controller.AutenticarUsuario.java

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

    FindResponse<UsuarioInfo> find = service.findByUsername(username);
    UsuarioInfo usuario = find.getInfo();

    if (usuario != null) {
        if (service.loguear(new FindByRequest(username, password))) {
            List<GrantedAuthority> grants = new ArrayList<>();
            for (String rol : usuario.getRoles()) {
                grants.add(new SimpleGrantedAuthority(rol));
            }//from  ww w . j a  va 2  s. c o m
            return new UsernamePasswordAuthenticationToken(username, password, grants);
        }
        throw new AuthenticationServiceException("Autenticacion fallida");
    }
    throw new UsernameNotFoundException("Usuario no encontrado.");
}

From source file:net.przemkovv.sphinx.service.CustomUserDetailsService.java

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

    net.przemkovv.sphinx.model.User domainUser = userService.getUser(email);
    if (domainUser == null) {
        throw new UsernameNotFoundException(email);
    }//from   w  w  w .  j  av a2 s .co  m

    boolean enabled = true;
    boolean accountNonExpired = true;
    boolean credentialsNonExpired = true;
    boolean accountNonLocked = true;

    return new User(domainUser.getEmail(), domainUser.getPassword(), enabled, accountNonExpired,
            credentialsNonExpired, accountNonLocked, getAuthorities(domainUser));
}

From source file:com.qpark.eip.core.spring.security.EipUserDetailsService.java

/**
 * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
 *///from ww  w  .  ja  v a2  s .  c om
@Override
public UserDetails loadUserByUsername(final String username)
        throws UsernameNotFoundException, DataAccessException {
    this.logger.debug("+loadUserByUsername user {}", username);
    User user = this.userProvider.getUser(username);
    if (user == null) {
        throw new UsernameNotFoundException("Application user '" + username + "' is not known");
    }
    this.logger.debug("-loadUserByUsername user {} found!", user.getUsername());
    return user;
}

From source file:net.maritimecloud.identityregistry.security.x509.X509HeaderUserDetailsService.java

@Override
public UserDetails loadUserByUsername(String certificateHeader) throws UsernameNotFoundException {
    if (certificateHeader == null || certificateHeader.length() < 10) {
        logger.warn("No certificate header found");
        throw new UsernameNotFoundException("No certificate header found");
    }//from w ww.  ja va 2s  .  co  m
    X509Certificate userCertificate = certUtil.getCertFromString(certificateHeader);
    if (userCertificate == null) {
        logger.error("Extracting certificate from header failed");
        throw new UsernameNotFoundException("Extracting certificate from header failed");
    }

    // Actually authenticate certificate against root cert.
    if (!certUtil.verifyCertificate(userCertificate)) {
        logger.warn("Certificate could not be verified");
        throw new UsernameNotFoundException("Certificate could not be verified");
    }
    // Check that the certificate has not been revoked
    long certId = userCertificate.getSerialNumber().longValue();
    Certificate cert = certificateService.getCertificateById(certId);
    if (cert.isRevoked()) {
        Calendar cal = Calendar.getInstance();
        Date now = cal.getTime();
        if (cert.getRevokedAt() == null || cert.getRevokedAt().before(now)) {
            logger.warn("The certificate has been revoked! Cert #" + certId);
            throw new UsernameNotFoundException("The certificate has been revoked! Cert #" + certId);
        }
    }
    // Get user details from the certificate
    UserDetails user = certUtil.getUserFromCert(userCertificate);
    if (user == null) {
        logger.warn("Extraction of data from the certificate failed");
        throw new UsernameNotFoundException("Extraction of data from the client certificate failed");
    }
    // Convert the permissions extracted from the certificate to authorities in this API
    InetOrgPerson person = ((InetOrgPerson) user);
    String certOrg = person.getO();
    Organization org = organizationService.getOrganizationByMrn(certOrg);
    if (org == null) {
        logger.warn("Unknown Organization '" + certOrg + "' in client certificate");
        throw new UsernameNotFoundException("Unknown Organization in client certificate");
    }
    Collection<GrantedAuthority> newRoles = new ArrayList<>();
    logger.debug("Looking up roles");
    for (GrantedAuthority role : user.getAuthorities()) {
        logger.debug("Looking up roles");
        String auth = role.getAuthority();
        String[] auths = auth.split(",");
        for (String auth2 : auths) {
            logger.debug("Looking up role: " + auth2);
            List<Role> foundRoles = roleService.getRolesByIdOrganizationAndPermission(org.getId(), auth2);
            if (foundRoles != null) {
                for (Role foundRole : foundRoles) {
                    newRoles.add(new SimpleGrantedAuthority(foundRole.getRoleName()));
                }
            }
        }
    }
    // Add ROLE_USER as standard for authenticated users with no other role.
    if (newRoles.isEmpty()) {
        newRoles.add(new SimpleGrantedAuthority("ROLE_USER"));
    }
    InetOrgPerson.Essence essence = new InetOrgPerson.Essence((InetOrgPerson) user);
    essence.setAuthorities(newRoles);
    return essence.createUserDetails();
}