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

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

Introduction

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

Prototype

public String getName() 

Source Link

Usage

From source file:org.xaloon.wicket.security.spring.XaloonDaoAuthenticationProvider.java

@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
        UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    if (authentication.getCredentials() == null) {
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }// w  w w . j a va  2  s .co m
    if (authentication.getCredentials() instanceof String) {
        String encoded = PasswordEncoder.get().encode(authentication.getName(),
                authentication.getCredentials().toString());

        if (!userDetails.getPassword().equals(encoded)) {
            throw new BadCredentialsException(messages
                    .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    }
}

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

@PerfLogged
@Override//  w w w . j  ava  2  s .c o m
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:de.thm.arsnova.service.UserServiceImpl.java

@Override
public void authenticate(final UsernamePasswordAuthenticationToken token,
        final UserProfile.AuthProvider authProvider) {
    Authentication auth;/*from  www  .  j  av  a2s .c  o m*/
    switch (authProvider) {
    case LDAP:
        auth = ldapAuthenticationProvider.authenticate(token);
        break;
    case ARSNOVA:
        auth = daoProvider.authenticate(token);
        break;
    case ARSNOVA_GUEST:
        String id = token.getName();
        boolean autoCreate = false;
        if (id == null || id.isEmpty()) {
            id = generateGuestId();
            autoCreate = true;
        }
        UserDetails userDetails = guestUserDetailsService.loadUserByUsername(id, autoCreate);
        if (userDetails == null) {
            throw new UsernameNotFoundException("Guest user does not exist");
        }
        auth = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

        break;
    default:
        throw new IllegalArgumentException("Unsupported authentication provider");
    }

    if (!auth.isAuthenticated()) {
        throw new BadRequestException();
    }
    SecurityContextHolder.getContext().setAuthentication(auth);
}

From source file:com.mothsoft.alexis.web.security.AlexisWebAuthenticationProvider.java

@Override
protected UserDetails retrieveUser(final String username, final UsernamePasswordAuthenticationToken token)
        throws AuthenticationException {
    return this.transactionTemplate.execute(new TransactionCallback<UserDetails>() {

        @Override//from  ww w. j a v  a 2  s.c  o m
        public UserDetails doInTransaction(TransactionStatus arg0) {
            final User user = AlexisWebAuthenticationProvider.this.userDao.findUserByUsername(username);
            final String password = String.valueOf(token.getCredentials());
            final UserDetails userDetails = AlexisWebAuthenticationProvider.this.userDetailsService
                    .loadUserByUsername(username);

            final String encodedPassword = AlexisWebAuthenticationProvider.this.passwordEncoder
                    .encodePassword(password, user.getPasswordSalt());

            // credentials are bad if none are stored (external auth) or they don't match
            if (user.getHashedPassword() == null || !username.equals(token.getName())
                    || !encodedPassword.equals(user.getHashedPassword())) {
                throw new BadCredentialsException(username);
            }

            final UserApiToken apiToken = AlexisWebAuthenticationProvider.this.userDao.createApiToken(user);
            final UserDetails toReturn = new UserAuthenticationDetails((UserAuthenticationDetails) userDetails,
                    apiToken.getToken());
            return toReturn;
        }
    });
}

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

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {
    UsernamePasswordAuthenticationToken user = (UsernamePasswordAuthenticationToken) exception
            .getAuthentication();//from  www . j  a  v  a  2 s.  c  om
    //System.out.println("Mensaje del error: "+exception.getMessage());
    //        PrincipalsessionInformaction user = request.getUserPrincipal();
    System.out.println("-----------------------------INTENTO FALLIDO-----------------------------");

    //Causas de la autenticacin fallida
    if (exception.getClass().isAssignableFrom(UsernameNotFoundException.class)) {
        //            System.out.println("INTENTO FALLIDO: El usuario no est registrado en la base de datos ");
        request.setAttribute("ERRORSESSION", "Usuario no registrado, verifique con el administrador");
        request.getRequestDispatcher("login?err=1").forward(request, response);
        //response.sendRedirect("login?err=1");
    } else if (exception.getClass().isAssignableFrom(BadCredentialsException.class)) {
        sessionFailDaoImp.insertUserSessionFail(user.getName(), request.getLocalAddr());
        usuarioConIntentoFallido.addIntentoUsuario(user.getName());
        //            System.out.println("INTENTO FALLIDO: Creedenciales erroneas");
        request.setAttribute("ERRORSESSION", "Contrasea incorrecta, intente nuevamente");
        request.getRequestDispatcher("login?err=1").forward(request, response);
        //response.sendRedirect("login?err=2");
    } else if (exception.getClass().isAssignableFrom(DisabledException.class)) {
        //            System.out.println("INTENTO FALLIDO: Usuario desabilitado");
        request.setAttribute("ERRORSESSION", "Usuario deshabilitado, verifique con el administrador");
        request.getRequestDispatcher("login?err=1").forward(request, response);
        //response.sendRedirect("login?err=3");
    } else if (exception.getClass().isAssignableFrom(SessionAuthenticationException.class)) {
        //            System.out.println("INTENTO FALLIDO: Usuario ya logeado");
        request.setAttribute("ERRORSESSION", "Ya existe una sesin abierta con este usuario");
        request.getRequestDispatcher("login?err=1").forward(request, response);
        //response.sendRedirect("login?err=4");
    } else if (exception.getClass().isAssignableFrom(IntentLimitExceeded.class)) {
        //            System.out.println("INTENTO FALLIDO: NMERO DE INTENTOS EXCEDIDOS");
        //Elimino al usuario de la listo de los intentos y se agrega a la lista de usuarios bloqueados
        usuarioConIntentoFallido.removeUsuario(user.getName());
        //Se crea el hilo para desbloquear al usuario
        listUsersLockoutIntentFail.addBlockUserFail(user.getName(), tiempoLockout);
        //request.setAttribute("ERRORSESSION", "Ha excedido el lmite de intentos. Por favor espere unos minutos e intente nuevamente");
        request.getRequestDispatcher("intentlimit").forward(request, response);
    } else {
        //            System.out.println("INTENTO FALLIDO: NO SE QUE PASO");
        request.setAttribute("ERRORSESSION", "No ha sido posible iniciar sesin");
        request.getRequestDispatcher("login?err=1").forward(request, response);
    }
}

From source file:org.apache.nifi.kerberos.KerberosProvider.java

@Override
public final AuthenticationResponse authenticate(final LoginCredentials credentials)
        throws InvalidLoginCredentialsException, IdentityAccessException {
    if (provider == null) {
        throw new IdentityAccessException("The Kerberos authentication provider is not initialized.");
    }/*from www. j  a  va 2s .com*/

    try {
        // Perform the authentication
        final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                credentials.getUsername(), credentials.getPassword());
        logger.debug("Created authentication token for principal {} with name {} and is authenticated {}",
                token.getPrincipal(), token.getName(), token.isAuthenticated());

        final Authentication authentication = provider.authenticate(token);
        logger.debug(
                "Ran provider.authenticate() and returned authentication for "
                        + "principal {} with name {} and is authenticated {}",
                authentication.getPrincipal(), authentication.getName(), authentication.isAuthenticated());

        return new AuthenticationResponse(authentication.getName(), credentials.getUsername(), expiration,
                issuer);
    } catch (final AuthenticationException e) {
        throw new InvalidLoginCredentialsException(e.getMessage(), e);
    }
}

