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

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

Introduction

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

Prototype

public boolean isAuthenticated() 

Source Link

Usage

From source file:com.hp.autonomy.frontend.find.idol.test.IdolMvcIntegrationTestUtils.java

@Override
protected Authentication createAuthentication(final Collection<GrantedAuthority> authorities) {
    final CommunityPrincipal communityPrincipal = mock(CommunityPrincipal.class);
    when(communityPrincipal.getId()).thenReturn(1L);
    when(communityPrincipal.getUsername()).thenReturn("user");

    final UsernamePasswordAuthenticationToken authentication = mock(UsernamePasswordAuthenticationToken.class);
    when(authentication.isAuthenticated()).thenReturn(true);
    when(authentication.getPrincipal()).thenReturn(communityPrincipal);
    when(authentication.getAuthorities()).thenReturn(authorities);

    return authentication;
}

From source file:de.pksoftware.springstrap.basic.service.BasicUserDetailsService.java

/**
 * Performs an auto login after signup./*from   w  ww .  j a v a  2 s .  c  o  m*/
 * @param newAccount
 * @param password
 */
public void autoLogin(IAccount newAccount, String password) {
    UserDetails userDetails = loadUserByUsername(newAccount.getUsername());
    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetails, password,
            userDetails.getAuthorities());
    authenticationManager.authenticate(auth);
    if (auth.isAuthenticated()) {
        SecurityContextHolder.getContext().setAuthentication(auth);
    }
}

From source file:org.springframework.security.jackson2.UsernamePasswordAuthenticationTokenMixinTest.java

@Test
public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenMixinTest() throws IOException {
    String tokenJson = "{\"@class\": \"org.springframework.security.authentication.UsernamePasswordAuthenticationToken\","
            + "\"principal\": \"user1\", \"credentials\": \"password\", \"authenticated\": true, \"details\": null, "
            + "\"authorities\" : [\"java.util.ArrayList\", [{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}";
    UsernamePasswordAuthenticationToken token = buildObjectMapper().readValue(tokenJson,
            UsernamePasswordAuthenticationToken.class);
    assertThat(token).isNotNull();/*  w  ww.  j  a v  a 2 s.c o m*/
    assertThat(token.isAuthenticated()).isEqualTo(true);
    assertThat(token.getAuthorities()).isNotNull().hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
}

From source file:org.springframework.security.jackson2.UsernamePasswordAuthenticationTokenMixinTest.java

@Test
public void deserializeUnauthenticatedUsernamePasswordAuthenticationTokenMixinTest()
        throws IOException, JSONException {
    String tokenJson = "{\"@class\": \"org.springframework.security.authentication.UsernamePasswordAuthenticationToken\","
            + " \"principal\": \"user1\", \"credentials\": \"password\", \"authenticated\": false, \"details\": null, "
            + "\"authorities\": [\"java.util.ArrayList\", []], \"name\": \"user1\"}";
    UsernamePasswordAuthenticationToken token = buildObjectMapper().readValue(tokenJson,
            UsernamePasswordAuthenticationToken.class);
    assertThat(token).isNotNull();//ww  w. ja  v  a 2 s .  c  om
    assertThat(token.isAuthenticated()).isEqualTo(false);
    assertThat(token.getAuthorities()).isNotNull().hasSize(0);
}

From source file:org.springframework.security.jackson2.UsernamePasswordAuthenticationTokenMixinTest.java

@Test
public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenWithUserTest() throws IOException {
    String tokenJson = "{\"@class\": \"org.springframework.security.authentication.UsernamePasswordAuthenticationToken\","
            + "\"principal\": {\"@class\": \"org.springframework.security.core.userdetails.User\", \"username\": \"user\", \"password\": \"pass\", \"accountNonExpired\": true, \"enabled\": true, "
            + "\"accountNonLocked\": true, \"credentialsNonExpired\": true, \"authorities\": [\"java.util.Collections$UnmodifiableSet\","
            + "[{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}, \"credentials\": \"pass\","
            + "\"details\": null, \"name\": \"user\", \"authenticated\": true,"
            + "\"authorities\": [\"java.util.ArrayList\", [{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"role\": \"ROLE_USER\"}]]}";
    ObjectMapper mapper = buildObjectMapper();
    UsernamePasswordAuthenticationToken token = mapper.readValue(tokenJson,
            UsernamePasswordAuthenticationToken.class);
    assertThat(token).isNotNull();//from  w  ww. ja  v  a2s .c  o  m
    assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class);
    assertThat(((User) token.getPrincipal()).getAuthorities()).isNotNull().hasSize(1)
            .contains(new SimpleGrantedAuthority("ROLE_USER"));
    assertThat(token.isAuthenticated()).isEqualTo(true);
    assertThat(token.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
}

