Example usage for org.springframework.security.authentication UsernamePasswordAuthenticationToken getCredentials

List of usage examples for org.springframework.security.authentication UsernamePasswordAuthenticationToken getCredentials

Introduction

In this page you can find the example usage for org.springframework.security.authentication UsernamePasswordAuthenticationToken getCredentials.

Prototype

public Object getCredentials() 

Source Link

Usage

From source file:nl.surfnet.coin.api.MockApiController.java

@Override
protected ClientMetaData getClientMetaData() {
    try {/*from   w  w  w  .  ja  v a2  s.c  o m*/
        return super.getClientMetaData();
    } catch (IllegalArgumentException e) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // basic
        if (authentication instanceof UsernamePasswordAuthenticationToken) {
            UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
            EntityMetadata metaData = new EntityMetadata();
            metaData.setAppEntityId("DUMMY-BASIC-AUTH");
            metaData.setOauthConsumerKey(token.getPrincipal() + ":" + token.getCredentials());
            JanusClientMetadata clientMetadata = new JanusClientMetadata(metaData);
            return clientMetadata;
        } else {
            throw e;
        }
    }
}

From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationProviderTest.java

@Test
public void shouldCreatesNewTokenForAdminAndUser() {

    // Given//ww w  . ja v a 2  s.c  om

    String responseJSON = "{\"token\":{\"methods\":[\"password\"],"
            + "\"roles\":[{\"id\":\"13abab31bc194317a009b25909f390a6\",\"name\":\"owner\"}],"
            + "\"expires_at\":\"2015-04-16T06:49:07.794235Z\",\"project\":{\"domain\":{\"id\":\"default\","
            + "\"name\":\"Default\"},\"id\":\"user tenantId\",\"name\":\"jesuspg2\"},"
            + "\"extras\":{},\"user\":{\"domain\":{\"id\":\"default\",\"name\":\"Default\"},"
            + "\"id\":\"a7e01921db0049f69daa76490402714a\",\"name\":\"jesus.perezgonzalez@telefonica.com\"},"
            + "\"audit_ids\":[\"0u8bgE6AStObXnzfI9nu6A\"],\"issued_at\":\"2015-04-15T10:49:07.794329Z\"}}";

    OpenStackAuthenticationProvider openStackAuthenticationProvider = new OpenStackAuthenticationProvider();
    openStackAuthenticationProvider.setSystemPropertiesProvider(systemPropertiesProvider);
    openStackAuthenticationToken = mock(OpenStackAuthenticationToken.class);
    openStackAuthenticationProvider.setoSAuthToken(openStackAuthenticationToken);
    OpenStackAccess openStackAccess = new OpenStackAccess();
    openStackAccess.setToken("token1");
    openStackAccess.setTenantId("tenantId1");
    openStackAccess.setOpenStackKeystone(new OpenStackKeystoneV3());

    when(openStackAuthenticationToken.getAdminCredentials(any(Client.class))).thenReturn(openStackAccess);
    Client client = mock(Client.class);
    when(openStackAuthenticationToken.getKeystoneURL()).thenReturn(keystoneURL);
    openStackAuthenticationProvider.setClient(client);
    WebTarget webResource = mock(WebTarget.class);
    when(client.target("http://keystone.test")).thenReturn(webResource);
    Invocation.Builder builder = mock(Invocation.Builder.class);
    when(webResource.request()).thenReturn(builder);
    when(builder.accept(MediaType.APPLICATION_JSON)).thenReturn(builder);
    when(builder.header("X-Auth-Token", "token1")).thenReturn(builder);
    when(builder.header("X-Subject-Token", "user token")).thenReturn(builder);
    Response response = mock(Response.class);
    when(builder.get()).thenReturn(response);
    when(response.getStatus()).thenReturn(200);

    // mock response
    when(response.readEntity(String.class)).thenReturn(responseJSON);

    openStackAuthenticationProvider.getTokenCache().removeAll();

    UsernamePasswordAuthenticationToken authentication = mock(UsernamePasswordAuthenticationToken.class);
    when(authentication.getCredentials()).thenReturn("user tenantId");

    // When
    UserDetails userDetails = openStackAuthenticationProvider.retrieveUser("user token", authentication);

    // Then
    verify(response).readEntity(String.class);
    assertNotNull(userDetails);
    assertEquals("user token", userDetails.getPassword());

}

