Example usage for org.springframework.security.oauth2.common.util RandomValueStringGenerator RandomValueStringGenerator

List of usage examples for org.springframework.security.oauth2.common.util RandomValueStringGenerator RandomValueStringGenerator

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.common.util RandomValueStringGenerator RandomValueStringGenerator.

Prototype

public RandomValueStringGenerator(int length) 

Source Link

Document

Create a generator of random strings of the length provided

Usage

From source file:org.cloudfoundry.identity.uaa.scim.endpoints.ScimUserEndpointsMockMvcTests.java

@Test
public void test_Create_User_Too_Long_Password() throws Exception {
    String email = "joe@" + generator.generate().toLowerCase() + ".com";
    ScimUser user = getScimUser();// w ww  .j  a  va  2s  .  c o  m
    user.setUserName(email);
    user.setPrimaryEmail(email);
    user.setPassword(new RandomValueStringGenerator(300).generate());
    ResultActions result = createUserAndReturnResult(user, scimReadWriteToken, null, null);
    result.andExpect(status().isBadRequest()).andExpect(jsonPath("$.error").value("invalid_password"))
            .andExpect(jsonPath("$.message").value("Password must be no more than 255 characters in length."))
            .andExpect(jsonPath("$.error_description")
                    .value("Password must be no more than 255 characters in length."));
}

From source file:org.cloudfoundry.identity.uaa.scim.endpoints.ScimUserEndpointsMockMvcTests.java

@Test
public void cannotCreateUserWithInvalidPasswordInDefaultZone() throws Exception {
    ScimUser user = getScimUser();/*from   www. java  2  s .c om*/
    user.setPassword(new RandomValueStringGenerator(260).generate());
    byte[] requestBody = JsonUtils.writeValueAsBytes(user);
    MockHttpServletRequestBuilder post = post("/Users").header("Authorization", "Bearer " + scimCreateToken)
            .contentType(APPLICATION_JSON).content(requestBody);

    getMockMvc().perform(post).andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.error").value("invalid_password"))
            .andExpect(jsonPath("$.message").value("Password must be no more than 255 characters in length."));
}

From source file:org.cloudfoundry.identity.uaa.db.StoreSubDomainAsLowerCase_V2_7_3.java

@Override
public synchronized void migrate(JdbcTemplate jdbcTemplate) throws Exception {
    RandomValueStringGenerator generator = new RandomValueStringGenerator(3);
    Map<String, List<IdentityZone>> zones = new HashMap<>();
    Set<String> duplicates = new HashSet<>();
    List<IdentityZone> identityZones = retrieveIdentityZones(jdbcTemplate);
    for (IdentityZone zone : identityZones) {
        addToMap(zone, zones, duplicates);
    }/*from  ww  w .j ava 2s .  c om*/

    for (String s : duplicates) {
        logger.debug("Processing zone duplicates for subdomain:" + s);
        List<IdentityZone> dupZones = zones.get(s);
        for (int i = 1; dupZones.size() > 1 && i < dupZones.size(); i++) {
            IdentityZone dupZone = dupZones.get(i);
            String newsubdomain = null;
            while (newsubdomain == null) {
                String potentialsubdomain = (dupZone.getSubdomain() + "-" + generator.generate()).toLowerCase();
                if (zones.get(potentialsubdomain) == null) {
                    newsubdomain = potentialsubdomain;
                }
            }
            logger.debug(String.format("Updating zone id:%s; old subdomain: %s; new subdomain: %s;",
                    dupZone.getId(), dupZone.getSubdomain(), newsubdomain));
            dupZone.setSubdomain(newsubdomain);
            dupZone = updateIdentityZone(dupZone, jdbcTemplate);
            zones.put(newsubdomain, Arrays.asList(dupZone));
        }
    }
    for (IdentityZone zone : identityZones) {
        String subdomain = zone.getSubdomain();
        if (StringUtils.hasText(subdomain) && !(subdomain.toLowerCase().equals(subdomain))) {
            logger.debug(
                    String.format("Lowercasing zone subdomain for id:%s; old subdomain: %s; new subdomain: %s;",
                            zone.getId(), zone.getSubdomain(), zone.getSubdomain().toLowerCase()));
            zone.setSubdomain(subdomain.toLowerCase());
            updateIdentityZone(zone, jdbcTemplate);
        }

    }
}

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

