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.nan21.dnet.core.web.controller.session.SessionController.java

/**
 * Process login action//w  w  w.ja  va  2 s  .  c o  m
 * 
 * @param username
 * @param password
 * @param clientCode
 * @param language
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/" + Constants.SESSION_ACTION_LOGIN, method = RequestMethod.POST)
public ModelAndView login(@RequestParam(value = "user", required = true) String username,
        @RequestParam(value = "pswd", required = true) String password,
        @RequestParam(value = "client", required = true) String clientCode,
        @RequestParam(value = "lang", required = false) String language, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    try {

        if (logger.isInfoEnabled()) {
            logger.info("Session request: -> login ");
        }

        if (logger.isDebugEnabled()) {
            logger.debug("  --> request-params: user={}, client={}, pswd=*** ",
                    new String[] { username, clientCode });
        }

        request.getSession().invalidate();
        request.getSession();

        prepareLoginParamsHolder(clientCode, language, request);

        String hashedPass = getMD5Password(password);

        Authentication authRequest = new UsernamePasswordAuthenticationToken(username, hashedPass);
        Authentication authResponse = this.getAuthenticationManager().authenticate(authRequest);
        SecurityContextHolder.getContext().setAuthentication(authResponse);

        response.sendRedirect(Constants.URL_DNET_UI_EXTJS);
        return null;
    } catch (Exception e) {
        ModelAndView err = this.showLogin(request, response);
        String msg = "Authentication failed. ";
        if (e.getMessage() != null && !"".equals(e.getMessage())) {
            msg += e.getMessage();
        }
        err.getModel().put("error", msg);
        return err;
    }
}

From source file:org.unidle.service.UserServiceImplTest.java

@Test
public void testIsCurrentUserWithSameEmail() throws Exception {

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

    final boolean result = subject.isCurrentUser("email@example.com");

    assertThat(result).isTrue();
}

From source file:org.cloudfoundry.identity.uaa.oauth.JwtTokenEnhancerTests.java

@Test
public void publicKeyStringIsReturnedFromTokenKeyEndpoint() throws Exception {
    tokenEnhancer.setVerifierKey("-----BEGIN RSA PUBLIC KEY-----\n"
            + "MGgCYQDk3m+AGfjcDrT4fspyIBqmulFjVXuiciYvpaD5j2XaR7c6Krm5wsBLOiUo\n"
            + "kmd6wbrRAMPMpoC1eogWNNoXY7Jd4eWdDVmscfHczGX13uBKXwdOCEqKqoWQsXIb\n" + "7kgz+HkCAwEAAQ==\n"
            + "-----END RSA PUBLIC KEY-----");
    Map<String, String> key = tokenEnhancer.getKey(new UsernamePasswordAuthenticationToken("foo", "bar"));
    assertTrue("Wrong key: " + key, key.get("value").contains("-----BEGIN"));
}

From source file:cn.org.once.cstack.explorer.FileControllerTestIT.java

@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();
    User user = null;/* w w  w . j a va 2s. 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:net.kamhon.ieagle.security.AuthenticationUtil.java

public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response,
        String username, String password) throws AuthenticationException {
    if (postOnly && !request.getMethod().equals("POST")) {
        throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
    }//from  w w w  .  j  a va2 s .co  m

    /*String username = obtainUsername(request);
    String password = obtainPassword(request);*/

    if (username == null) {
        username = "";
    }

    if (password == null) {
        password = "";
    }

    username = username.trim();

    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,
            password);

    // Place the last username attempted into HttpSession for views
    HttpSession session = request.getSession(false);

    if (session != null || getAllowSessionCreation()) {
        request.getSession().setAttribute(SPRING_SECURITY_LAST_USERNAME_KEY,
                TextEscapeUtils.escapeEntities(username));
    }

    // Allow subclasses to set the "details" property
    setDetails(request, authRequest);

    return this.getAuthenticationManager().authenticate(authRequest);
}

From source file:org.wicketopia.example.web.page.BasePage.java

@Override
protected void onInitialize() {
    super.onInitialize();
    setOutputMarkupId(true);//from www . j a  v a 2 s. co  m
    add(new Label("titleLabel", getTitleModel()).setRenderBodyOnly(true));
    add(new Label("captionLabel", getCaptionModel()).setRenderBodyOnly(true));
    add(new Label("copyrightLabel", resourceModel("page.copyright", new GregorianCalendar().get(Calendar.YEAR)))
            .setEscapeModelStrings(false));

    add(new FeedbackPanel("feedback").setOutputMarkupPlaceholderTag(true));
    add(new BookmarkablePageLink<Void>("homeLink", HomePage.class));
    add(new Link("login") {
        @Override
        public void onClick() {
            final UsernamePasswordAuthenticationToken tok = new UsernamePasswordAuthenticationToken("admin",
                    "admin");
            SecurityContextHolder.getContext().setAuthentication(authenticationManager.authenticate(tok));
            setResponsePage(BasePage.this.getClass());
        }

        @Override
        public boolean isVisible() {
            return SecurityContextHolder.getContext().getAuthentication() == null;
        }
    });
    add(new Link("logout") {
        @Override
        public void onClick() {
            SecurityContextHolder.clearContext();
            setResponsePage(BasePage.this.getClass());
        }

        @Override
        public boolean isVisible() {
            return SecurityContextHolder.getContext().getAuthentication() != null;
        }
    });
}

From source file:org.osiam.security.helper.FBClientCredentialsTokenEndpointFilter.java

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String clientId = request.getParameter("client_id");
    String clientSecret = request.getParameter("client_secret");
    if (clientId == null) {
        return null;
    }/*w w w . j  a va  2s  .  c  om*/
    if (clientSecret == null) {
        clientSecret = "";
    }
    clientId = clientId.trim();
    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(clientId,
            clientSecret);
    return this.getAuthenticationManager().authenticate(authRequest);

}

From source file:waffle.spring.WindowsAuthenticationProviderTests.java

/**
 * Test authenticate with custom granted authority factory.
 *//*ww  w.  j ava 2s. co m*/
@Test
public void testAuthenticateWithCustomGrantedAuthorityFactory() {
    this.provider.setDefaultGrantedAuthority(null);
    this.provider.setGrantedAuthorityFactory(new FqnGrantedAuthorityFactory(null, false));

    final MockWindowsIdentity mockIdentity = new MockWindowsIdentity(WindowsAccountImpl.getCurrentUsername(),
            new ArrayList<String>());
    final WindowsPrincipal principal = new WindowsPrincipal(mockIdentity);
    final UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
            principal, "password");

    final Authentication authenticated = this.provider.authenticate(authentication);
    Assert.assertNotNull(authenticated);
    Assert.assertTrue(authenticated.isAuthenticated());
    final Collection<? extends GrantedAuthority> authorities = authenticated.getAuthorities();
    final Iterator<? extends GrantedAuthority> authoritiesIterator = authorities.iterator();
    Assert.assertEquals(2, authorities.size());

    final List<String> list = new ArrayList<>();
    while (authoritiesIterator.hasNext()) {
        list.add(authoritiesIterator.next().getAuthority());
    }
    Collections.sort(list);
    Assert.assertEquals("Everyone", list.get(0));
    Assert.assertEquals("Users", list.get(1));
    Assert.assertTrue(authenticated.getPrincipal() instanceof WindowsPrincipal);
}

From source file:cn.org.once.cstack.modules.ModulesControllerTestIT.java

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

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

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

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

}