Example usage for org.springframework.security.authentication UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken

List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken

Introduction

In this page you can find the example usage for org.springframework.security.authentication UsernamePasswordAuthenticationToken UsernamePasswordAuthenticationToken.

Prototype

public UsernamePasswordAuthenticationToken(Object principal, Object credentials,
        Collection<? extends GrantedAuthority> authorities) 

Source Link

Document

This constructor should only be used by AuthenticationManager or AuthenticationProvider implementations that are satisfied with producing a trusted (i.e.

Usage

From source file:com.hp.autonomy.frontend.find.idol.authentication.IdolPreAuthenticatedAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final Object principal = authentication.getPrincipal();

    if (principal == null) {
        throw new BadCredentialsException("Principal not supplied");
    }//from ww w  .  j  a v a 2 s  .c o  m

    final String username = principal.toString().toLowerCase();

    UserRoles user;

    try {
        user = userService.getUser(username);
    } catch (final AciErrorException e) {
        log.debug("Failed to fetch the user", e);

        if (USER_NOT_FOUND_ERROR_ID.equals(e.getErrorId())) {
            // use empty password so that auto created users cannot be authenticated against
            this.userService.addUser(username, "", UserConfiguration.IDOL_USER_ROLE);

            user = userService.getUser(username);
        } else {
            throw e;
        }
    }

    final Collection<SimpleGrantedAuthority> grantedAuthorities = new HashSet<>();

    for (final String role : user.getRoles()) {
        grantedAuthorities.add(new SimpleGrantedAuthority(role));
    }

    return new UsernamePasswordAuthenticationToken(
            new CommunityPrincipal(user.getUid(), username, user.getSecurityInfo()), null,
            authoritiesMapper.mapAuthorities(grantedAuthorities));
}

From source file:com.autoupdater.server.utils.authentication.BCryptAuthenticationManager.java

/**
 * Authenticate user.//www  .  j av a2 s . c o m
 * 
 * @param auth
 *            authentication data passed by Spring Security
 * @return result of authentication
 */
@Override
public Authentication authenticate(Authentication auth) throws AuthenticationException {
    logger.debug("Performing authentication");

    User user = null;

    logger.debug("Searching user [" + auth.getName() + "] in DB");
    try {
        user = userService.findByUsername(auth.getName());
    } catch (Exception e) {
        logger.error("User [" + auth.getName() + "] does not exists (exception)!");
        throw new AuthenticationServiceException("Error while obtaining User data!");
    }
    if (user == null) {
        logger.error("User [" + auth.getName() + "] does not exists (null)!");
        throw new BadCredentialsException("User does not exists!");
    }

    if (!BCrypt.checkpw(auth.getCredentials().toString(), user.getHashedPassword())) {
        logger.error("Password doesn't match!");
        throw new BadCredentialsException("Password doesn't match!");
    }

    logger.debug("User details are good and ready to go");
    return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(),
            getAuthorities(user.isAdmin(), user.isPackageAdmin()));
}

From source file:org.web4thejob.security.ADAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    if (authentication.getName() == null || (String) authentication.getCredentials() == null) {
        throw new BadCredentialsException("");
    }//from  w  w w .  j  a va  2  s.  co  m

    String principal = getPrincipal(authentication.getName());
    String passwd = (String) authentication.getCredentials();

    LdapContext ctx = null;
    try {
        Hashtable<String, Object> env = new Hashtable<String, Object>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, LdapCtxFactory.class.getCanonicalName());
        env.put(Context.SECURITY_AUTHENTICATION, "Simple");
        env.put(Context.SECURITY_PRINCIPAL, principal);
        env.put(Context.SECURITY_CREDENTIALS, passwd);
        env.put(Context.PROVIDER_URL, url);
        ctx = new InitialLdapContext(env, null);
        //LDAP Connection Successful

        UserDetails userDetails = userDetailsService.loadUserByUsername(principal);
        return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities());
    } catch (NamingException nex) {
        throw new BadCredentialsException("LDAP authentication failed.", nex);
    } catch (UsernameNotFoundException e) {
        throw new BadCredentialsException("UserDetails did not find a valid user for name: " + principal, e);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception ignore) {
            }
        }
    }
}

From source file:cz.muni.fi.editor.test.service.support.other.TestSecurityContextFactory.java

@Override
@Transactional(readOnly = true)/*  w ww . java2 s  . c  om*/
public SecurityContext createSecurityContext(WithEditorUser withEditorUser) {
    SecurityContext context = SecurityContextHolder.createEmptyContext();

    UserDTO user = new UserDTO();
    user.setId(withEditorUser.id());

    User dao = new User();
    dao.setId(withEditorUser.id());

    List<OrganizationDTO> member = organizationDAO.getOrganizationForUser(dao, true).stream().map(o -> {
        OrganizationDTO dto = new OrganizationDTO();
        dto.setId(o.getId());
        return dto;
    }).collect(Collectors.toList());

    List<OrganizationDTO> owner = organizationDAO.ownedBy(dao).stream().map(o -> {
        OrganizationDTO dto = new OrganizationDTO();
        dto.setId(o.getId());
        return dto;
    }).collect(Collectors.toList());

    user.init(owner, member);

    Authentication auth = new UsernamePasswordAuthenticationToken(user, user.getPassword(),
            user.getAuthorities());

    context.setAuthentication(auth);

    return context;
}

