Example usage for org.springframework.security.core Authentication getCredentials

List of usage examples for org.springframework.security.core Authentication getCredentials

Introduction

In this page you can find the example usage for org.springframework.security.core Authentication getCredentials.

Prototype

Object getCredentials();

Source Link

Document

The credentials that prove the principal is correct.

Usage

From source file:com.esquema.seguridad.AutenticacionPersonalizada.java

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

    UsernamePasswordAuthenticationToken auth;
    String usuario = String.valueOf(authentication.getPrincipal());
    //System.out.println("Usuario..: " + usuario);

    String password = null;/*w  w  w . jav a 2 s  .  c  o  m*/
    try {
        //password = encr.encr(authentication.getCredentials().toString());
        password = authentication.getCredentials().toString();
        //System.out.println("Passwordss..: " + password);

    } catch (Exception ex) {
        Logger.getLogger(AutenticacionPersonalizada.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (usuario.isEmpty() && !password.isEmpty()) {
        throw new BadCredentialsException("Usuario no vlido");
    }

    if (password.isEmpty() && !usuario.isEmpty()) {
        throw new BadCredentialsException("Clave no vlida");
    }

    if (usuario.isEmpty() && password.isEmpty()) {
        throw new BadCredentialsException("Credenciales no vlidas");
    }

    //Llamado al mtodo encuentra. Est ms arriba.
    s_user usuarioBD = encuentra(usuario);

    if (usuarioBD.getEnabled() == 0) {
        throw new BadCredentialsException("El usuario [" + usuario.toUpperCase() + "] se encuentra bloqueado");
    }

    /*
    System.out.println("Clave de HTTPS..: " + clave);
    System.out.println("Resultado del query..: " + usuarioBD);
    System.out.println("Usuario BD..: " + usuarioBD.getUserlogin());
    System.out.println("Password BD..: " + usuarioBD.getPasswd());
    */

    if (usuarioBD.getIs_ldap() == 1) {
        try {
            ldapTemplate.afterPropertiesSet();
        } catch (Exception ex) {
            Logger.getLogger(AutenticacionPersonalizada.class.getName()).log(Level.SEVERE, null, ex);
        }

        // Perform the authentication.
        Filter filter = new EqualsFilter("sAMAccountName", usuario);

        if (!ldapTemplate.authenticate(env.getProperty("ldap.base"), filter.encode(), password)) {
            throw new BadCredentialsException("Clave o Usuario invlido");
        }
    } else {

        String clave = null;
        try {
            //create MD5 hash using the string: userlogin:passwd
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            byte[] b = (usuario + ":" + password).getBytes();
            //byte[] b = (password).getBytes();
            byte[] hash = md.digest(b);
            clave = Base64.encodeToString(hash, true);
        } catch (Exception ex) {
            Logger.getLogger(AutenticacionPersonalizada.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (usuarioBD == null || (!clave.equals(usuarioBD.getPasswd()))) {
            throw new BadCredentialsException("Clave o Usuario invlido");
        }
    }

    /*
    System.out.println("Usuario BD..: " + usuarioBD.getUserlogin());
    System.out.println("Password BD..: " + usuarioBD.getPasswd());
    */
    List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
    grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));

    auth = new UsernamePasswordAuthenticationToken(usuario, password, grantedAuths);
    auth.setDetails(usuarioBD);

    return auth;
}

From source file:ru.efo.security.ADUserDetailsService.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    final String username = authentication.getName();
    final String password = authentication.getCredentials().toString();
    logger.log(Level.FINE, "Performing logon into '" + ldapUrl + "' with credentials '" + username + "'/'"
            + password.replaceAll(".", "*") + "'");

    DirContext context = null;/* w w w. j  a va 2s. c o  m*/
    try {
        context = getDirContext(username + userSuffix, password);
        logger.log(Level.FINE, "User '" + username + "' has been successfully logged on");
        final ADUserDetails details = loadUserByUsername(context, username, password);
        return new UsernamePasswordAuthenticationToken(details, password, details.getAuthorities());
    } catch (NamingException ex) {
        logger.log(Level.SEVERE, "Could not login into '" + ldapUrl + "'", ex);
        throw new BadCredentialsException(ex.getMessage());
    } finally {
        if (context != null) {
            try {
                context.close();
            } catch (NamingException ex) {
                logger.log(Level.WARNING, "Could not close DirContext", ex);
            }
        }
    }
}

From source file:se.kth.csc.config.MockAuthConfig.java

@Bean
@Autowired//from w ww.j a  v a 2s  .  co  m
public AuthenticationProvider authenticationProvider(
        final AuthenticationUserDetailsService<Authentication> authenticationUserDetailsService) {
    return new AuthenticationProvider() {
        @Override
        public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
            final UserDetails userDetails = authenticationUserDetailsService.loadUserDetails(authentication);
            return new Authentication() {
                @Override
                public Collection<? extends GrantedAuthority> getAuthorities() {
                    return userDetails.getAuthorities();
                }

                @Override
                public Object getCredentials() {
                    return authentication.getCredentials();
                }

                @Override
                public Object getDetails() {
                    return authentication.getDetails();
                }

                public UserDetails getUserDetails() {
                    return userDetails;
                }

                @Override
                public Object getPrincipal() {
                    return userDetails;
                }

                @Override
                public boolean isAuthenticated() {
                    return authentication.isAuthenticated();
                }

                @Override
                public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
                    authentication.setAuthenticated(isAuthenticated);
                }

                @Override
                public String getName() {
                    return authentication.getName();
                }
            };
        }

        @Override
        public boolean supports(Class<?> authentication) {
            return true;
        }
    };
}

