Example usage for org.springframework.security.oauth2.provider.client BaseClientDetails BaseClientDetails

List of usage examples for org.springframework.security.oauth2.provider.client BaseClientDetails BaseClientDetails

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.provider.client BaseClientDetails BaseClientDetails.

Prototype

public BaseClientDetails(String clientId, String resourceIds, String scopes, String grantTypes,
            String authorities, String redirectUris) 

Source Link

Usage

From source file:org.cloudfoundry.identity.uaa.integration.feature.SamlLoginIT.java

@Test
public void testSamlLoginClientIDPAuthorizationAutomaticRedirect() throws Exception {
    IdentityProvider provider = createIdentityProvider("simplesamlphp");
    assertEquals(provider.getOriginKey(),
            provider.getConfigValue(IdentityProviderDefinition.class).getIdpEntityAlias());
    List<String> idps = Arrays.asList(provider.getOriginKey());
    webDriver.get(baseUrl + "/logout.do");
    String adminAccessToken = testClient.getOAuthAccessToken("admin", "adminsecret", "client_credentials",
            "clients.read clients.write clients.secret");

    String clientId = UUID.randomUUID().toString();
    BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, "openid", "authorization_code",
            "uaa.none", baseUrl);
    clientDetails.setClientSecret("secret");
    clientDetails.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, idps);
    clientDetails.addAdditionalInformation(ClientConstants.AUTO_APPROVE, true);

    testClient.createClient(adminAccessToken, clientDetails);

    webDriver.get(baseUrl + "/oauth/authorize?client_id=" + clientId + "&redirect_uri="
            + URLEncoder.encode(baseUrl) + "&response_type=code&state=8tp0tR");
    //we should now be in the Simple SAML PHP site
    webDriver.findElement(By.xpath("//h2[contains(text(), 'Enter your username and password')]"));
    webDriver.findElement(By.name("username")).clear();
    webDriver.findElement(By.name("username")).sendKeys(testAccounts.getUserName());
    webDriver.findElement(By.name("password")).sendKeys("koala");
    webDriver.findElement(By.xpath("//input[@value='Login']")).click();

    assertThat(webDriver.findElement(By.cssSelector("h1")).getText(), Matchers.containsString("Where to?"));
    webDriver.get(baseUrl + "/logout.do");
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.SamlLoginIT.java

@Test
public void testLoginClientIDPAuthorizationAlreadyLoggedIn() throws Exception {
    webDriver.get(baseUrl + "/logout.do");
    String adminAccessToken = testClient.getOAuthAccessToken("admin", "adminsecret", "client_credentials",
            "clients.read clients.write clients.secret");

    String clientId = UUID.randomUUID().toString();
    BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, "openid", "authorization_code",
            "uaa.none", "http://localhost:8080/login");
    clientDetails.setClientSecret("secret");
    List<String> idps = Arrays.asList("okta-local"); //not authorized for the current IDP
    clientDetails.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, idps);

    testClient.createClient(adminAccessToken, clientDetails);

    webDriver.findElement(By.name("username")).clear();
    webDriver.findElement(By.name("username")).sendKeys(testAccounts.getUserName());
    webDriver.findElement(By.name("password")).sendKeys("koala");
    webDriver.findElement(By.xpath("//input[@value='Sign in']")).click();

    webDriver.get(baseUrl + "/oauth/authorize?client_id=" + clientId
            + "&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2Flogin&response_type=code&state=8tp0tR");

    assertThat(webDriver.findElement(By.cssSelector("p")).getText(),
            Matchers.containsString("The application is not authorized for your account."));
    webDriver.get(baseUrl + "/logout.do");
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.SamlLoginWithLocalIdpIT.java

