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) 

Source Link

Usage

From source file:com.example.ClientDetailsController.java

@PostMapping("/clients")
public String add(Principal user) {
    BaseClientDetails client = new BaseClientDetails(strings.generate(), null,
            "openid,cloud_controller.read,cloud_controller.write", "password,authorization_code,refresh_token",
            "ROLE_CLIENT");
    client.setClientSecret(strings.generate());
    client.setAutoApproveScopes(Arrays.asList("true"));
    clients.addClientDetails(client);/*w  w w  . j  a  v a2  s  .c  o m*/
    template.update("INSERT into user_client_details (username, client_id) values (?,?)", user.getName(),
            client.getClientId());
    return "redirect:/clients";
}

From source file:org.cloudfoundry.identity.uaa.audit.event.SystemDeletableTest.java

@Test
public void client_event_received() throws Exception {
    BaseClientDetails client = new BaseClientDetails("clientId", "", "", "client_credentials", "uaa.none");
    EntityDeletedEvent<ClientDetails> event = new EntityDeletedEvent(client, authentication);
    for (IdentityZone zone : Arrays.asList(this.zone, IdentityZone.getUaa())) {
        resetDeletable();/*from   w  w  w  .  j  a  va 2 s.c  o m*/
        IdentityZoneHolder.set(zone);
        deletable.onApplicationEvent(event);
        verify(deletable, never()).deleteByIdentityZone(any());
        verify(deletable, never()).deleteByOrigin(any(), any());
        verify(deletable, times(1)).deleteByClient(client.getClientId(), zone.getId());
        verify(deletable, never()).deleteByUser(any(), any());
    }
}

From source file:org.cloudfoundry.identity.uaa.integration.ScimGroupEndpointsIntegrationTests.java

private void createTestClient(String name, String secret, String scope) throws Exception {
    OAuth2AccessToken token = getClientCredentialsAccessToken("clients.read,clients.write,clients.admin");
    HttpHeaders headers = getAuthenticatedHeaders(token);
    BaseClientDetails client = new BaseClientDetails(name, "", scope, "authorization_code,password",
            "scim.read,scim.write");
    client.setClientSecret(secret);//from  w  w  w.  j  a v  a  2  s.c  o m
    ResponseEntity<Void> result = serverRunning.getRestTemplate().exchange(
            serverRunning.getUrl("/oauth/clients"), HttpMethod.POST,
            new HttpEntity<BaseClientDetails>(client, headers), Void.class);
    assertEquals(HttpStatus.CREATED, result.getStatusCode());
}

From source file:org.cloudfoundry.identity.uaa.mock.audit.AuditCheckMockMvcTests.java

@Test
public void testUserApprovalAdded() throws Exception {
    clientRegistrationService.updateClientDetails(
            new BaseClientDetails("login", "oauth", "oauth.approvals", "password", "oauth.login"));

    String marissaToken = testClient.getUserOAuthAccessToken("login", "loginsecret", testUser.getUserName(),
            testPassword, "oauth.approvals");
    Approval[] approvals = { new Approval().setUserId(null).setClientId("app").setScope("cloud_controller.read")
            .setExpiresAt(Approval.timeFromNow(1000)).setStatus(Approval.ApprovalStatus.APPROVED) };

    MockHttpServletRequestBuilder approvalsPut = put("/approvals").accept(MediaType.APPLICATION_JSON_VALUE)
            .contentType(MediaType.APPLICATION_JSON).header("Authorization", "Bearer " + marissaToken)
            .content(JsonUtils.writeValueAsBytes(approvals));

    testListener.clearEvents();/*from   w w  w  .  j a va  2  s. c  o  m*/

    getMockMvc().perform(approvalsPut).andExpect(status().isOk());

    assertEquals(1, testListener.getEventCount());

    ApprovalModifiedEvent approvalModifiedEvent = (ApprovalModifiedEvent) testListener.getLatestEvent();
    assertEquals(testUser.getUserName(), approvalModifiedEvent.getAuthentication().getName());
}

