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.springsource.greenhouse.account.UsernamePasswordAuthenticationProvider.java

private Authentication authenticatedToken(Account account, Authentication original) {
    List<GrantedAuthority> authorities = null;
    UsernamePasswordAuthenticationToken authenticated = new UsernamePasswordAuthenticationToken(account, null,
            authorities);/* w ww  .  j  av a 2  s .  co m*/
    authenticated.setDetails(original.getDetails());
    return authenticated;
}

From source file:com.github.sshw.security.SSHAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    SSHSession sshSession = new SSHSessionImpl();
    //UsernamePasswordAuthenticationToken request = (UsernamePasswordAuthenticationToken) authentication;
    String username = authentication.getPrincipal().toString();
    String password = authentication.getCredentials().toString();
    //log.info("{}:{}", username, password);
    boolean success = sshSession.login(username, password);
    log.info("SSH login: {}={}", username, success);
    Authentication result = new UsernamePasswordAuthenticationToken(username, password, authorities);
    //result.setAuthenticated(success);
    log.info("adding SSH session for {}", username);
    sshSessionManager.sessionsByUsername.put(username, sshSession);
    return result;
}

From source file:org.exoplatform.acceptance.security.CrowdAuthenticationProviderMock.java

/**
 * {@inheritDoc}/*from ww w  .  j  a  va 2s. com*/
 * Performs authentication with the same contract as {@link
 * org.springframework.security.authentication.AuthenticationManager#authenticate(Authentication)}.
 */
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();
    try {
        UserDetails user = crowdUserDetailsServiceMock.loadUserByUsername(name);
        if (user.getPassword().equals(password)) {
            return new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword(),
                    user.getAuthorities());
        } else {
            throw new BadCredentialsException("Invalid username or password");
        }
    } catch (UsernameNotFoundException unnfe) {
        throw new BadCredentialsException("Invalid username or password", unnfe);
    }
}

From source file:com.exp.tracker.services.impl.JpaExpenseServiceTests.java

@Before
public void setup() {
    userDetailService = ctx.getBean(JdbcDaoImpl.class);
    UserDetails userDetails = userDetailService.loadUserByUsername("Admin");
    Authentication authToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(),
            userDetails.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(authToken);
    rCtx = new MockRequestContext();
    MockExternalContext ec = new MockExternalContext();
    ec.setCurrentUser("Admin");
    ((MockRequestContext) rCtx).setExternalContext(ec);
    // Add 1st user
    UserBean ub1 = new UserBean();
    ub1.setEmailId("a@b.com");
    ub1.setEnabled(true);// w  w w  .ja  va  2 s  .  c  o m
    ub1.setFirstName("Test1");
    ub1.setLastName("User1");
    ub1.setMiddleInit("1");
    ub1.setPassword("password");
    ub1.setUsername("testuser1");
    UserBean userBean1 = userService.addUser(ub1, rCtx);
    Assert.assertNotNull("Failed to create user1. Why", userBean1);
    //
    // Add 1st user
    UserBean ub2 = new UserBean();
    ub2.setEmailId("a@b.com");
    ub2.setEnabled(true);
    ub2.setFirstName("Test2");
    ub2.setLastName("User2");
    ub2.setMiddleInit("2");
    ub2.setPassword("password");
    ub2.setUsername("testuser2");
    UserBean userBean2 = userService.addUser(ub2, rCtx);
    Assert.assertNotNull("Failed to create user2", userBean2);
    // Setup an expense
    ExpenseDetail ed = new ExpenseDetail();
    ed.setAmount(20.0F);
    ed.setCategory("Somecategory");
    ed.setCreatedBy("Admin");
    ed.setDate(new Date());
    ed.setDescription("Some Expense");
    ed.setPaidBy("testuser1");
    ed.setSettlementId(null);
    // now set shares
    UserShare us1 = new UserShare("testuser1", 10.0F, 0.0F, true);
    UserShare us2 = new UserShare("testuser2", 10.0F, 0.0F, true);
    ed.getUserShares().add(us1);
    ed.getUserShares().add(us2);
    //
    expenseDetail = ed;

}

From source file:com.corporate.transport.authentication.FacebookAuthenticationProvider.java

public Authentication authenticate(Authentication authentication) {

    System.out.println("FacebookAuthenticationProvider.authenticate()");

    UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;

    String username = auth.getName();
    String password = (String) auth.getCredentials();

    //TEST      /*  ww  w.  j  a  va  2  s. c o m*/
    try {
        System.out.println("GOING FOR VALIDATION");
        LDAPAuthentication ldap = new LDAPAuthentication();
        if (ldap.authenticate(username, password)) {
            List<GrantedAuthority> grantedAuthoritiesList = new ArrayList<GrantedAuthority>();

            if (username != null && (username.equals("patel286@avaya.com"))) {
                grantedAuthoritiesList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));
            } else {
                grantedAuthoritiesList.add(new GrantedAuthorityImpl("ROLE_USER"));
            }

            return new UsernamePasswordAuthenticationToken(username, null, grantedAuthoritiesList);
        }

    } catch (Exception e) {

        if (e instanceof AuthenticationException) {
            throw new BadCredentialsException("Incorrect Email Id or Password - Jayesh");
        }
        //TODO [SM] Add logging for specific exception
        else if (e instanceof CommunicationException) {
            throw new LDAPConnectivityException("There is some error connecting with LDAP");
        } else if (e instanceof NamingException) {
            throw new LDAPConnectivityException("There is some error connecting with LDAP");
        } else {
            throw new LDAPConnectivityException("There is some error connecting with LDAP");
        }
    }

    //PRODUCTION      
    /*      try{
       System.out.println("GOING FOR VALIDATION");
       com.corporate.ldap.Authentication ldap = new com.corporate.ldap.Authentication();
       status = ldap.authenticate(username, password);
            
       System.out.println("GOING FOR VALIDATION STATUS:"+status);
       if(status==1){
    List<GrantedAuthority> grantedAuthoritiesList = new ArrayList<GrantedAuthority>();
            
    if(username!=null && username.equals("jayesh.patel")){
       grantedAuthoritiesList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));   
    }else{
       grantedAuthoritiesList.add(new GrantedAuthorityImpl("ROLE_USER"));
    }
            
    return new UsernamePasswordAuthenticationToken(username, null, grantedAuthoritiesList);
            
       }else if(status==0){
    throw new BadCredentialsException("Incorrect Email Id or Password.");
            
       }else if(status==2){
    throw new LDAPConnectivityException("There is some error connecting with LDAP");
       }
            
    }catch (Exception e) {
       e.printStackTrace();
    }*/

    return null;

}