@SuppressWarnings("unchecked")
@Test/*from   ww  w . j a v a 2  s. c o  m*/
public void testLocalSamlIdpLoginInTestZone1Works() throws Exception {
    assumeTrue("Expected testzone1/2.localhost to resolve to 127.0.0.1", doesSupportZoneDNS());
    String zoneId = "testzone1";

    RestTemplate identityClient = IntegrationTestUtils
            .getClientCredentialsTemplate(IntegrationTestUtils.getClientCredentialsResource(baseUrl,
                    new String[] { "zones.write", "zones.read", "scim.zones" }, "identity", "identitysecret"));
    RestTemplate adminClient = IntegrationTestUtils.getClientCredentialsTemplate(
            IntegrationTestUtils.getClientCredentialsResource(baseUrl, new String[0], "admin", "adminsecret"));
    IdentityZone zone = IntegrationTestUtils.createZoneOrUpdateSubdomain(identityClient, baseUrl, zoneId,
            zoneId);
    String email = new RandomValueStringGenerator().generate() + "@samltesting.org";
    ScimUser user = IntegrationTestUtils.createUser(adminClient, baseUrl, email, "firstname", "lastname", email,
            true);
    IntegrationTestUtils.makeZoneAdmin(identityClient, baseUrl, user.getId(), zoneId);

    String zoneAdminToken = IntegrationTestUtils.getAuthorizationCodeToken(serverRunning,
            UaaTestAccounts.standard(serverRunning), "identity", "identitysecret", email, "secr3T");

    String testZone1Url = baseUrl.replace("localhost", zoneId + ".localhost");
    String zoneAdminClientId = new RandomValueStringGenerator().generate() + "-" + zoneId + "-admin";
    BaseClientDetails clientDetails = new BaseClientDetails(zoneAdminClientId, null, "uaa.none",
            "client_credentials", "uaa.admin,scim.read,scim.write,uaa.resource", testZone1Url);
    clientDetails.setClientSecret("secret");
    IntegrationTestUtils.createClientAsZoneAdmin(zoneAdminToken, baseUrl, zoneId, clientDetails);

    RestTemplate zoneAdminClient = IntegrationTestUtils.getClientCredentialsTemplate(IntegrationTestUtils
            .getClientCredentialsResource(testZone1Url, new String[0], zoneAdminClientId, "secret"));
    String zoneUserEmail = new RandomValueStringGenerator().generate() + "@samltesting.org";
    IntegrationTestUtils.createUser(zoneAdminClient, testZone1Url, zoneUserEmail, "Dana", "Scully",
            zoneUserEmail, true);

    SamlIdentityProviderDefinition samlIdentityProviderDefinition = createZone1IdpDefinition(IDP_ENTITY_ID);
    IdentityProvider<SamlIdentityProviderDefinition> provider = new IdentityProvider<>();
    provider.setIdentityZoneId(zoneId);
    provider.setType(OriginKeys.SAML);
    provider.setActive(true);
    provider.setConfig(samlIdentityProviderDefinition);
    provider.setOriginKey(samlIdentityProviderDefinition.getIdpEntityAlias());
    provider.setName("Local SAML IdP for testzone1");
    provider = IntegrationTestUtils.createOrUpdateProvider(zoneAdminToken, baseUrl, provider);
    assertNotNull(provider.getId());

    SamlServiceProviderDefinition samlServiceProviderDefinition = createZone1SamlSpDefinition(
            "cloudfoundry-saml-login");
    SamlServiceProvider sp = new SamlServiceProvider();
    sp.setIdentityZoneId(zoneId);
    sp.setActive(true);
    sp.setConfig(samlServiceProviderDefinition);
    sp.setEntityId("testzone1.cloudfoundry-saml-login");
    sp.setName("Local SAML SP for testzone1");
    sp = createOrUpdateSamlServiceProvider(zoneAdminToken, baseUrl, sp);

    webDriver.get(baseUrl + "/logout.do");
    webDriver.get(testZone1Url + "/logout.do");
    webDriver.get(testZone1Url + "/login");
    Assert.assertEquals(zone.getName(), webDriver.getTitle());

    List<WebElement> elements = webDriver
            .findElements(By.xpath("//a[text()='" + samlIdentityProviderDefinition.getLinkText() + "']"));
    assertNotNull(elements);
    assertEquals(1, elements.size());

    WebElement element = elements.get(0);
    assertNotNull(element);
    element.click();
    webDriver.findElement(By.xpath("//h1[contains(text(), 'Welcome to The Twiglet Zone[" + zoneId + "]!')]"));
    webDriver.findElement(By.name("username")).clear();
    webDriver.findElement(By.name("username")).sendKeys(zoneUserEmail);
    webDriver.findElement(By.name("password")).sendKeys("secr3T");
    webDriver.findElement(By.xpath("//input[@value='Sign in']")).click();
    assertThat(webDriver.findElement(By.cssSelector("h1")).getText(), Matchers.containsString("Where to?"));

    webDriver.get(baseUrl + "/logout.do");
    webDriver.get(testZone1Url + "/logout.do");

    // disable the provider
    provider.setActive(false);
    provider = IntegrationTestUtils.createOrUpdateProvider(zoneAdminToken, baseUrl, provider);
    assertNotNull(provider.getId());
    webDriver.get(testZone1Url + "/login");
    Assert.assertEquals(zone.getName(), webDriver.getTitle());
    elements = webDriver
            .findElements(By.xpath("//a[text()='" + samlIdentityProviderDefinition.getLinkText() + "']"));
    assertNotNull(elements);
    assertEquals(0, elements.size());

    // enable the provider
    provider.setActive(true);
    provider = IntegrationTestUtils.createOrUpdateProvider(zoneAdminToken, baseUrl, provider);
    assertNotNull(provider.getId());
    webDriver.get(testZone1Url + "/login");
    Assert.assertEquals(zone.getName(), webDriver.getTitle());
    elements = webDriver
            .findElements(By.xpath("//a[text()='" + samlIdentityProviderDefinition.getLinkText() + "']"));
    assertNotNull(elements);
    assertEquals(1, elements.size());
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.SamlLoginWithLocalIdpIT.java

private void createZoneUser(String idpZoneId, String zoneAdminToken, String zoneUserEmail, String zoneUrl)
        throws Exception {
    String zoneAdminClientId = new RandomValueStringGenerator().generate() + "-" + idpZoneId + "-admin";
    BaseClientDetails clientDetails = new BaseClientDetails(zoneAdminClientId, null, "uaa.none",
            "client_credentials", "uaa.admin,scim.read,scim.write,uaa.resource", zoneUrl);
    clientDetails.setClientSecret("secret");
    IntegrationTestUtils.createClientAsZoneAdmin(zoneAdminToken, baseUrl, idpZoneId, clientDetails);

    RestTemplate zoneAdminClient = IntegrationTestUtils.getClientCredentialsTemplate(IntegrationTestUtils
            .getClientCredentialsResource(zoneUrl, new String[0], zoneAdminClientId, "secret"));
    IntegrationTestUtils.createUser(zoneAdminClient, zoneUrl, zoneUserEmail, "Dana", "Scully", zoneUserEmail,
            true);/*from w w w  .j ava2s .c  o  m*/
}

From source file:org.cloudfoundry.identity.uaa.login.EmailChangeEmailServiceTest.java

private Map<String, String> setUpCompleteActivation(String username, String clientId, String redirectUri) {
    Map<String, String> codeData = new HashMap<>();
    codeData.put("user_id", "user-001");
    codeData.put("client_id", clientId);
    codeData.put("redirect_uri", redirectUri);
    codeData.put("email", "new@example.com");
    BaseClientDetails clientDetails = new BaseClientDetails("client-id", null, null, "authorization_grant",
            null, "http://app.com/*");
    clientDetails.addAdditionalInformation(CHANGE_EMAIL_REDIRECT_URL, "http://fallback.url/redirect");

    when(codeStore.retrieveCode("the_secret_code", IdentityZoneHolder.get().getId()))
            .thenReturn(new ExpiringCode("the_secret_code", new Timestamp(System.currentTimeMillis()),
                    JsonUtils.writeValueAsString(codeData), null));
    ScimUser user = new ScimUser("user-001", username, "", "");
    user.setPrimaryEmail("user@example.com");
    when(scimUserProvisioning.retrieve("user-001", IdentityZoneHolder.get().getId())).thenReturn(user);

    when(clientDetailsService.loadClientByClientId(clientId, "uaa")).thenReturn(clientDetails);

    Map<String, String> response = emailChangeEmailService.completeVerification("the_secret_code");

    ScimUser updatedUser = new ScimUser("user-001", "new@example.com", "", "");
    user.setPrimaryEmail("new@example.com");

    verify(scimUserProvisioning).update("user-001", updatedUser, IdentityZoneHolder.get().getId());
    return response;
}

From source file:org.cloudfoundry.identity.uaa.mock.providers.IdentityProviderEndpointDocs.java

void createLDAPProvider(IdentityProvider<LdapIdentityProviderDefinition> identityProvider,
        FieldDescriptor[] fields, String name) throws Exception {
    Map<String, Object> attributeMappings = new HashedMap(identityProvider.getConfig().getAttributeMappings());
    attributeMappings.put(EMAIL_VERIFIED_ATTRIBUTE_NAME, "emailVerified");
    identityProvider.getConfig().setAttributeMappings(attributeMappings);
    BaseClientDetails admin = new BaseClientDetails("admin", null, "", "client_credentials", "uaa.admin",
            "http://redirect.url");
    admin.setClientSecret("adminsecret");

    IdentityZoneCreationResult zone = MockMvcUtils.createOtherIdentityZoneAndReturnResult(
            new RandomValueStringGenerator(8).generate().toLowerCase(), mockMvc, webApplicationContext, admin,
            IdentityZoneHolder.getCurrentZoneId());

    Snippet requestFields = requestFields(fields);

    Snippet responseFields = responseFields(
            (FieldDescriptor[]) ArrayUtils.addAll(ldapAllFields, new FieldDescriptor[] { VERSION, ID,
                    ADDITIONAL_CONFIGURATION, IDENTITY_ZONE_ID, CREATED, LAST_MODIFIED }));

    ResultActions resultActions = mockMvc
            .perform(post("/identity-providers")
                    .header(IdentityZoneSwitchingFilter.SUBDOMAIN_HEADER, zone.getIdentityZone().getSubdomain())
                    .param("rawConfig", "true").header("Authorization", "Bearer " + zone.getZoneAdminToken())
                    .contentType(APPLICATION_JSON)
                    .content(serializeExcludingProperties(identityProvider, "id", "version", "created",
                            "last_modified", "identityZoneId", "config.additionalConfiguration")))
            .andExpect(status().isCreated());

    resultActions.andDo(document("{ClassName}/" + name, preprocessRequest(prettyPrint()),
            preprocessResponse(prettyPrint()),
            requestHeaders(headerWithName("Authorization").description(
                    "Bearer token containing `zones.<zone id>.admin` or `uaa.admin` or `idps.write` (only in the same zone that you are a user of)"),
                    IDENTITY_ZONE_ID_HEADER, IDENTITY_ZONE_SUBDOMAIN_HEADER),
            commonRequestParams, requestFields, responseFields));

    mockMvc.perform(post("/login.do").header("Host", zone.getIdentityZone().getSubdomain() + ".localhost")
            .with(cookieCsrf()).param("username", "marissa4").param("password", "ldap4"))
            .andExpect(status().isFound()).andExpect(redirectedUrl("/"));

}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void refreshAccessToken_withClient_withAutoApproveField() throws Exception {
    String clientId = "testclient" + generator.generate();
    BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, "uaa.user,other.scope",
            "authorization_code,refresh_token", "uaa.resource", TEST_REDIRECT_URI);
    clientDetails.setAutoApproveScopes(Arrays.asList("uaa.user"));
    clientDetails.setClientSecret("secret");
    clientDetails.addAdditionalInformation(ClientConstants.AUTO_APPROVE, Arrays.asList("other.scope"));
    clientDetails.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, Arrays.asList("uaa"));
    clientDetailsService.addClientDetails(clientDetails);

    String username = "testuser" + generator.generate();
    String userScopes = "uaa.user,other.scope";
    ScimUser developer = setUpUser(username, userScopes, OriginKeys.UAA, IdentityZone.getUaa().getId());

    MockHttpSession session = getAuthenticatedSession(developer);

    String state = generator.generate();

    MvcResult result = getMockMvc()//from  w ww.  j  av a2 s.  co  m
            .perform(get("/oauth/authorize").session(session).param(OAuth2Utils.RESPONSE_TYPE, "code")
                    .param(OAuth2Utils.STATE, state).param(OAuth2Utils.CLIENT_ID, clientId))
            .andExpect(status().isFound()).andReturn();

    URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?"));
    Map query = splitQuery(url);
    String code = ((List<String>) query.get("code")).get(0);
    state = ((List<String>) query.get("state")).get(0);

    MockHttpServletRequestBuilder oauthTokenPost = post("/oauth/token")
            .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE).accept(MediaType.APPLICATION_JSON_VALUE)
            .param(OAuth2Utils.RESPONSE_TYPE, "token").param(OAuth2Utils.GRANT_TYPE, "authorization_code")
            .param(OAuth2Utils.CLIENT_ID, clientId).param("client_secret", "secret").param("code", code)
            .param("state", state);

    MvcResult mvcResult = getMockMvc().perform(oauthTokenPost).andReturn();
    OAuth2RefreshToken refreshToken = JsonUtils
            .readValue(mvcResult.getResponse().getContentAsString(), CompositeAccessToken.class)
            .getRefreshToken();

    MockHttpServletRequestBuilder postForRefreshToken = post("/oauth/token")
            .header("Authorization", "Basic " + new String(Base64.encode((clientId + ":" + SECRET).getBytes())))
            .param(GRANT_TYPE, REFRESH_TOKEN).param(REFRESH_TOKEN, refreshToken.getValue());
    getMockMvc().perform(postForRefreshToken).andExpect(status().isOk());
}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void authorizeEndpointWithPromptNone_WhenNotAuthenticated() throws Exception {
    String clientId = "testclient" + generator.generate();
    BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, "uaa.user,other.scope",
            "authorization_code,refresh_token", "uaa.resource", TEST_REDIRECT_URI);
    clientDetails.setAutoApproveScopes(Arrays.asList("uaa.user"));
    clientDetails.setClientSecret("secret");
    clientDetails.addAdditionalInformation(ClientConstants.AUTO_APPROVE, Arrays.asList("other.scope"));
    clientDetails.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, Arrays.asList("uaa"));
    clientDetailsService.addClientDetails(clientDetails);

    MockHttpSession session = new MockHttpSession();

    String state = generator.generate();

    MvcResult result = getMockMvc()/*from  ww w  .  j a v  a2 s . c  om*/
            .perform(get("/oauth/authorize").session(session).param(OAuth2Utils.RESPONSE_TYPE, "code")
                    .param(OAuth2Utils.STATE, state).param(OAuth2Utils.CLIENT_ID, clientId)
                    .param(OAuth2Utils.REDIRECT_URI, TEST_REDIRECT_URI)
                    .param(ID_TOKEN_HINT_PROMPT, ID_TOKEN_HINT_PROMPT_NONE))
            .andExpect(status().isFound()).andExpect(cookie().maxAge("Current-User", 0)).andReturn();

    String url = result.getResponse().getHeader("Location");
    assertEquals(UaaUrlUtils.addQueryParameter(TEST_REDIRECT_URI, "error", "login_required"), url);

}