From source file:org.cloudfoundry.identity.uaa.mock.audit.AuditCheckMockMvcTests.java

@Test
public void testUserCreatedEventDuringLoginServerAuthorize() throws Exception {
    clientRegistrationService.updateClientDetails(new BaseClientDetails("login", "oauth", "oauth.approvals",
            "authorization_code,password,client_credentials", "oauth.login"));
    String username = "jacob" + new RandomValueStringGenerator().generate();
    String loginToken = testClient.getClientCredentialsOAuthAccessToken("login", "loginsecret", "oauth.login");
    MockHttpServletRequestBuilder userPost = post("/oauth/authorize").with(cookieCsrf())
            .accept(MediaType.APPLICATION_JSON_VALUE).contentType(MediaType.APPLICATION_JSON)
            .header("Authorization", "Bearer " + loginToken).param("source", "login")
            .param(UaaAuthenticationDetails.ADD_NEW, "true").param("username", username)
            .param("name", "Jacob Gyllenhammer").param("email", "jacob@gyllenhammer.non")
            .param("external_id", "jacob").param("response_type", "code").param("client_id", "login")
            .param("redirect_uri", "http://localhost:8080/uaa").param("state", "erw342");

    testListener.clearEvents();//w w w  .  j  av  a 2s. c  o  m

    getMockMvc().perform(userPost).andExpect(status().isOk());

    assertEquals(2, testListener.getEventCount());

    UserModifiedEvent userModifiedEvent = (UserModifiedEvent) testListener.getEvents().get(0);
    assertEquals("login", userModifiedEvent.getAuthentication().getName());
    assertEquals(username, userModifiedEvent.getUsername());
    assertEquals(AuditEventType.UserCreatedEvent, userModifiedEvent.getAuditEvent().getType());

}

From source file:org.cloudfoundry.identity.uaa.mock.audit.AuditCheckMvcMockTests.java

@Test
public void testUserApprovalAdded() throws Exception {
    clientRegistrationService.updateClientDetails(
            new BaseClientDetails("login", "oauth", "oauth.approvals", "password", "oauth.login"));

    String marissaToken = testClient.getUserOAuthAccessToken("login", "loginsecret", testAccounts.getUserName(),
            testAccounts.getPassword(), "oauth.approvals");
    Approval[] approvals = {/*from  w  w  w. j ava  2 s. c  o  m*/
            new Approval(null, "app", "cloud_controller.read", 1000, Approval.ApprovalStatus.APPROVED) };

    MockHttpServletRequestBuilder approvalsPut = put("/approvals").accept(MediaType.APPLICATION_JSON_VALUE)
            .contentType(MediaType.APPLICATION_JSON).header("Authorization", "Bearer " + marissaToken)
            .content(new ObjectMapper().writeValueAsBytes(approvals));

    testListener.clearEvents();

    mockMvc.perform(approvalsPut).andExpect(status().isOk());

    Assert.assertEquals(1, testListener.getEventCount());

    ApprovalModifiedEvent approvalModifiedEvent = (ApprovalModifiedEvent) testListener.getLatestEvent();
    Assert.assertEquals(testAccounts.getUserName(), approvalModifiedEvent.getAuthentication().getName());
}

From source file:org.cloudfoundry.identity.uaa.mock.audit.AuditCheckMvcMockTests.java

