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) 

Source Link

Document

This constructor can be safely used by any code that wishes to create a UsernamePasswordAuthenticationToken, as the #isAuthenticated() will return false.

Usage

From source file:org.callistasoftware.netcare.core.support.TestSupport.java

protected void runAs(final UserBaseView user) {
    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(user, null));
}

From source file:de.tudarmstadt.ukp.csniper.webapp.security.SpringAuthenticatedWebSession.java

@Override
public boolean authenticate(String username, String password) {
    boolean authenticated = false;
    try {//  w  ww .j a v a  2  s  . c o  m
        Authentication authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        authenticated = authentication.isAuthenticated();
    } catch (AuthenticationException e) {
        log.warn(format("User '%s' failed to login. Reason: %s", username, e.getMessage()));
        error(format("User '%s' failed to login. Reason: %s", username, e.getMessage()));
        authenticated = false;
    }
    return authenticated;
}

From source file:business.SelectionControllerTests.java

protected UserAuthenticationToken getRequester() {
    User user = userService.findByUsername("test+requester@dntp.thehyve.nl");
    Authentication authentication = new UsernamePasswordAuthenticationToken(user, "requester");
    return (UserAuthenticationToken) authenticationProvider.authenticate(authentication);
}

From source file:de.interseroh.report.test.security.LdapServerTest.java

@Test
public void testJndiSpring() throws Exception {
    DefaultSpringSecurityContextSource ctxSrc = new DefaultSpringSecurityContextSource(
            "ldap://ldap.xxx:389/OU=xxx");

    ctxSrc.setUserDn(USER_LDAP);/*from   w ww  . ja v  a2  s.  c  o  m*/
    ctxSrc.setPassword(PASSWORD_LDAP);

    ctxSrc.afterPropertiesSet();

    logger.info("Base LDAP Path: " + ctxSrc.getBaseLdapPath());
    logger.info("Principal: " + ctxSrc.getAuthenticationSource().getPrincipal().toString());
    logger.info("Credentials: " + ctxSrc.getAuthenticationSource().getCredentials());

    Authentication bob = new UsernamePasswordAuthenticationToken("bob", "bob");

    BindAuthenticator authenticator = new BindAuthenticator(ctxSrc);
    authenticator.setUserSearch(
            new FilterBasedLdapUserSearch("", "(&(objectCategory=Person)(sAMAccountName={0}))", ctxSrc));
    authenticator.afterPropertiesSet();

    authenticator.authenticate(bob);

    DirContextOperations user = authenticator.authenticate(bob);

    logger.info("User: {}", user);
}

From source file:com.javiermoreno.springboot.rest.AuthenticationTokenProcessingFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    String encryptedToken = request.getHeader("X-Auth-Token");
    if (SecurityContextHolder.getContext().getAuthentication() == null && encryptedToken != null) {
        Token token = new Token(cryptoService, encryptedToken);
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null) {
            ip = request.getRemoteAddr();
        }// ww  w. ja v a  2 s . c o  m
        if (ip.equals(token.getIp()) == true && token.isExpired() == false) {
            UserDetails userDetails = userDetailsService.loadUserByUsername(token.getUsername());
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails.getUsername(), userDetails.getPassword());
            authentication.setDetails(
                    new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request));
            SecurityContextHolder.getContext()
                    .setAuthentication(authenticationManager.authenticate(authentication));
        }

    }
    chain.doFilter(req, res);
}

From source file:hsa.awp.user.security.TestIntegrationLdapSpringSecurity.java

@Test
public void testArampp() {

    Authentication auth = new UsernamePasswordAuthenticationToken("arampp", "IbI98S35");
    securityContext.setAuthentication(auth);
    ldapAuthProvider.authenticate(auth);
}

From source file:net.solarnetwork.central.dras.biz.alert.test.SimpleAlertBizTest.java

@Before
public void setupSecurity() {
    SecurityContextHolder.getContext()//from  www  . ja  v  a  2s .c o m
            .setAuthentication(new UsernamePasswordAuthenticationToken(TEST_USERNAME, "unittest"));
}

From source file:com.healthcit.cacure.test.DataSetTestExecutionListener.java

public void beforeTestMethod(TestContext testContext) throws Exception {
    // Determine if a dataset should be loaded, from where, and extract any
    // special configuration.
    Configuration configuration = determineConfiguration(testContext.getTestClass(),
            testContext.getTestMethod());

    if (configuration == null)
        return;//from  w w  w.  ja  va  2  s. c o m

    SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
            configuration.getUserName(), configuration.getUserPassword()));

    if (configuration.getLocation() == null)
        return;

    configurationCache.put(testContext.getTestMethod(), configuration);

    // Find a single, unambiguous data source.
    DataSource dataSource = lookupDataSource(testContext);

    // Fetch a connection from the data source, using an existing one if we're
    // already participating in a transaction.
    Connection connection = DataSourceUtils.getConnection(dataSource);
    configuration.setConnectionTransactional(DataSourceUtils.isConnectionTransactional(connection, dataSource));

    // Load the data set.
    loadData(configuration, connection);
}

From source file:org.red5.server.plugin.admin.client.AuthClientRegistry.java

@SuppressWarnings("unchecked")
@Override/*  w  w  w  .java2s  .  c  om*/
public IClient newClient(Object[] params) throws ClientNotFoundException, ClientRejectedException {
    log.debug("New client - params: {}, {}, {}", params);

    if (params == null || params.length == 0) {
        log.warn("Client didn't pass a username.");
        throw new ClientRejectedException();
    }

    String username, passwd;
    if (params[0] instanceof HashMap) {
        // Win FP sends HashMap
        HashMap userWin = (HashMap) params[0];
        username = (String) userWin.get(0);
        passwd = (String) userWin.get(1);
    } else if (params[0] instanceof ArrayList) {
        // Mac FP sends ArrayList
        ArrayList userMac = (ArrayList) params[0];
        username = (String) userMac.get(0);
        passwd = (String) userMac.get(1);
    } else {
        throw new ClientRejectedException();
    }

    UsernamePasswordAuthenticationToken t = new UsernamePasswordAuthenticationToken(username, passwd);

    masterScope = Red5.getConnectionLocal().getScope();

    ProviderManager mgr = (ProviderManager) masterScope.getContext().getBean("authenticationManager");
    try {
        log.debug("Checking password: {}", passwd);
        t = (UsernamePasswordAuthenticationToken) mgr.authenticate(t);
    } catch (BadCredentialsException ex) {
        log.debug("{}", ex);
        throw new ClientRejectedException();
    }

    if (t.isAuthenticated()) {
        client = new AuthClient(nextId(), this);
        addClient(client);
        client.setAttribute("authInformation", t);
        log.debug("Authenticated client - username: {}, id: {}", new Object[] { username, client.getId() });
    }

    return client;
}

From source file:com.sorception.jscrap.services.UserService.java

@PreAuthorize("isAnonymous() || hasRole('ROLE_ADMIN')")
public String authenticateUser(String username, String password) {
    try {/*w  w  w.  jav  a  2  s  . c  om*/
        logger.info("Generating auth token for user " + username + "...");
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
        this.authenticationManager.authenticate(token);
        return this.getAuthentication(username, password);
    } catch (BadCredentialsException es) {
        throw new AuthenticationException("Bad credentials for user " + username);
    }
}