From source file:org.red5.server.plugin.admin.client.AuthClientRegistry.java

@SuppressWarnings("unchecked")
@Override//from   w w w . j av a 2  s .c o  m
public IClient newClient(Object[] params) throws ClientNotFoundException, ClientRejectedException {
    log.debug("New client - params: {}, {}, {}", params);

    if (params == null || params.length == 0) {
        log.warn("Client didn't pass a username.");
        throw new ClientRejectedException();
    }

    String username, passwd;
    if (params[0] instanceof HashMap) {
        // Win FP sends HashMap
        HashMap userWin = (HashMap) params[0];
        username = (String) userWin.get(0);
        passwd = (String) userWin.get(1);
    } else if (params[0] instanceof ArrayList) {
        // Mac FP sends ArrayList
        ArrayList userMac = (ArrayList) params[0];
        username = (String) userMac.get(0);
        passwd = (String) userMac.get(1);
    } else {
        throw new ClientRejectedException();
    }

    UsernamePasswordAuthenticationToken t = new UsernamePasswordAuthenticationToken(username, passwd);

    masterScope = Red5.getConnectionLocal().getScope();

    ProviderManager mgr = (ProviderManager) masterScope.getContext().getBean("authenticationManager");
    try {
        log.debug("Checking password: {}", passwd);
        t = (UsernamePasswordAuthenticationToken) mgr.authenticate(t);
    } catch (BadCredentialsException ex) {
        log.debug("{}", ex);
        throw new ClientRejectedException();
    }

    if (t.isAuthenticated()) {
        client = new AuthClient(nextId(), this);
        addClient(client);
        client.setAttribute("authInformation", t);
        log.debug("Authenticated client - username: {}, id: {}", new Object[] { username, client.getId() });
    }

    return client;
}

From source file:org.springframework.security.jackson2.UsernamePasswordAuthenticationTokenMixinTest.java

@Test
public void deserializeAuthenticatedUsernamePasswordAuthenticationTokenMixinWithCustomUserTest()
        throws Exception {
    String tokenJson = "{"
            + "  \"@class\" : \"org.springframework.security.authentication.UsernamePasswordAuthenticationToken\","
            + "  \"details\" : null," + "  \"authorities\" : [ \"java.util.ArrayList\", [ {"
            + "    \"@class\" : \"org.springframework.security.core.authority.SimpleGrantedAuthority\","
            + "    \"role\" : \"ROLE_USER\"" + "  } ] ]," + "  \"authenticated\" : true,"
            + "  \"principal\" : {"
            + "    \"@class\" : \"org.springframework.security.jackson2.CustomUserForTest\","
            + "    \"username\" : \"user\"," + "    \"password\" : \"pass\","
            + "    \"customProperty\" : \"custom\"," + "    \"authorities\" : [ \"java.util.ArrayList\", [ {"
            + "      \"@class\" : \"org.springframework.security.core.authority.SimpleGrantedAuthority\","
            + "      \"role\" : \"ROLE_USER\"" + "    } ] ]," + "    \"accountNonExpired\" : true,"
            + "    \"accountNonLocked\" : true," + "    \"credentialsNonExpired\" : true,"
            + "    \"enabled\" : true" + "  }," + "  \"credentials\" : \"pass\"," + "  \"name\" : \"user\""
            + "}";

    UsernamePasswordAuthenticationToken token = buildObjectMapper().readValue(tokenJson,
            UsernamePasswordAuthenticationToken.class);

    assertThat(token).isNotNull();//from  ww w  .  ja v  a 2s.com
    assertThat(token.getPrincipal()).isNotNull().isInstanceOf(CustomUserForTest.class);
    assertThat(((CustomUserForTest) token.getPrincipal()).getAuthorities()).isNotNull().hasSize(1)
            .contains(new SimpleGrantedAuthority("ROLE_USER"));
    assertThat(((CustomUserForTest) token.getPrincipal()).getCustomProperty()).isNotNull().isEqualTo("custom");
    assertThat(token.isAuthenticated()).isEqualTo(true);
    assertThat(token.getAuthorities()).hasSize(1).contains(new SimpleGrantedAuthority("ROLE_USER"));
}