@Test
public void testUserCreatedEventDuringLoginServerAuthorize() throws Exception {
    clientRegistrationService.updateClientDetails(new BaseClientDetails("login", "oauth", "oauth.approvals",
            "authorization_code,password,client_credentials", "oauth.login"));
    String loginToken = testClient.getClientCredentialsOAuthAccessToken("login", "loginsecret", "oauth.login");

    MockHttpServletRequestBuilder userPost = post("/oauth/authorize").accept(MediaType.APPLICATION_JSON_VALUE)
            .contentType(MediaType.APPLICATION_JSON).header("Authorization", "Bearer " + loginToken)
            .param("source", "login").param(UaaAuthenticationDetails.ADD_NEW, "true").param("username", "jacob")
            .param("name", "Jacob Gyllenhammer").param("email", "jacob@gyllenhammer.non")
            .param("external_id", "jacob").param("response_type", "code").param("client_id", "login")
            .param("redirect_uri", "http://localhost:8080/uaa").param("state", "erw342");

    testListener.clearEvents();/*from w ww .ja va  2 s . c o m*/

    mockMvc.perform(userPost).andExpect(status().isOk());

    Assert.assertEquals(2, testListener.getEventCount());

    UserModifiedEvent userModifiedEvent = (UserModifiedEvent) testListener.getEvents().get(0);
    Assert.assertEquals("login", userModifiedEvent.getAuthentication().getName());
    Assert.assertEquals("jacob", userModifiedEvent.getUsername());
    assertEquals(AuditEventType.UserCreatedEvent, userModifiedEvent.getAuditEvent().getType());

}

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()/*www .  j a  v  a 2 s  .  c o  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.providers.IdentityProviderEndpointsMockMvcTests.java

private void testRetrieveIdps(boolean retrieveActive) throws Exception {
    String clientId = RandomStringUtils.randomAlphabetic(6);
    BaseClientDetails client = new BaseClientDetails(clientId, null, "idps.write,idps.read", "password", null);
    client.setClientSecret("test-client-secret");
    mockMvcUtils.createClient(getMockMvc(), adminToken, client);

    ScimUser user = mockMvcUtils.createAdminForZone(getMockMvc(), adminToken, "idps.read,idps.write");
    String accessToken = mockMvcUtils.getUserOAuthAccessToken(getMockMvc(), client.getClientId(),
            client.getClientSecret(), user.getUserName(), "secr3T", "idps.read,idps.write");
    String randomOriginKey = new RandomValueStringGenerator().generate();
    IdentityProvider identityProvider = MultitenancyFixture.identityProvider(randomOriginKey,
            IdentityZone.getUaa().getId());
    IdentityProvider createdIDP = createIdentityProvider(null, identityProvider, accessToken,
            status().isCreated());/*ww w .  ja v a  2s  .co m*/

    String retrieveActiveParam = retrieveActive ? "?active_only=true" : "";
    MockHttpServletRequestBuilder requestBuilder = get("/identity-providers" + retrieveActiveParam)
            .header("Authorization", "Bearer" + accessToken).contentType(APPLICATION_JSON);

    int numberOfIdps = identityProviderProvisioning.retrieveAll(retrieveActive, IdentityZone.getUaa().getId())
            .size();

    MvcResult result = getMockMvc().perform(requestBuilder).andExpect(status().isOk()).andReturn();
    List<IdentityProvider> identityProviderList = JsonUtils.readValue(result.getResponse().getContentAsString(),
            new TypeReference<List<IdentityProvider>>() {
            });
    assertEquals(numberOfIdps, identityProviderList.size());
    assertTrue(identityProviderList.contains(createdIDP));

    createdIDP.setActive(false);
    createdIDP = JsonUtils.readValue(updateIdentityProvider(null, createdIDP, accessToken, status().isOk())
            .getResponse().getContentAsString(), IdentityProvider.class);

    result = getMockMvc().perform(requestBuilder).andExpect(status().isOk()).andReturn();
    identityProviderList = JsonUtils.readValue(result.getResponse().getContentAsString(),
            new TypeReference<List<IdentityProvider>>() {
            });
    if (!retrieveActive) {
        assertEquals(numberOfIdps, identityProviderList.size());
        assertTrue(identityProviderList.contains(createdIDP));
    } else {
        assertEquals(numberOfIdps - 1, identityProviderList.size());
        assertFalse(identityProviderList.contains(createdIDP));
    }
}

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

private BaseClientDetails getBaseClientDetails() throws Exception {
    String clientId = RandomStringUtils.randomAlphabetic(6);
    BaseClientDetails client = new BaseClientDetails(clientId, null, "idps.read,idps.write", "password", null);
    client.setClientSecret("test-client-secret");
    mockMvcUtils.createClient(getMockMvc(), adminToken, client);
    return client;
}