From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationProviderTest.java

@Test
public void shouldCreatesNewTokenForAdminAndUserWithAPIv3() {

    // Given/*  w  w  w  .  j  a  v a  2  s.c o  m*/

    String responseJSON = "{\"access\": {\"token\": {\"issued_at\": \"2015-04-16T14:47:17.573966\", "
            + "\"expires\": \"2015-04-17T10:47:17Z\", \"id\": \"user token\", "
            + "\"tenant\": {\"description\": \"Cloud admins\", \"enabled\": true, "
            + "\"id\": \"user tenantId\", \"name\": \"tenantName\"}, "
            + "\"audit_ids\": [\"z4fSnIPsQ2eu3ylzoXRfvA\"]}, \"user\": {\"username\": \"admin\", "
            + "\"roles_links\": [], \"id\": \"e12249b99b3e4b9394dd85703b04e851\", "
            + "\"roles\": [{\"name\": \"admin\"}], \"name\": \"admin\"}, \"metadata\": {\"is_admin\": 0, "
            + "\"roles\": [\"bb780354f545410b9cc144809e845148\"]}}}";

    OpenStackAuthenticationProvider openStackAuthenticationProvider = new OpenStackAuthenticationProvider();
    openStackAuthenticationProvider.setSystemPropertiesProvider(systemPropertiesProvider);
    openStackAuthenticationToken = mock(OpenStackAuthenticationToken.class);
    openStackAuthenticationProvider.setoSAuthToken(openStackAuthenticationToken);
    OpenStackAccess openStackAccess = new OpenStackAccess();
    openStackAccess.setToken("token1");
    openStackAccess.setTenantId("tenantId1");
    openStackAccess.setOpenStackKeystone(new OpenStackKeystoneV2());

    when(openStackAuthenticationToken.getAdminCredentials(any(Client.class))).thenReturn(openStackAccess);
    Client client = mock(Client.class);
    when(openStackAuthenticationToken.getKeystoneURL()).thenReturn(keystoneURL);
    openStackAuthenticationProvider.setClient(client);
    WebTarget webResource = mock(WebTarget.class);
    when(client.target("http://keystone.test")).thenReturn(webResource);
    when(webResource.path("user token")).thenReturn(webResource);
    Invocation.Builder builder = mock(Invocation.Builder.class);
    when(webResource.request()).thenReturn(builder);
    when(builder.accept(MediaType.APPLICATION_JSON)).thenReturn(builder);
    when(builder.header("X-Auth-Token", "token1")).thenReturn(builder);
    Response response = mock(Response.class);
    when(builder.get()).thenReturn(response);
    when(response.getStatus()).thenReturn(200);

    // mock response
    when(response.readEntity(String.class)).thenReturn(responseJSON);

    openStackAuthenticationProvider.getTokenCache().removeAll();

    UsernamePasswordAuthenticationToken authentication = mock(UsernamePasswordAuthenticationToken.class);
    when(authentication.getCredentials()).thenReturn("user tenantId");

    // When
    UserDetails userDetails = openStackAuthenticationProvider.retrieveUser("user token", authentication);

    // Then
    verify(response).readEntity(String.class);
    assertNotNull(userDetails);
    assertEquals("user token", userDetails.getPassword());

}

From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationProviderTest.java