From source file:com.cruz.sec.config.MyAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    System.out.println("Entrando a la verificacin del usuario");
    System.out.println("Nombre de usuario: " + authentication.getName());
    UserDetails userDetails = (UserDetails) this.customJDBCDaoImpl.loadUserByUsername(authentication.getName());
    if (userDetails.isEnabled()) {
        Object salt = null;/* ww w  . j  ava  2 s  .  com*/
        if (this.saltSource != null) {
            salt = saltSource.getSalt(userDetails);
        }
        if (shaPasswordEncoder.isPasswordValid(userDetails.getPassword(),
                authentication.getCredentials().toString(), salt)) {
            //Verifico si el usuario ya tiene una sesin abierta, si es as la cierro y le creo su nueva instancia
            verifUserInSession(userDetails.getUsername());
            return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        }
        throw new BadCredentialsException("Bad credentials");
    } else {
        throw new DisabledException("User disabled");
    }
}

From source file:com.ggk.hrms.authentication.DefaultUserAuthenticationConverter.java

public Authentication extractAuthentication(Map<String, ?> map) {
    if (map.containsKey(USERNAME)) {
        UserDetailsImpl user = getUserPrincipal(map);
        return new UsernamePasswordAuthenticationToken(user, "N/A", getAuthorities(user));
    }/*from ww w  .  j  av  a  2s .c om*/
    return null;
}

From source file:org.kamranzafar.xmpp.template.XmppAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    //Authentication and BOSH pre-binding
    BoshConnectionConfiguration boshConfiguration = BoshConnectionConfiguration.builder()
            .hostname(xmppConfig.getHost()).port(xmppConfig.getPort()).file(xmppConfig.getHttpBind()).wait(60)
            .build();/*from  w  ww  . j  a  v  a  2 s . co m*/

    XmppClient xmppClient = new XmppClient(xmppConfig.getHost(), boshConfiguration);

    try {
        xmppClient.connect(new Jid((String) authentication.getPrincipal()));
        xmppClient.login((String) authentication.getPrincipal(), (String) authentication.getCredentials());

        rocks.xmpp.extensions.httpbind.BoshConnection boshConnection = (rocks.xmpp.extensions.httpbind.BoshConnection) xmppClient
                .getActiveConnection();

        String sessionId = boshConnection.getSessionId();

        // Detaches the BOSH session, without terminating it.
        long rid = boshConnection.detach();
        //            System.out.println("JID: " + xmppClient.getConnectedResource());
        //            System.out.println("SID: " + sessionId);
        //            System.out.println("RID: " + rid);

        XmppUser xmppUser = new XmppUser();
        xmppUser.setUsername((String) authentication.getPrincipal());
        xmppUser.setJid(xmppClient.getConnectedResource().toString());
        xmppUser.setSid(sessionId);
        xmppUser.setRid(rid);

        Collection<? extends GrantedAuthority> authorities = Collections
                .singleton(new SimpleGrantedAuthority("ROLE_USER"));

        return new UsernamePasswordAuthenticationToken(xmppUser, authentication.getCredentials(), authorities);
    } catch (XmppException e) {
        e.printStackTrace();
        throw new XmppAuthenticationException(e.getMessage(), e);
    }
}

From source file:com.github.djabry.platform.service.security.DefaultAuthenticationProvider.java

/**
 * Performs authentication with the same contract as {@link
 * org.springframework.security.authentication.AuthenticationManager#authenticate(org.springframework.security.core.Authentication)}.
 *
 * @param authentication the authentication request object.
 * @return a fully authenticated object including credentials. May return <code>null</code> if the
 * <code>AuthenticationProvider</code> is unable to support authentication of the passed
 * <code>Authentication</code> object. In such a case, the next <code>AuthenticationProvider</code> that
 * supports the presented <code>Authentication</code> class will be tried.
 * @throws org.springframework.security.core.AuthenticationException if authentication fails.
 *//*from w  w  w.ja v a  2  s  . c  o m*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getName();
    String password = authentication.getCredentials().toString();

    UserDetails details = userDetailsService.loadUserByUsername(username);
    SecurityToken<DBUser> token = springAuthenticationService.login(username, password);

    if (token != null) {
        return new UsernamePasswordAuthenticationToken(username, password, details.getAuthorities());
    }

    throw new BadCredentialsException("Incorrect credentials");

}

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 ava  2s.  c  o 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:app.controller.CustomerControllerTest.java

/**
 * Allows to set up a user with specific authority
 * @param credential the value used as username, password and role
 */// w ww  .j  ava2 s .  c om
void setSecurityContext(String credential) {
    UsernamePasswordAuthenticationToken user = new UsernamePasswordAuthenticationToken(credential, credential,
            AuthorityUtils.createAuthorityList("ROLE_" + credential.toUpperCase()));
    SecurityContextHolder.getContext().setAuthentication(user);
}