From source file:org.cloudifysource.security.CloudifyDaoAuthenticationProvider.java

@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
                    "Only UsernamePasswordAuthenticationToken is supported"));

    logger.finest("CloudifyDaoAuthenticationProvider: authenticate");
    final UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication;
    final CloudifyUserDetails user;

    // Determine username
    final String username = userToken.getName();
    final String password = (String) authentication.getCredentials();

    if (StringUtils.isBlank(username)) {
        throw new IllegalArgumentException("Empty username not allowed");
    }//from  w w w. ja v  a  2  s . co m
    Assert.notNull(password, "Null password was supplied in authentication token");
    logger.fine("Processing authentication request for user: " + username);

    // Get the Cloudify user details from the user details service
    try {
        user = retrieveUser(username);
        String retrievedUserPassword = user.getPassword();

        if (!password.equals(retrievedUserPassword)) {
            logger.warning("Authentication failed: password does not match stored value");
            throw new BadCredentialsException(messages
                    .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
        }
    } catch (final UsernameNotFoundException e) {
        logger.warning("User '" + username + "' not found");
        throw e;
    }

    // authenticate
    runAuthenticationChecks(user);

    // create a successful and full authentication token
    return createSuccessfulAuthentication(userToken, user);
}

From source file:org.springframework.security.extensions.kerberos.KerberosAuthenticationProvider.java

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
    String validatedUsername = kerberosClient.login(auth.getName(), auth.getCredentials().toString());
    UserDetails userDetails = this.userDetailsService.loadUserByUsername(validatedUsername);
    UsernamePasswordAuthenticationToken output = new UsernamePasswordAuthenticationToken(userDetails,
            auth.getCredentials(), userDetails.getAuthorities());
    output.setDetails(authentication.getDetails());
    return output;

}

