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.unidle.service.UserServiceImplTest.java

@Test
public void testCurrentUserWIthInvalidAuthentication() throws Exception {

    SecurityContextHolder.getContext()// w w  w  .  j  ava2 s . c  om
            .setAuthentication(new UsernamePasswordAuthenticationToken(UUID.randomUUID(), null));

    final User result = subject.currentUser();

    assertThat(result).isNull();
}

From source file:org.sharetask.service.AuthenticationServiceTest.java

@Test
public void testPasswordEncoding() throws NoSuchAlgorithmException, NoSuchProviderException {
    final ArrayList<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
    list.add(new SimpleGrantedAuthority(Role.ROLE_USER.name()));
    list.add(new SimpleGrantedAuthority(Role.ROLE_ADMINISTRATOR.name()));
    final User u = new UserDetailsImpl("dev1@shareta.sk", "password",
            "6ef7a5723d302c64d65d02f5c6662dc61bebec930ea300620bc9ff7f12b49fda11e2e57933526fd3b73840b0693a7cf4abe05fbfe16223d4bd42eb3043cf5d24",
            list);/*from w  w  w  .  j a v  a  2s.com*/
    final String password = passwordEncoder.encodePassword("password", saltSource.getSalt(u));
    final org.sharetask.entity.UserAuthentication user = userRepository.findOne(u.getUsername());
    assertEquals(password, user.getPassword());
    final Authentication authentication = new UsernamePasswordAuthenticationToken("dev1@shareta.sk",
            "password");
    try {
        authenticationManager.authenticate(authentication);
    } catch (final BadCredentialsException e) {
        fail("Problem with authentication: user/password");
    }
}

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

@Test
public void testSigninWhenAuthenticated() throws Exception {

    SecurityContextHolder.getContext()// ww  w  .j  a  va2s  .c  o  m
            .setAuthentication(new UsernamePasswordAuthenticationToken(user.getUuid(), null));

    subject.perform(get("/signin")).andExpect(view().name("redirect:/account"));
}

From source file:cherry.entree.secure.passwd.PasswdControllerImpl.java

@Override
public ModelAndView execute(PasswdForm form, BindingResult binding, Authentication auth, Locale locale,
        SitePreference sitePref, HttpServletRequest request, RedirectAttributes redirAttr) {

    if (binding.hasErrors()) {
        ModelAndView mav = new ModelAndView(PathDef.VIEW_PASSWD_INIT);
        return mav;
    }/*from w w  w  .j  ava2 s  .co m*/

    if (!validateForm(form, binding)) {
        ModelAndView mav = new ModelAndView(PathDef.VIEW_PASSWD_INIT);
        return mav;
    }

    if (!auth.getName().equals(form.getLoginId())) {
        rejectOnCurAuthFailed(binding);
        ModelAndView mav = new ModelAndView(PathDef.VIEW_PASSWD_INIT);
        return mav;
    }

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(auth.getName(),
            form.getPassword());
    try {
        Authentication a = authenticationManager.authenticate(token);
        checkNotNull(a, "AuthenticationManager#authenticate(token): null");
    } catch (AuthenticationException ex) {
        rejectOnCurAuthFailed(binding);
        ModelAndView mav = new ModelAndView(PathDef.VIEW_PASSWD_INIT);
        return mav;
    }

    String password = passwordEncoder.encode(form.getNewPassword());
    if (!passwdService.changePassword(auth.getName(), password)) {
        if (log.isDebugEnabled()) {
            log.debug("Password has not been updated: loginId={0}, password={1}", auth.getName(), password);
        }
        throw new IllegalStateException("");
    }

    UriComponents uc = fromMethodCall(on(PasswdController.class).finish(auth, locale, sitePref, request))
            .build();

    ModelAndView mav = new ModelAndView();
    mav.setView(new RedirectView(uc.toUriString(), true));
    return mav;
}

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

@Test
public void testAccount() throws Exception {
    SecurityContextHolder.getContext()//from   w  w w .  j a va  2s .c om
            .setAuthentication(new UsernamePasswordAuthenticationToken(user.getUuid(), null));

    subject.perform(get("/account")).andExpect(status().isOk()).andExpect(view().name(".account"));
}