@Test
public void testEnteringContraveningPasswordShowsErrorMessage() {
    startCreateUserFlow(new RandomValueStringGenerator(260).generate());
    Assert.assertEquals("Password must be no more than 255 characters in length.",
            webDriver.findElement(By.cssSelector(".alert-error")).getText());
}

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

@Test
public void resetPassword_displaysErrorMessage_WhenPasswordIsInvalid() throws Exception {
    String newPassword = new RandomValueStringGenerator(260).generate();
    beginResetPassword();//from   w ww  .  ja  va  2s.  c  o  m
    webDriver.findElement(By.name("password")).sendKeys(newPassword);
    webDriver.findElement(By.name("password_confirmation")).sendKeys(newPassword);
    webDriver.findElement(By.xpath("//input[@value='Create new password']")).click();
    assertThat(webDriver.findElement(By.cssSelector(".error-message")).getText(),
            containsString("Password must be no more than 255 characters in length."));
}

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.providers.IdentityProviderEndpointsDocs.java

public void createLDAPProvider(IdentityProvider<LdapIdentityProviderDefinition> identityProvider,
        FieldDescriptor[] fields, String name) throws Exception {
    BaseClientDetails admin = new BaseClientDetails("admin", null, "", "client_credentials", "uaa.admin");
    admin.setClientSecret("adminsecret");

    IdentityZoneCreationResult zone = MockMvcUtils.createOtherIdentityZoneAndReturnResult(
            new RandomValueStringGenerator(8).generate().toLowerCase(), getMockMvc(),
            getWebApplicationContext(), admin);

    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 = getMockMvc()
            .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)"),
                    headerWithName("X-Identity-Zone-Id").description(
                            "May include this header to administer another zone if using `zones.<zone id>.admin` or `uaa.admin` scope against the default UAA zone.")
                            .optional()),
            commonRequestParams, requestFields, responseFields));

    getMockMvc()//w w  w .java2  s  .  co m
            .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.util.MockMvcUtils.java

public static IdentityZone createZoneUsingWebRequest(MockMvc mockMvc, String accessToken) throws Exception {
    final String zoneId = new RandomValueStringGenerator(12).generate().toLowerCase();
    IdentityZone identityZone = MultitenancyFixture.identityZone(zoneId, zoneId);

    MvcResult result = mockMvc/*from  w w  w  .  j ava  2  s.  c om*/
            .perform(post("/identity-zones").header("Authorization", "Bearer " + accessToken)
                    .contentType(APPLICATION_JSON).content(JsonUtils.writeValueAsString(identityZone)))
            .andExpect(status().isCreated()).andReturn();
    return JsonUtils.readValue(result.getResponse().getContentAsString(), IdentityZone.class);
}

From source file:org.cloudfoundry.identity.uaa.provider.oauth.XOAuthProviderConfigurator.java