From source file:org.springframework.security.ldap.authentication.AbstractLdapAuthenticationProvider.java

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            messages.getMessage("LdapAuthenticationProvider.onlySupports",
                    "Only UsernamePasswordAuthenticationToken is supported"));

    final UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication;

    String username = userToken.getName();
    String password = (String) authentication.getCredentials();

    if (logger.isDebugEnabled()) {
        logger.debug("Processing authentication request for user: " + username);
    }//  w w w. ja  va2  s. c o m

    if (!StringUtils.hasLength(username)) {
        throw new BadCredentialsException(
                messages.getMessage("LdapAuthenticationProvider.emptyUsername", "Empty Username"));
    }

    if (!StringUtils.hasLength(password)) {
        throw new BadCredentialsException(
                messages.getMessage("AbstractLdapAuthenticationProvider.emptyPassword", "Empty Password"));
    }

    Assert.notNull(password, "Null password was supplied in authentication token");

    DirContextOperations userData = doAuthentication(userToken);

    UserDetails user = userDetailsContextMapper.mapUserFromContext(userData, authentication.getName(),
            loadUserAuthorities(userData, authentication.getName(), (String) authentication.getCredentials()));

    return createSuccessfulAuthentication(userToken, user);
}

From source file:org.springframework.security.ldap.authentication.LdapAuthenticationProvider.java

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
            messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports",
                    "Only UsernamePasswordAuthenticationToken is supported"));

    final UsernamePasswordAuthenticationToken userToken = (UsernamePasswordAuthenticationToken) authentication;

    String username = userToken.getName();
    String password = (String) authentication.getCredentials();

    if (logger.isDebugEnabled()) {
        logger.debug("Processing authentication request for user: " + username);
    }/* ww  w . j a  v  a  2s  .com*/

    if (!StringUtils.hasLength(username)) {
        throw new BadCredentialsException(
                messages.getMessage("LdapAuthenticationProvider.emptyUsername", "Empty Username"));
    }

    Assert.notNull(password, "Null password was supplied in authentication token");

    try {
        DirContextOperations userData = getAuthenticator().authenticate(authentication);

        Collection<GrantedAuthority> extraAuthorities = loadUserAuthorities(userData, username, password);

        UserDetails user = userDetailsContextMapper.mapUserFromContext(userData, username, extraAuthorities);

        return createSuccessfulAuthentication(userToken, user);
    } catch (PasswordPolicyException ppe) {
        // The only reason a ppolicy exception can occur during a bind is that the account is locked.
        throw new LockedException(
                messages.getMessage(ppe.getStatus().getErrorCode(), ppe.getStatus().getDefaultMessage()));
    } catch (UsernameNotFoundException notFound) {
        if (hideUserNotFoundExceptions) {
            throw new BadCredentialsException(
                    messages.getMessage("LdapAuthenticationProvider.badCredentials", "Bad credentials"));
        } else {
            throw notFound;
        }
    } catch (NamingException ldapAccessFailure) {
        throw new AuthenticationServiceException(ldapAccessFailure.getMessage(), ldapAccessFailure);
    }
}