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:net.gplatform.sudoor.server.security.model.auth.SSAuth.java

/**
 * WARNING: Normally this is used by non-web interface. For web interface,
 * pls use Spring Security config to auto authenticate Here there is no
 * signin, if you want to signin after authenticate pls use
 * authenticateAndSignin/*from w  w  w  . ja v  a  2 s .  c o m*/
 * 
 * @param username
 * @param password
 */
public void authenticate(String username, String password) {
    logger.debug("Authenticate:" + username);

    Authentication request = new UsernamePasswordAuthenticationToken(username, password);
    authenticationManager.authenticate(request);
}

From source file:com.edgenius.wiki.service.impl.TestVolumnPageService.java

@Before
public void setUp() throws IOException {

    System.out.println("Load test file from URL:"
            + this.getClass().getClassLoader().getResource("testcase/pageservice/samplepagecontent.txt"));
    URL samplePage = this.getClass().getClassLoader().getResource("testcase/pageservice/samplepagecontent.txt");
    content = FileUtils.readFileToString(new File(samplePage.getPath()));

    System.out.println("Load test file from URL:"
            + this.getClass().getClassLoader().getResource("testcase/pageservice/spacelist.txt"));
    URL spaceList = this.getClass().getClassLoader().getResource("testcase/pageservice/spacelist.txt");
    spaces = FileUtils.readLines(new File(spaceList.getPath()));

    HttpServletRequest request = new MockHttpServletRequest() {

        public String getRemoteUser() {
            return "admin";
        }//  w w w. ja v a2s. c  o  m

    };
    ServletUtils.setRequest(request);
    //      MockServletContext servletContext = new MockServletContext();
    //      WebApplicationContext springContext;
    //      servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE   , springContext);
    //      ServletUtils.setServletContext(servletContext);

    Authentication authentication = new UsernamePasswordAuthenticationToken("admin", "admin");
    SecurityContextHolder.getContext().setAuthentication(authentication);
    //create spaces
    for (String uname : spaces) {
        Space space = new Space();
        space.setUnixName(uname);
        space.setName("Title:" + uname);
        space.setDescription("Description:" + uname);
        WikiUtil.setTouchedInfo(userReadingService, space);
        try {
            spaceService.createSpace(space);
        } catch (SpaceException e) {
            e.printStackTrace();
            Assert.fail(e.toString());
        }
    }
}

From source file:com.evolveum.midpoint.web.security.MidPointAuthWebSession.java

@Override
public boolean authenticate(String username, String password) {
    LOGGER.debug("Authenticating '{}' {} password in web session.",
            new Object[] { username, (StringUtils.isEmpty(password) ? "without" : "with") });

    boolean authenticated;
    try {//  www  .j  av a  2  s .  com
        Authentication authentication = authenticationProvider
                .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        authenticated = authentication.isAuthenticated();

        auditEvent(authentication, username, OperationResultStatus.SUCCESS);
    } catch (AuthenticationException ex) {
        String key = ex.getMessage() != null ? ex.getMessage() : "web.security.provider.unavailable";
        MidPointApplication app = (MidPointApplication) getSession().getApplication();
        error(app.getString(key));

        LOGGER.debug("Couldn't authenticate user.", ex);
        authenticated = false;

        auditEvent(null, username, OperationResultStatus.FATAL_ERROR);
    }

    return authenticated;
}

From source file:org.unidle.controller.UpdateAccountControllerTest.java

@Test
public void testAccount() throws Exception {
    SecurityContextHolder.getContext()//from  ww  w .  j av  a2s. c om
            .setAuthentication(new UsernamePasswordAuthenticationToken(user.getUuid(), null));

    subject.perform(get("/account/update")).andExpect(status().isOk())
            .andExpect(view().name(".ajax.update-account"))
            .andExpect(model().attribute("userForm",
                    allOf(hasProperty("email", equalTo("email@example.com")),
                            hasProperty("firstName", equalTo("first name")),
                            hasProperty("lastName", equalTo("last name")))));
}

From source file:org.vaadin.spring.security.internal.AbstractVaadinSecurity.java

@Override
public Authentication login(String username, String password, boolean rememberMe)
        throws AuthenticationException, Exception {
    return login(new UsernamePasswordAuthenticationToken(username, password), rememberMe);
}

From source file:com.gm.machine.web.RegisterAction.java

@Override
public String save() throws Exception {
    try {//from   w  w  w.j  a  v  a2  s.  co  m
        HttpServletRequest request = Struts2Utils.getRequest();
        String rcode = Struts2Utils.getParameter("rcode");
        String scode = (String) Struts2Utils.getSession().getAttribute("scode");
        if (StringUtils.isBlank(rcode)) {
            this.tip = "??!";
            return input();
        } else {
            if (!rcode.equalsIgnoreCase(scode)) {
                this.tip = "??!";
                return input();
            }

        }
        userManager.save(entity);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                entity.getLoginName(), entity.getPassword());
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authenticatedUser = authenticationManager.authenticate(token);

        SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
        request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                SecurityContextHolder.getContext());

        entity.setLastLoginDate(new Date());// ?
        entity.setLoginTimes(entity.getLoginTimes() + 1);// 
        userManager.save(entity);
        request.getSession().setAttribute("loginuser", entity);
        request.getSession().setAttribute("userid", entity.getId());
    } catch (Exception e) {
        this.addActionMessage(Global.SAVE_LOSE);
        e.printStackTrace();
    }
    return RELOAD;
}

From source file:org.cloudfoundry.tools.security.CloudFoundryAuthenticationProviderTest.java

@Test
public void shouldNotAuthenticateIfNotInActiveUsers() throws Exception {
    setupEnvironment("user@cloudfoundry.com");
    Authentication authentication = new UsernamePasswordAuthenticationToken("missing@cloudfoundry.com",
            "password");
    this.thrown.expect(BadCredentialsException.class);
    this.authenticationProvider.authenticate(authentication);
}

From source file:cn.org.once.cstack.servers.AbstractApplicationControllerTestIT.java

@Before
public void setup() throws Exception {
    logger.info("setup");

    this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();

    User user = null;/*www.  j a  va2  s.c o m*/
    try {
        user = userService.findByLogin("johndoe");
    } catch (ServiceException e) {
        logger.error(e.getLocalizedMessage());
    }

    Authentication authentication = null;
    if (user != null) {
        authentication = new UsernamePasswordAuthenticationToken(user.getLogin(), user.getPassword());
    }
    Authentication result = authenticationManager.authenticate(authentication);
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(result);
    session = new MockHttpSession();
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext);
}

From source file:eu.freme.broker.security.ManagementEndpointAuthenticationFilter.java

private Authentication tryToAuthenticateWithUsernameAndPassword(Optional<String> username,
        Optional<String> password) {
    UsernamePasswordAuthenticationToken requestAuthentication = new UsernamePasswordAuthenticationToken(
            username, password);/*from www. j a v  a 2s  .  co  m*/
    return tryToAuthenticate(requestAuthentication);
}

From source file:org.unidle.controller.CreateQuestionControllerTest.java

@Test
public void testQuestionPost() throws Exception {
    SecurityContextHolder.getContext()// w  w  w  .  j a  v a  2s .c  o  m
            .setAuthentication(new UsernamePasswordAuthenticationToken(user.getUuid(), null));

    subject.perform(fileUpload("/question/create").param("question", "this is a test question"))
            .andExpect(view().name(startsWith("redirect:/question/")));

    assertThat(questionRepository.count()).isEqualTo(1L);
    assertThat(questionRepository.findAll().get(0).getTags()).isEmpty();
}