From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java

@Test
public void testAuthorizeEndpointWithPromptNone_Authenticated() throws Exception {
    String clientId = "testclient" + generator.generate();
    BaseClientDetails clientDetails = new BaseClientDetails(clientId, null, "uaa.user,other.scope",
            "authorization_code,refresh_token", "uaa.resource", TEST_REDIRECT_URI);
    clientDetails.setAutoApproveScopes(Arrays.asList("uaa.user"));
    clientDetails.setClientSecret("secret");
    clientDetails.addAdditionalInformation(ClientConstants.AUTO_APPROVE, Arrays.asList("other.scope"));
    clientDetails.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, Arrays.asList("uaa"));
    clientDetailsService.addClientDetails(clientDetails);

    String username = "testuser" + generator.generate();
    String userScopes = "uaa.user,other.scope";
    ScimUser developer = setUpUser(username, userScopes, OriginKeys.UAA, IdentityZone.getUaa().getId());

    MockHttpSession session = getAuthenticatedSession(developer);

    String state = generator.generate();

    MvcResult result = getMockMvc()/*from ww w .ja va 2 s .co m*/
            .perform(get("/oauth/authorize").session(session).param(OAuth2Utils.RESPONSE_TYPE, "code")
                    .param(OAuth2Utils.STATE, state).param(OAuth2Utils.CLIENT_ID, clientId)
                    .param(OAuth2Utils.REDIRECT_URI, TEST_REDIRECT_URI)
                    .param(ID_TOKEN_HINT_PROMPT, ID_TOKEN_HINT_PROMPT_NONE))
            .andExpect(status().isFound()).andReturn();

    String url = result.getResponse().getHeader("Location");
    assertThat(url, containsString(TEST_REDIRECT_URI));
}

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