From source file:sample.contact.ContactManagerTests.java

private void makeActiveUser(String username) {
    String password = "";

    if ("rod".equals(username)) {
        password = "koala";
    } else if ("dianne".equals(username)) {
        password = "emu";
    } else if ("scott".equals(username)) {
        password = "wombat";
    } else if ("peter".equals(username)) {
        password = "opal";
    }//from www . ja  va  2 s  .  c  om

    Authentication authRequest = new UsernamePasswordAuthenticationToken(username, password);
    SecurityContextHolder.getContext().setAuthentication(authRequest);
}

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

@Test
public void shouldAuthenticateUsingCloudFoundryLogin() throws Exception {
    setupEnvironment("user@cloudfoundry.com");
    given(this.cloudFoundryClient.login()).willReturn("token");
    this.cloudFoundryClientFactory = new CloudFoundryClientFactory() {
        @Override/*from ww  w.  jav a 2  s. c o m*/
        public CloudFoundryClient getCloudFoundryClient(String username, String password,
                String cloudControllerUrl) {
            assertThat(username, is("user@cloudfoundry.com"));
            assertThat(password, is("password"));
            assertThat(cloudControllerUrl, is("https://api.cloudfoundry.com"));
            return CloudFoundryAuthenticationProviderTest.this.cloudFoundryClient;
        }
    };
    Authentication authentication = new UsernamePasswordAuthenticationToken("user@cloudfoundry.com",
            "password");
    Authentication authenticate = this.authenticationProvider.authenticate(authentication);
    verify(this.cloudFoundryClient).login();
    assertThat(authenticate, is(not(nullValue())));
    assertThat(authenticate.getAuthorities().iterator().next().getAuthority(), is("GRANTED_ROLE"));
}

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

@RequestMapping(method = POST, value = "/signup")
public String submit(@Valid final UserForm userForm, final Errors errors, final WebRequest webRequest) {

    final Connection<?> connection = ProviderSignInUtils.getConnection(webRequest);

    if (connection == null) {
        return "redirect:/signin";
    }//from   w w w.  j a  v a  2 s .  c  om

    if (errors.hasErrors()) {
        return ".signup";
    }

    if (userService.exists(userForm.getEmail())) {
        errors.rejectValue("email", "errors.email.exists");

        return ".signup";
    }

    final User user = userService.createUser(userForm.getEmail(), userForm.getFirstName(),
            userForm.getLastName());

    ProviderSignInUtils.handlePostSignUp(user.getUuid().toString(), webRequest);

    final Authentication authentication = new UsernamePasswordAuthenticationToken(user.getId(), null);

    SecurityContextHolder.getContext().setAuthentication(authentication);

    analytics.identify(user.getUuid(), TRAIT_CREATED, user.getCreatedDate().toDate(), TRAIT_EMAIL,
            user.getEmail(), TRAIT_FIRST_NAME, user.getFirstName(), TRAIT_LAST_NAME, user.getLastName());

    analytics.track(user.getUuid(), SIGN_UP);

    return "redirect:/account";
}

From source file:org.unidle.web.CurrentUserMethodArgumentResolverTest.java

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

    final User result = (User) subject.resolveArgument(null, null, null, null);

    assertThat(result).isEqualTo(user);
}

From source file:org.devgateway.toolkit.forms.wicket.SSAuthenticatedWebSession.java

@Override
public boolean authenticate(final String username, final String password) {
    boolean authenticated;
    try {/*from  www.  j  a  v  a  2s. co  m*/
        Authentication authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // httpSession.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
        // SecurityContextHolder.getContext());
        authenticated = authentication.isAuthenticated();

        if (authenticated && rememberMeServices != null) {
            rememberMeServices.loginSuccess(
                    (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest(),
                    (HttpServletResponse) RequestCycle.get().getResponse().getContainerResponse(),
                    authentication);
        }

    } catch (AuthenticationException e) {
        this.setAe(e);
        log.warn("User '{}' failed to login. Reason: {}", username, e.getMessage());
        authenticated = false;
    }
    return authenticated;
}