public String getCompleteAuthorizationURI(String alias, String baseURL,
        AbstractXOAuthIdentityProviderDefinition definition) {
    try {//from  ww w . j  a  v  a2s. c o  m
        String authUrlBase;
        if (definition instanceof OIDCIdentityProviderDefinition) {
            authUrlBase = overlay((OIDCIdentityProviderDefinition) definition).getAuthUrl().toString();
        } else {
            authUrlBase = definition.getAuthUrl().toString();
        }
        String queryAppendDelimiter = authUrlBase.contains("?") ? "&" : "?";
        List<String> query = new ArrayList<>();
        query.add("client_id=" + definition.getRelyingPartyId());
        query.add("response_type=" + URLEncoder.encode(definition.getResponseType(), "UTF-8"));
        query.add("redirect_uri=" + URLEncoder.encode(baseURL + "/login/callback/" + alias, "UTF-8"));
        query.add("state=" + RandomStringUtils.randomAlphanumeric(10));
        if (definition.getScopes() != null && !definition.getScopes().isEmpty()) {
            query.add("scope=" + URLEncoder.encode(String.join(" ", definition.getScopes()), "UTF-8"));
        }
        if (OIDCIdentityProviderDefinition.class.equals(definition.getParameterizedClass())) {
            final RandomValueStringGenerator nonceGenerator = new RandomValueStringGenerator(12);
            query.add("nonce=" + nonceGenerator.generate());
        }
        String queryString = String.join("&", query);
        return authUrlBase + queryAppendDelimiter + queryString;
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.cloudfoundry.identity.uaa.scim.endpoints.ScimGroupEndpointsMockMvcTests.java

@Test
public void getGroupsInOtherZone_withZoneAdminToken_returnsOkWithResults() throws Exception {
    String subdomain = new RandomValueStringGenerator(8).generate();
    BaseClientDetails bootstrapClient = null;
    MockMvcUtils.IdentityZoneCreationResult result = utils().createOtherIdentityZoneAndReturnResult(subdomain,
            getMockMvc(), getWebApplicationContext(), bootstrapClient);

    ScimGroup group1 = new ScimGroup(null, "scim.whatever", result.getIdentityZone().getId());
    ScimGroup group2 = new ScimGroup(null, "another.group", result.getIdentityZone().getId());

    getMockMvc()//from  w  w  w  .  j  a v a2s  . com
            .perform(post("/Groups")
                    .header(IdentityZoneSwitchingFilter.HEADER, result.getIdentityZone().getId())
                    .header("Authorization", "bearer " + result.getZoneAdminToken()).accept(APPLICATION_JSON)
                    .contentType(APPLICATION_JSON).content(JsonUtils.writeValueAsString(group1)))
            .andExpect(status().isCreated());

    getMockMvc()
            .perform(post("/Groups")
                    .header(IdentityZoneSwitchingFilter.HEADER, result.getIdentityZone().getId())
                    .header("Authorization", "bearer " + result.getZoneAdminToken()).accept(APPLICATION_JSON)
                    .contentType(APPLICATION_JSON).content(JsonUtils.writeValueAsString(group2)))
            .andExpect(status().isCreated());

    MockHttpServletRequestBuilder get = get("/Groups")
            .header("Authorization", "Bearer " + result.getZoneAdminToken())
            .header(IdentityZoneSwitchingFilter.HEADER, result.getIdentityZone().getId())
            .param("attributes", "displayName").param("filter", "displayName co \"scim\"")
            .contentType(MediaType.APPLICATION_JSON).accept(APPLICATION_JSON);
    MvcResult mvcResult = getMockMvc().perform(get).andExpect(status().isOk()).andReturn();

    SearchResults searchResults = JsonUtils.readValue(mvcResult.getResponse().getContentAsString(),
            SearchResults.class);
    assertThat(searchResults.getResources().size(), is(getSystemScopes("scim").size() + 1));

    get = get("/Groups").header("Authorization", "Bearer " + result.getZoneAdminToken())
            .header(IdentityZoneSwitchingFilter.HEADER, result.getIdentityZone().getId())
            .contentType(MediaType.APPLICATION_JSON).accept(APPLICATION_JSON);
    mvcResult = getMockMvc().perform(get).andExpect(status().isOk()).andReturn();

    searchResults = JsonUtils.readValue(mvcResult.getResponse().getContentAsString(), SearchResults.class);
    assertThat(searchResults.getResources().size(), is(getSystemScopes(null).size() + 2));
}