public static ZoneScimInviteData createZoneForInvites(MockMvc mockMvc, ApplicationContext context,
        String clientId, String redirectUri) throws Exception {
    RandomValueStringGenerator generator = new RandomValueStringGenerator();
    String superAdmin = getClientCredentialsOAuthAccessToken(mockMvc, "admin", "adminsecret", "", null);
    IdentityZoneCreationResult zone = utils()
            .createOtherIdentityZoneAndReturnResult(generator.generate().toLowerCase(), mockMvc, context, null);
    BaseClientDetails appClient = new BaseClientDetails("app", "", "scim.invite",
            "client_credentials,password,authorization_code",
            "uaa.admin,clients.admin,scim.write,scim.read,scim.invite", redirectUri);
    appClient.setClientSecret("secret");
    appClient = utils().createClient(mockMvc, zone.getZoneAdminToken(), appClient, zone.getIdentityZone());
    appClient.setClientSecret("secret");
    String adminToken = utils().getClientCredentialsOAuthAccessToken(mockMvc, appClient.getClientId(),
            appClient.getClientSecret(), "", zone.getIdentityZone().getSubdomain());

    String username = new RandomValueStringGenerator().generate().toLowerCase() + "@example.com";
    ScimUser user = new ScimUser(clientId, username, "given-name", "family-name");
    user.setPrimaryEmail(username);/*from   w  w w  .j a  va2s  . c o m*/
    user.setPassword("password");
    user = createUserInZone(mockMvc, adminToken, user, zone.getIdentityZone().getSubdomain());
    user.setPassword("password");

    ScimGroup group = new ScimGroup("scim.invite");
    group.setMembers(Arrays.asList(new ScimGroupMember(user.getId(), USER, Arrays.asList(MEMBER))));

    return new ZoneScimInviteData(adminToken, zone, appClient, superAdmin);
}