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:com.mastercard.test.spring.security.LogPrincipalRuleTests.java

@Test
public void ruleDoesNotBreakWhenUserIsProvided() throws Throwable {
    DefaultStatement statement = new DefaultStatement();
    Description description = Description.createTestDescription(MockWithMockUserTest.class.getName(), "test");

    LogPrincipalRule rule = new LogPrincipalRule();

    Statement actual = rule.apply(statement, description);

    SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext());
    SecurityContextHolder.getContext()/*  www.  j  a  v a2 s. c o m*/
            .setAuthentication(new UsernamePasswordAuthenticationToken("user", "password"));

    actual.evaluate();

    assertNotSame(statement, actual);
    assertTrue(statement.isEvaluated());
}

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

@Test(expected = BadCredentialsException.class)
public void testAuthenticateUnknownUser() throws Exception {
    crowdAuthenticationProviderMock.authenticate(new UsernamePasswordAuthenticationToken("foo", "bar"));
}

From source file:com.ram.topup.business.service.authentication.impl.AuthenticationServiceImpl.java

@Override
public UserProfile login(String username, String password) {
    try {// ww  w .  j ava 2 s  .co m
        Authentication authenticate = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(username, password));
        if (authenticate.isAuthenticated()) {
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            return ((ExtendedUserDetailsImpl) authenticate.getPrincipal()).getUser().toUserProfile();
        } else {
            throw new TopupException("Authentication Failed with username=" + username);
        }
    } catch (AuthenticationException e) {
        throw new TopupException("Authentication Error Occured", e);
    }

}

From source file:com.mtt.myapp.AbstractSystemTransactionalTest.java

@Before
public void beforeSetSecurity() {
    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("admin", null);
    SecurityContextImpl context = new SecurityContextImpl();
    context.setAuthentication(token);/*from  ww  w .  ja  v  a2 s.  c  o m*/
    SecurityContextHolder.setContext(context);
}

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

public HomePage() {
    add(new Scaffold<Person>("scaffold", Person.class, persistenceProvider));
    add(new Link("loginAdmin") {
        @Override//  www.  j av  a2  s  .  com
        public void onClick() {
            final UsernamePasswordAuthenticationToken tok = new UsernamePasswordAuthenticationToken("admin",
                    "admin");
            SecurityContextHolder.getContext().setAuthentication(authenticationManager.authenticate(tok));
            setResponsePage(HomePage.class);
            setRedirect(true);
        }

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

    add(new Link("logout") {
        @Override
        public void onClick() {
            SecurityContextHolder.clearContext();
            setResponsePage(HomePage.class);
            setRedirect(true);
        }

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

From source file:eu.freme.common.security.AuthenticationController.java

@RequestMapping(value = "/authenticate", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<String> authenticate(
        @RequestHeader(value = "X-Auth-Username", required = true) String username,
        @RequestHeader(value = "X-Auth-Password", required = true) String password) {

    UsernamePasswordAuthenticationToken requestAuthentication = new UsernamePasswordAuthenticationToken(
            username, password);//  w  ww .  j a  v  a2s  .  c o m
    Authentication resultOfAuthentication = null;
    try {
        Authentication responseAuthentication = authenticationManager.authenticate(requestAuthentication);
        if (responseAuthentication == null || !responseAuthentication.isAuthenticated()) {
            throw new AuthenticationFailedException();
        }
        logger.debug("User successfully authenticated");
        resultOfAuthentication = responseAuthentication;
    } catch (Exception e) {
        logger.error(e);
        throw new AuthenticationFailedException();
    }

    SecurityContextHolder.getContext().setAuthentication(resultOfAuthentication);

    Token token = (Token) resultOfAuthentication.getDetails();

    JSONObject json = new JSONObject();
    json.put("token", token.getToken());

    ResponseEntity<String> response = new ResponseEntity<String>(json.toString(), HttpStatus.OK);
    return response;

}

From source file:com.muk.services.processor.BasicAuthPrincipalProcessor.java

@Override
public void process(Exchange exchange) throws Exception {
    @SuppressWarnings("unchecked")
    final List<Header> httpHeaders = exchange.getIn().getHeader("org.restlet.http.headers", List.class);

    String userpass = "bad:creds";
    for (final Header header : httpHeaders) {
        if (header.getName().toLowerCase().equals(HttpHeaders.AUTHORIZATION.toLowerCase())) {
            userpass = new String(Base64.decodeBase64(
                    (StringUtils.substringAfter(header.getValue(), " ").getBytes(StandardCharsets.UTF_8))),
                    StandardCharsets.UTF_8);
            break;
        }/*from   w w w.  ja v  a 2 s  . c  o m*/
    }

    final String[] tokens = userpass.split(":");

    // create an Authentication object
    // build a new bearer token type
    final UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(tokens[0],
            tokens[1]);

    // wrap it in a Subject
    final Subject subject = new Subject();
    subject.getPrincipals().add(authToken);

    // place the Subject in the In message
    exchange.getIn().setHeader(Exchange.AUTHENTICATION, subject);
}

From source file:com.javaid.bolaky.domain.pool.service.impl.DefaultPoolsServiceIntegrationTests.java

@Before
public void populateUsername() {
    Authentication authentication = new UsernamePasswordAuthenticationToken("Javaid", "Jav");
    SecurityContextHolder.getContext().setAuthentication(authentication);
}

From source file:springchat.rest.AuthenticationRest.java

@RequestMapping(value = "/rest/auth", method = RequestMethod.POST, produces = { "application/json" })
@ResponseBody//from   ww w .  j a  v a2  s .c o m
public AuthenticationResultDto postUser(@RequestParam("user") String user, HttpServletRequest request) {
    AuthenticationResultDto dto = new AuthenticationResultDto();
    dto.setSessionId(request.getSession().getId());
    try {
        // Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated
        AbstractAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, "");
        token.setDetails(new WebAuthenticationDetails(request));
        Authentication authentication = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        dto.setSuccess(Boolean.TRUE);
        request.getSession().setAttribute("authenticated", Boolean.TRUE);
    } catch (Exception e) {
        SecurityContextHolder.getContext().setAuthentication(null);
        dto.setSuccess(Boolean.FALSE);
        request.getSession().setAttribute("authenticated", Boolean.FALSE);
    }
    return dto;
}

From source file:com.utest.webservice.auth.BasicAuthAuthorizationInterceptor.java

@Override
public void handleMessage(final Message message) throws Fault {
    try {//w ww.  j a v  a 2  s . c o  m
        AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
        Authentication authentication = SessionUtil.getAuthenticationToken(message);
        if (policy == null && authentication == null) {
            sendErrorResponse(message, HttpURLConnection.HTTP_UNAUTHORIZED);
            return;
        }
        if (authentication == null) {
            authentication = new UsernamePasswordAuthenticationToken(policy.getUserName(),
                    policy.getPassword());
            ((UsernamePasswordAuthenticationToken) authentication).setDetails(message.get("HTTP.REQUEST"));
            authentication = authenticationProvider.authenticate(authentication);
        } else {
            if (((UsernamePasswordAuthenticationToken) authentication).getDetails() == null) {
                ((UsernamePasswordAuthenticationToken) authentication).setDetails(message.get("HTTP.REQUEST"));
            }
        }
        SecurityContextHolder.getContext().setAuthentication(authentication);
    } catch (final RuntimeException ex) {
        sendErrorResponse(message, HttpURLConnection.HTTP_UNAUTHORIZED);
        throw ex;
    }
}