From source file:org.apache.nifi.kerberos.KerberosProvider.java

@Override
public final AuthenticationResponse authenticate(final LoginCredentials credentials)
        throws InvalidLoginCredentialsException, IdentityAccessException {
    if (provider == null) {
        throw new IdentityAccessException("The Kerberos authentication provider is not initialized.");
    }/*from  w ww  .j  a v  a2s  .  c  om*/

    try {
        // Perform the authentication
        final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
                credentials.getUsername(), credentials.getPassword());
        logger.debug("Created authentication token for principal {} with name {} and is authenticated {}",
                token.getPrincipal(), token.getName(), token.isAuthenticated());

        final Authentication authentication = provider.authenticate(token);
        logger.debug(
                "Ran provider.authenticate() and returned authentication for "
                        + "principal {} with name {} and is authenticated {}",
                authentication.getPrincipal(), authentication.getName(), authentication.isAuthenticated());

        return new AuthenticationResponse(authentication.getName(), credentials.getUsername(), expiration,
                issuer);
    } catch (final AuthenticationException e) {
        throw new InvalidLoginCredentialsException(e.getMessage(), e);
    }
}

From source file:org.cloudfoundry.identity.uaa.mock.util.MockMvcUtils.java

public static String getUserOAuthAccessTokenAuthCode(MockMvc mockMvc, String clientId, String clientSecret,
        String userId, String username, String password, String scope) throws Exception {
    String basicDigestHeaderValue = "Basic " + new String(
            org.apache.commons.codec.binary.Base64.encodeBase64((clientId + ":" + clientSecret).getBytes()));
    UaaPrincipal p = new UaaPrincipal(userId, username, "test@test.org", OriginKeys.UAA, "",
            IdentityZoneHolder.get().getId());
    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(p, "",
            UaaAuthority.USER_AUTHORITIES);
    Assert.assertTrue(auth.isAuthenticated());

    SecurityContextHolder.getContext().setAuthentication(auth);
    MockHttpSession session = new MockHttpSession();
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            new MockSecurityContext(auth));

    String state = new RandomValueStringGenerator().generate();
    MockHttpServletRequestBuilder authRequest = get("/oauth/authorize")
            .header("Authorization", basicDigestHeaderValue).header("Accept", MediaType.APPLICATION_JSON_VALUE)
            .session(session).param(OAuth2Utils.GRANT_TYPE, "authorization_code")
            .param(OAuth2Utils.RESPONSE_TYPE, "code")
            .param(TokenConstants.REQUEST_TOKEN_FORMAT, TokenConstants.OPAQUE).param(OAuth2Utils.STATE, state)
            .param(OAuth2Utils.CLIENT_ID, clientId).param(OAuth2Utils.REDIRECT_URI, "http://localhost/test");
    if (StringUtils.hasText(scope)) {
        authRequest.param(OAuth2Utils.SCOPE, scope);
    }/*w  w  w . j ava2 s  . co m*/

    MvcResult result = mockMvc.perform(authRequest).andExpect(status().is3xxRedirection()).andReturn();
    String location = result.getResponse().getHeader("Location");
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(location);
    String code = builder.build().getQueryParams().get("code").get(0);

    authRequest = post("/oauth/token").header("Authorization", basicDigestHeaderValue)
            .header("Accept", MediaType.APPLICATION_JSON_VALUE)
            .param(OAuth2Utils.GRANT_TYPE, "authorization_code").param(OAuth2Utils.RESPONSE_TYPE, "token")
            .param("code", code).param(OAuth2Utils.CLIENT_ID, clientId)
            .param(OAuth2Utils.REDIRECT_URI, "http://localhost/test");
    if (StringUtils.hasText(scope)) {
        authRequest.param(OAuth2Utils.SCOPE, scope);
    }
    result = mockMvc.perform(authRequest).andExpect(status().is2xxSuccessful()).andReturn();
    InjectedMockContextTest.OAuthToken oauthToken = JsonUtils
            .readValue(result.getResponse().getContentAsString(), InjectedMockContextTest.OAuthToken.class);
    return oauthToken.accessToken;

}