@Test
public void shouldCreateNewTokenAfterResetCache() throws InterruptedException {
    // Given/*from w  w  w.  jav  a 2 s  . c  om*/

    String responseJSON = "{\"token\":{\"methods\":[\"password\"],"
            + "\"roles\":[{\"id\":\"13abab31bc194317a009b25909f390a6\",\"name\":\"owner\"}],"
            + "\"expires_at\":\"2015-04-16T06:49:07.794235Z\",\"project\":{\"domain\":{\"id\":\"default\","
            + "\"name\":\"Default\"},\"id\":\"user tenantId\",\"name\":\"jesuspg2\"},"
            + "\"extras\":{},\"user\":{\"domain\":{\"id\":\"default\",\"name\":\"Default\"},"
            + "\"id\":\"a7e01921db0049f69daa76490402714a\",\"name\":\"jesus.perezgonzalez@telefonica.com\"},"
            + "\"audit_ids\":[\"0u8bgE6AStObXnzfI9nu6A\"],\"issued_at\":\"2015-04-15T10:49:07.794329Z\"}}";

    OpenStackAuthenticationProvider openStackAuthenticationProvider = new OpenStackAuthenticationProvider();
    openStackAuthenticationProvider.setSystemPropertiesProvider(systemPropertiesProvider);
    openStackAuthenticationToken = mock(OpenStackAuthenticationToken.class);
    openStackAuthenticationProvider.setoSAuthToken(openStackAuthenticationToken);

    OpenStackAccess openStackAccess = new OpenStackAccess();
    openStackAccess.setToken("token1");
    openStackAccess.setTenantId("tenantId1");
    openStackAccess.setOpenStackKeystone(new OpenStackKeystoneV3());

    when(openStackAuthenticationToken.getAdminCredentials(any(Client.class))).thenReturn(openStackAccess);
    when(openStackAuthenticationToken.getKeystoneURL()).thenReturn(keystoneURL);
    Client client = mock(Client.class);
    openStackAuthenticationProvider.setClient(client);
    WebTarget webResource = mock(WebTarget.class);
    when(client.target("http://keystone.test")).thenReturn(webResource);
    Invocation.Builder builder = mock(Invocation.Builder.class);
    when(webResource.request()).thenReturn(builder);
    when(builder.accept(MediaType.APPLICATION_JSON)).thenReturn(builder);
    when(builder.header("X-Auth-Token", "token1")).thenReturn(builder);
    when(builder.header("X-Subject-Token", "user token")).thenReturn(builder);

    Response response = mock(Response.class);
    when(builder.get()).thenReturn(response);
    when(response.getStatus()).thenReturn(200);

    // mock response
    when(response.readEntity(String.class)).thenReturn(responseJSON);

    openStackAuthenticationProvider.getTokenCache().removeAll();
    UsernamePasswordAuthenticationToken authentication = mock(UsernamePasswordAuthenticationToken.class);
    when(authentication.getCredentials()).thenReturn("user tenantId");
    // When
    UserDetails firstTimeUserDetails = openStackAuthenticationProvider.retrieveUser("user token",
            authentication);

    // force expire elements now
    openStackAuthenticationProvider.getTokenCache().get("admin").setTimeToIdle(1);
    openStackAuthenticationProvider.getTokenCache().get("admin").setTimeToLive(1);
    openStackAuthenticationProvider.getTokenCache().get("user token-user tenantId").setTimeToIdle(1);
    openStackAuthenticationProvider.getTokenCache().get("user token-user tenantId").setTimeToLive(1);
    Thread.sleep(2000);

    UserDetails secondTimeUserDetails = openStackAuthenticationProvider.retrieveUser("user token",
            authentication);

    // Then
    verify(response, times(2)).readEntity(String.class);
    assertNotNull(firstTimeUserDetails);
    assertEquals("user token", firstTimeUserDetails.getPassword());

    assertEquals("user token", secondTimeUserDetails.getPassword());
}

From source file:org.taverna.server.master.identity.StrippedDownAuthProvider.java