From source file:org.opentides.util.SecurityUtilTest.java

@Test
public void testGetSessionUserNotInstanceSessionUser() {
    List<GrantedAuthority> auths = new ArrayList<>();
    auths.add(new SimpleGrantedAuthority("ROLE1"));
    auths.add(new SimpleGrantedAuthority("ROLE2"));

    UserDetails userDetails = new User("admin", "password", auths);
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
            null, auths);/*  w  w  w  . j a  v a2 s . c o  m*/
    SecurityContextHolder.getContext().setAuthentication(authentication);

    SessionUser actual = SecurityUtil.getSessionUser();
    assertNull(actual);
}

From source file:com.codesolid.goalboost.social.SimpleSignInAdapter.java

@Override
public String signIn(String localUserId, Connection<?> connection, NativeWebRequest request) {
    Logger logger = LoggerFactory.getLogger(SimpleSignInAdapter.class);
    logger.info(//  w w w.  j a va2  s  .  c  o  m
            "Inside SimpleSignInAdapter.signIn, localUserId = " + localUserId == null ? "NULL" : localUserId);
    logger.info("Getting security context.");
    SecurityContext context = SecurityContextHolder.getContext();
    logger.info("Calling loadUserByUserName.");
    UserDetails user = siteUserDetailsService.loadUserByUsername(localUserId);
    logger.info("Creating UserPasswordAuthenticationToken.");
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, null, null);
    logger.info("Setting token on context");
    context.setAuthentication(token);
    logger.info("Returning null");
    return null;
    //return extractOriginalUrl(request);
}

From source file:org.shredzone.cilla.ws.cxf.CillaRemoteAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    if (!(authentication.getPrincipal() instanceof RemoteUserDetails)) {
        throw new InsufficientAuthenticationException(
                "authentication must contain a RemoteUserDetails principal");
    }// w  w w.j av a 2  s . com

    try {
        RemoteUserDetails userDetails = (RemoteUserDetails) authentication.getPrincipal();

        List<GrantedAuthority> authorities = loginWs.authenticate().getRights().stream()
                .map(SimpleGrantedAuthority::new).collect(toList());

        userDetails.setAuthorities(authorities);
        userDetails.setUser(userWs.fetchByLogin(userDetails.getUsername()));

        return new UsernamePasswordAuthenticationToken(userDetails, null, authorities);
    } catch (SOAPFaultException ex) {
        throw new BadCredentialsException(ex.getMessage());
    } catch (CillaServiceException ex) {
        throw new AuthenticationServiceException("couldn't get user details", ex);
    }
}

From source file:org.statefulj.webapp.services.impl.UserSessionServiceImpl.java

@Override
public void login(HttpSession session, User user) {
    UserDetails userDetails = this.getDetails(user);
    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails,
            user.getPassword(), userDetails.getAuthorities());
    SecurityContextHolder.getContext().setAuthentication(auth);
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            SecurityContextHolder.getContext());
}

From source file:org.socialhistoryservices.pid.service.StubPidResourceServiceTest.java

@BeforeClass
public static void setup() throws Exception {

    if (System.getProperty("pid.properties") == null) // -Dhandle.properties=pid.properties
        System.setProperty("pid.properties", "server/pid.properties");

    class Grant implements GrantedAuthority {

        private String authority;

        public Grant(String authority) {
            this.authority = authority;
        }/*from ww w  .ja v  a 2  s  .  co  m*/

        @Override
        public String getAuthority() {
            return authority;
        }
    }
    final Collection<GrantedAuthority> authorities = new ArrayList(4);
    authorities.add(new Grant("ROLE_PID-WEBSERVICE-USER"));
    authorities.add(new Grant("ROLE_PID-WEBSERVICE-USER_00000.1"));
    authorities.add(new Grant("ROLE_PID-WEBSERVICE-USER_" + na));
    authorities.add(new Grant("ROLE_PID-WEBSERVICE-USER_00000.2"));
    ClientToken clientToken = new ClientToken("test-client", UUID.randomUUID().toString(), null);
    UsernamePasswordAuthenticationToken usernamePasswordAuthentication = new UsernamePasswordAuthenticationToken(
            null, null, authorities);
    OAuth2Authentication auth2Authentication = new OAuth2Authentication(clientToken,
            usernamePasswordAuthentication);
    final SecurityContext context = SecurityContextHolder.getContext();
    context.setAuthentication(auth2Authentication);
}