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:nz.net.orcon.kanban.security.JcrAuthenticationProvider.java

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

    String username = authIn.getName();
    String password = authIn.getCredentials().toString();

    logger.info("Authenticated Request - user: " + username);

    ObjectContentManager ocm = null;/*from   ww  w. j  a va2s  . co m*/

    try {
        ocm = ocmFactory.getOcm();

        User user = (User) ocm.getObject(User.class, String.format(URI.USER_URI, username));
        if (user != null && user.checkPassword(password)) {
            logger.info("Authenticated User: " + username);
            List<GrantedAuthority> grantedAuths = this.securityTool.getRoles(username);
            Authentication auth = new UsernamePasswordAuthenticationToken(username, password, grantedAuths);
            return auth;
        } else {
            logger.warn("Authentication Failure: " + username);
        }
    } catch (Exception e) {
        logger.error("Authentication Exception: " + username, e);
    } finally {
        if (ocm != null) {
            ocm.logout();
        }
    }

    return null;
}

From source file:com.t2tierp.controller.LoginController.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String nomeUsuario = authentication.getName();
    String senha = authentication.getCredentials().toString();
    try {/*from   w ww  .  j av a 2  s  .co  m*/
        InitialContext initialContext = new InitialContext();
        dao = (UsuarioDAO) initialContext.lookup("java:comp/ejb/usuarioDAO");

        Md5PasswordEncoder enc = new Md5PasswordEncoder();
        senha = enc.encodePassword(nomeUsuario + senha, null);
        Usuario usuario = dao.getUsuario(nomeUsuario, senha);
        if (usuario != null) {
            List<PapelFuncao> funcoes = dao.getPapelFuncao(usuario);
            List<GrantedAuthority> grantedAuths = new ArrayList<>();
            for (PapelFuncao p : funcoes) {
                grantedAuths.add(new SimpleGrantedAuthority(p.getFuncao().getNome()));
            }
            Authentication auth = new UsernamePasswordAuthenticationToken(nomeUsuario, senha, grantedAuths);

            return auth;
        }
    } catch (Exception e) {
        //e.printStackTrace();
    }
    return null;
}

From source file:org.openengsb.opencit.ui.web.LoginPageTest.java

private void mockAuthentication() {
    AuthenticationManager authManager = mock(AuthenticationManager.class);
    final Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new GrantedAuthorityImpl("ROLE_USER"));
    when(authManager.authenticate(any(Authentication.class))).thenAnswer(new Answer<Authentication>() {
        @Override//w  w  w .j a v  a 2  s  . c  o m
        public Authentication answer(InvocationOnMock invocation) {
            Authentication auth = (Authentication) invocation.getArguments()[0];
            if (auth.getCredentials().equals("password")) {
                return new UsernamePasswordAuthenticationToken(auth.getPrincipal(), auth.getCredentials(),
                        authorities);
            }
            throw new BadCredentialsException("wrong password");
        }
    });
    contextMock.putBean("authenticationManager", authManager);
}

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.
 *///  w  ww . ja  v  a2 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:cz.muni.pa165.carparkapp.configuration.MyAuthenticationProvider.java

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

    password = DigestUtils.shaHex(password);
    Employee user = null;//from   w w  w .  ja va  2  s .  co m

    for (Employee e : dao.getAllEmployees()) {
        //System.out.println(e);
        if (e.getUserName().equals(username)) {
            user = e;
            break;
        }
    }

    if (user == null) {
        throw new BadCredentialsException("Username not found.");
    }

    if (!password.equals(user.getPassword())) {
        throw new BadCredentialsException("Wrong password.");
    }

    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority("ROLE_" + user.getRole()));

    return new UsernamePasswordAuthenticationToken(username, password, authorities);
}

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  ava2  s .  c  om*/

    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:org.deegree.securityproxy.authentication.wass.AddParameterAnonymousAuthenticationFilter.java

private String extractParameterValue(Authentication authResult) {
    Object credentials = authResult.getCredentials();
    if (credentials != null && credentials instanceof String) {
        LOG.debug("authentication parameter " + parameterKey + "=" + credentials);
        return (String) credentials;
    }//from  www .  j  a  va 2s .c om
    return null;
}

From source file:org.n52.oss.ui.services.OSSAuthenticationProvider.java

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

    AuthToken token = authenticateOSS(username, password);

    if (token.auth_token != null) {
        if (!token.isValid)
            throw new UsernameNotFoundException(
                    "Username is not validated please contact site administration!");

        final List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_SCRIPT_AUTHOR"));

        if (token.isAdmin)
            grantedAuths.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        final UserDetails principal = new User(username, token.auth_token, grantedAuths);
        final Authentication auth = new UsernamePasswordAuthenticationToken(principal, token.auth_token,
                grantedAuths);/*from w  ww.j  a va 2  s  .co m*/
        return auth;

    } else
        throw new UsernameNotFoundException("Wrong username/password combination");
}

From source file:nl.surfnet.mujina.spring.security.CustomAuthenticationProvider.java

@SuppressWarnings("serial")
@Override/*from   ww  w .j  av a 2s .c o  m*/
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
    final String name = authentication.getName();
    final String password = authentication.getCredentials().toString();

    /*
     * First check if we know this user. Fallback user if Method.ALL otherwise
     * an Exception
     */
    Authentication authenticationForUser = getAuthenticationForUser(name, password);
    if (idpConfiguration.getAuthentication() == AuthenticationMethod.Method.ALL) {
        return authenticationForUser != null ? authenticationForUser
                : new SimpleAuthentication(name, password,
                        Arrays.asList((GrantedAuthority) new GrantedAuthorityImpl("ROLE_USER"),
                                (GrantedAuthority) new GrantedAuthorityImpl("ROLE_ADMIN")));
    } else {
        if (authenticationForUser == null) {
            throw new AuthenticationException("Can not log in") {
            };
        }
        return authenticationForUser;

    }
}

From source file:nl.surfnet.coin.api.basic.MockBasicAuthenticationManager.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
            authentication.getPrincipal(), authentication.getCredentials(),
            Arrays.asList(new SimpleGrantedAuthority("ROLE_USER")));
    token.setDetails(authentication.getDetails());
    return token;
}