/**
 * Allows subclasses to actually retrieve the <code>UserDetails</code> from
 * an implementation-specific location, with the option of throwing an
 * <code>AuthenticationException</code> immediately if the presented
 * credentials are incorrect (this is especially useful if it is necessary
 * to bind to a resource as the user in order to obtain or generate a
 * <code>UserDetails</code>).
 * <p>/*from ww w.  j  a v a  2s.  co  m*/
 * Subclasses are not required to perform any caching, as the
 * <code>AbstractUserDetailsAuthenticationProvider</code> will by default
 * cache the <code>UserDetails</code>. The caching of
 * <code>UserDetails</code> does present additional complexity as this means
 * subsequent requests that rely on the cache will need to still have their
 * credentials validated, even if the correctness of credentials was assured
 * by subclasses adopting a binding-based strategy in this method.
 * Accordingly it is important that subclasses either disable caching (if
 * they want to ensure that this method is the only method that is capable
 * of authenticating a request, as no <code>UserDetails</code> will ever be
 * cached) or ensure subclasses implement
 * {@link #additionalAuthenticationChecks(UserDetails, UsernamePasswordAuthenticationToken)}
 * to compare the credentials of a cached <code>UserDetails</code> with
 * subsequent authentication requests.
 * </p>
 * <p>
 * Most of the time subclasses will not perform credentials inspection in
 * this method, instead performing it in
 * {@link #additionalAuthenticationChecks(UserDetails, UsernamePasswordAuthenticationToken)}
 * so that code related to credentials validation need not be duplicated
 * across two methods.
 * </p>
 * 
 * @param username
 *            The username to retrieve
 * @param authentication
 *            The authentication request, which subclasses <em>may</em> need
 *            to perform a binding-based retrieval of the
 *            <code>UserDetails</code>
 * 
 * @return the user information (never <code>null</code> - instead an
 *         exception should the thrown)
 * 
 * @throws AuthenticationException
 *             if the credentials could not be validated (generally a
 *             <code>BadCredentialsException</code>, an
 *             <code>AuthenticationServiceException</code> or
 *             <code>UsernameNotFoundException</code>)
 */
private UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {
    try {
        return userDetailsService.loadUserByUsername(username);
    } catch (UsernameNotFoundException notFound) {
        if (authentication.getCredentials() != null) {
            String presentedPassword = authentication.getCredentials().toString();
            passwordEncoder.matches(presentedPassword, userNotFoundEncodedPassword);
        }
        throw notFound;
    } catch (AuthenticationException e) {
        throw e;
    } catch (Exception repositoryProblem) {
        throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
    }
}

From source file:com.sun.identity.provider.springsecurity.OpenSSOAuthenticationProvider.java

/**
 * authenticate the access request.//from w w w .j a  va2  s  .  c o  m
 *
 * Note by this point the user has already been granted an sso token
 * (i.e. they have already authenticated because they were redirected
 * to opensso).
 *
 * If the user has any group membership we turn those into
 * GrantedAuthortities (roles in Spring terminolgy).
 * @see  OpenSSOSimpleAuthoritiesPopulator
 *
 * Note that a failure to retrieve OpenSSO roles does not result in
 * an non revcoverable exception (but we should revist this decision). In theory
 * we can continue with authentication only. The user will have no
 * GrantedAuthorities.
 *
 * @param authentication
 * @return authentication token - possibly withe ROLE_*  authorities.
 * 
 * @throws org.springframework.security.core.AuthenticationException
 */
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    OpenSSOSimpleAuthoritiesPopulator populator = new OpenSSOSimpleAuthoritiesPopulator();

    if (debug.messageEnabled())
        debug.message("Authentication: " + authentication);

    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String principal = (String) token.getPrincipal();

    // hack alert
    // We pass in the SSOToken as the credential (.e.g the password)
    // this is probably confusing - and we should refactor to use a
    // proper OpenSSOAuthenitcationToken.
    SSOToken ssoToken = (SSOToken) token.getCredentials();

    try {
        Collection<? extends GrantedAuthority> ga = populator.getGrantedAuthorities(ssoToken);
        UserDetails u = new User(principal, "secret", true, true, true, true, ga);
        authentication = new UsernamePasswordAuthenticationToken(u, "secret", ga);
    } catch (Exception ex) {
        //throw new AuthenticationServiceException("Exception trying to get AMIdentity", ex);
        // Note: We eat the exception
        // The authentication can still succeed - but there will be no
        // granted authorities (i.e. no roles granted).
        // This is arguably the right thing to do here
        debug.error("Exception Trying to get AMIdentity", ex);
    }

    return authentication;
}

From source file:com.mothsoft.alexis.web.security.AlexisWebAuthenticationProvider.java

@Override
protected UserDetails retrieveUser(final String username, final UsernamePasswordAuthenticationToken token)
        throws AuthenticationException {
    return this.transactionTemplate.execute(new TransactionCallback<UserDetails>() {

        @Override//from  w  w w.j a v a 2 s  .com
        public UserDetails doInTransaction(TransactionStatus arg0) {
            final User user = AlexisWebAuthenticationProvider.this.userDao.findUserByUsername(username);
            final String password = String.valueOf(token.getCredentials());
            final UserDetails userDetails = AlexisWebAuthenticationProvider.this.userDetailsService
                    .loadUserByUsername(username);

            final String encodedPassword = AlexisWebAuthenticationProvider.this.passwordEncoder
                    .encodePassword(password, user.getPasswordSalt());

            // credentials are bad if none are stored (external auth) or they don't match
            if (user.getHashedPassword() == null || !username.equals(token.getName())
                    || !encodedPassword.equals(user.getHashedPassword())) {
                throw new BadCredentialsException(username);
            }

            final UserApiToken apiToken = AlexisWebAuthenticationProvider.this.userDao.createApiToken(user);
            final UserDetails toReturn = new UserAuthenticationDetails((UserAuthenticationDetails) userDetails,
                    apiToken.getToken());
            return toReturn;
        }
    });
}

From source file:whitelabel.cloud.webapp.security.spring.CloudUserDetailsAuthenticationProvider.java

@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
        throws AuthenticationException {

    CloudWebAutenticationDetails details = ((CloudWebAutenticationDetails) authentication.getDetails());

    WsEndUserClient wsEndUser = new WsEndUserClient(wsEndUserNamespace, wsEndUserServiceName,
            details.getDatacenterUrl() + wsEndUserEndpoint);
    AppUserToken utoken = null;/*from ww  w.  ja v  a  2 s .co m*/
    try {
        utoken = wsEndUser.loginAs(username, authentication.getCredentials().toString());
    } catch (Exception e) {
        throw new UsernameNotFoundException("USERNAME_NOT_FOUND", e);
    }

    if (utoken == null || !utoken.isValid()) {
        throw new UsernameNotFoundException("USERNAME_NOT_FOUND");
    }
    // create new cloud-user
    CloudUser cu = new CloudUser(username, authentication.getCredentials().toString(),
            details.getDatacenterId());
    // set di wsEndUser to the user (so every ws-invoke use same authentication token)
    cu.setWsEndUser(wsEndUser);

    try {
        //find VDCResourceConfiguration
        WsEndUserVDCConfigClient wsEndUserVDCConfigClient = new WsEndUserVDCConfigClient(wsEndUserNamespace,
                wsEndUserServiceName, details.getDatacenterUrl() + wsEndUserEndpoint);
        wsEndUserVDCConfigClient.setCredentials(utoken.getUserName(), utoken.getToken());
        cu.setVdcResourceBoundConfig(wsEndUserVDCConfigClient.getVDCResourceConfiguration());
    } catch (Exception e) {
        throw new UsernameNotFoundException("VDC_CONFIG_NOT_FOUND", e);
    }

    return new UserDetailsImpl(cu);

}

From source file:com.github.lynxdb.server.api.http.WebSecurityConfig.java

@Autowired
public void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(new AbstractUserDetailsAuthenticationProvider() {
        @Override/*from   w ww.j ava 2s  . co m*/
        protected void additionalAuthenticationChecks(UserDetails ud, UsernamePasswordAuthenticationToken upat)
                throws AuthenticationException {

        }

        @Override
        protected UserDetails retrieveUser(String string, UsernamePasswordAuthenticationToken upat)
                throws AuthenticationException {
            User user = users.byLogin(string);
            if (user == null) {
                throw new UsernameNotFoundException("No such User : " + string);
            }
            if (user.checkPassword(upat.getCredentials().toString())) {
                return user;
            } else {
                throw new BadCredentialsException("Bad credentials");

            }
        }
    });
}

From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationProviderTest.java

@Test
public void shouldAddCredentialsToClaudiaDataWhenAuthenticatedWithToken() {
    // given//  ww  w.jav a  2s  .c om

    ClaudiaData claudiaData = new ClaudiaData("org", "vdc", "service");
    SecurityContext context = mock(SecurityContext.class);
    SecurityContextHolder.setContext(context);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = mock(
            UsernamePasswordAuthenticationToken.class);
    when(context.getAuthentication()).thenReturn(usernamePasswordAuthenticationToken);
    when(usernamePasswordAuthenticationToken.getPrincipal()).thenReturn("token1");
    when(usernamePasswordAuthenticationToken.getCredentials()).thenReturn("tenantId1");
    // when
    OpenStackAuthenticationProvider.addCredentialsToClaudiaData(claudiaData);

    // then
    assertNotNull(claudiaData);
    assertEquals("org", claudiaData.getOrg());
    assertEquals("vdc", claudiaData.getVdc());
    assertEquals("service", claudiaData.getService());
    assertEquals("token1", claudiaData.getUser().getToken());
    assertEquals("tenantId1", claudiaData.getUser().getTenantId());
    assertEquals("", claudiaData.getUser().getTenantName());

}