From source file:org.xaloon.wicket.security.spring.external.ExternalAuthenticationProvider.java

private Authentication createExternalAuthenticationToken(Authentication authentication,
        AuthenticationToken initialToken) {
    User user = userDao.newUser();/* ww w.  j  a  v a  2s. com*/
    user.setUsername(authentication.getName());
    user.setExternal(true);
    externalParameterResolver.resolve(initialToken, user);

    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new SimpleGrantedAuthority(SecurityAuthorities.AUTHENTICATED_USER));

    UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
            authentication.getPrincipal(), authentication.getCredentials(), authorities);
    result.setDetails(user);
    return result;
}

From source file:nc.noumea.mairie.appock.core.security.AppockAuthenticationProvider.java

/**
 * Override la mthode authenticate/*from www .  j a  v  a2 s. c  om*/
 * 
 * @param authentication Authentication
 * @throws AuthenticationException Exception d'authentification
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    Authentication authenticationResult = null;

    if (provider != null)
        try {
            authenticationResult = provider.authenticate(authentication);
        } catch (BadCredentialsException e) {
            LOGGER.error("Error lors de l'authentification", e);
            throw new BadCredentialsException(messageProvider);
        }

    String username = authentication.getName();
    String password = (String) authentication.getCredentials();
    List<GrantedAuthority> roles = new ArrayList<>();

    try {
        AppUser appUser = appUserService.findByLogin(username);
        if (appUser == null || !appUser.isActif()) {
            throw new BadCredentialsException(messageAppock);
        }
    } catch (NoResultException e) {
        throw new BadCredentialsException(messageAppock);
    }

    return (provider == null) ? new UsernamePasswordAuthenticationToken(username, password, roles)
            : authenticationResult;
}

From source file:fr.univrouen.poste.web.ProfilChoiceController.java

@RequestMapping
public String profilChoice(@RequestParam(required = false) String profil) {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(auth.getAuthorities());

    if (profil != null) {
        logger.info(auth.getName() + " a slectionn le profil " + profil);
        if ("membre".equals(profil)) {
            authorities.remove(new GrantedAuthorityImpl("ROLE_CANDIDAT"));
        }//ww w . j  av a 2 s  . c o m
        if ("candidat".equals(profil)) {
            authorities.remove(new GrantedAuthorityImpl("ROLE_MEMBRE"));
        }
        auth = new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(), authorities);
        SecurityContextHolder.getContext().setAuthentication(auth);
    }

    if (auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_CANDIDAT"))
            && auth.getAuthorities().contains(new GrantedAuthorityImpl("ROLE_MEMBRE"))) {
        return "profilChoice";
    } else {
        return "index";
    }
}

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 w  w  .j  ava  2 s . c o  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.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;/*www. j  a  v a  2 s  .  c  o  m*/
        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:org.xaloon.wicket.security.spring.SpringSecurityFacade.java

private AuthenticationToken authenticateInternal(AbstractAuthenticationToken authenticationRequestToken) {
    boolean authenticated = false;
    String name = authenticationRequestToken.getName();
    String errorMessage = null;/* ww  w .ja  v  a2 s  .c  o m*/
    try {
        Authentication authentication = authenticationManager.authenticate(authenticationRequestToken);
        authenticated = authentication.isAuthenticated();
        if (authenticated && authentication.getDetails() == null) {
            // Try to load user details. Copy information into new token
            UsernamePasswordAuthenticationToken authenticationWithDetails = new UsernamePasswordAuthenticationToken(
                    authentication.getPrincipal(), authentication.getCredentials(),
                    authentication.getAuthorities());
            authenticationWithDetails.setDetails(userDao.getUserByUsername(authentication.getName()));
            authentication = authenticationWithDetails;
        }
        SecurityContextHolder.getContext().setAuthentication(authentication);
        name = authentication.getName();
    } catch (AuthenticationException e) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("User " + name + " failed to login. Reason: ", e);
        }
        authenticated = false;
        errorMessage = e.getMessage();
    }
    if (authenticated) {
        return new AuthenticationToken(name, new ArrayList<AuthenticationAttribute>());
    }
    return new AuthenticationToken(name, errorMessage);
}

From source file:com.gs.config.MyAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UserDetails userDetails = this.customJDBCDaoImpl.loadUserByUsername(authentication.getName());
    //Obtengo los intentos de inicio de sesin hechos por un usuario
    int intentos = usuarioConIntentoFallido.getIntentosUsuario(authentication.getName());
    if (intentos < intentosPosibles && !listUsersLockoutIntentFail.findUserBlockout(authentication.getName())) {
        if (userDetails.isEnabled()) {
            if (userDetails != null && shaPasswordEncoder.isPasswordValid(userDetails.getPassword(),
                    authentication.getCredentials().toString(), null)) {
                usuarioConIntentoFallido.removeUsuario(userDetails.getUsername());
                //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());
            }/*w  ww . jav a  2  s  .c om*/
            throw new BadCredentialsException("Bad credentials");
        } else {
            throw new DisabledException("User disabled");
        }
    } else {
        throw new IntentLimitExceeded("limite de intentos excedidos");
    }
}