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

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

Introduction

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

Prototype

public void setClientSecret(String clientSecret) 

Source Link

Usage

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

@Test
public void revokeOtherClientTokenForbidden() throws Exception {
    String resourceClientId = generator.generate();
    BaseClientDetails resourceClient = new BaseClientDetails(resourceClientId, "", "uaa.resource",
            "client_credentials,password", "uaa.resource");
    resourceClient.setClientSecret("secret");
    createClient(getMockMvc(), adminToken, resourceClient);

    BaseClientDetails client = new BaseClientDetails(generator.generate(), "", "openid",
            "client_credentials,password", null);
    client.setClientSecret("secret");
    createClient(getMockMvc(), adminToken, client);

    //this is the token we will revoke
    String revokeAccessToken = getClientCredentialsOAuthAccessToken(getMockMvc(), client.getClientId(),
            client.getClientSecret(), null, null, false);

    String tokenToBeRevoked = getClientCredentialsOAuthAccessToken(getMockMvc(), resourceClientId,
            resourceClient.getClientSecret(), null, null, true);

    getMockMvc().perform(delete("/oauth/token/revoke/" + tokenToBeRevoked).header("Authorization",
            "Bearer " + revokeAccessToken)).andExpect(status().isForbidden());
}

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

protected BaseClientDetails getAClientWithClientsRead() throws Exception {
    BaseClientDetails client = new BaseClientDetails(generator.generate(), "", "openid",
            "client_credentials,password", "clients.read");
    client.setClientSecret("secret");

    createClient(getMockMvc(), adminToken, client);
    return client;
}

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  av  a  2 s  . 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);
}

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

public static IdentityZone createOtherIdentityZone(String subdomain, MockMvc mockMvc,
        ApplicationContext webApplicationContext) throws Exception {

    BaseClientDetails client = new BaseClientDetails("admin", null, null, "client_credentials",
            "clients.admin,scim.read,scim.write,idps.write,uaa.admin");
    client.setClientSecret("admin-secret");

    return createOtherIdentityZone(subdomain, mockMvc, webApplicationContext, client);
}

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

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

    ScimUser user = mockMvcUtils.createAdminForZone(getMockMvc(), adminToken, "idps.write");
    return mockMvcUtils.getUserOAuthAccessToken(getMockMvc(), client.getClientId(), client.getClientSecret(),
            user.getUserName(), "secr3T", "idps.write");
}

From source file:org.cloudfoundry.identity.uaa.mock.zones.IdentityZoneSwitchingFilterMockMvcTest.java

@Test
public void testNoSwitching() throws Exception {

    final String clientId = UUID.randomUUID().toString();
    BaseClientDetails client = new BaseClientDetails(clientId, null, null, "client_credentials", null);
    client.setClientSecret("secret");

    getMockMvc().perform(/* w  w w  .ja v  a 2s .co m*/
            post("/oauth/clients").header("Authorization", "Bearer " + adminToken).accept(APPLICATION_JSON)
                    .contentType(APPLICATION_JSON).content(JsonUtils.writeValueAsString(client)))
            .andExpect(status().isCreated());

    getMockMvc()
            .perform(get("/oauth/token?grant_type=client_credentials").header("Authorization",
                    "Basic " + new String(Base64
                            .encodeBase64((client.getClientId() + ":" + client.getClientSecret()).getBytes()))))
            .andExpect(status().isOk());
}

From source file:org.cloudfoundry.identity.uaa.mock.zones.IdentityZoneSwitchingFilterMockMvcTest.java

private ClientDetails createClientInOtherZone(String accessToken, ResultMatcher statusMatcher, String headerKey,
        String headerValue) throws Exception {
    String clientId = generator.generate();
    BaseClientDetails client = new BaseClientDetails(clientId, null, null, "client_credentials", null);
    client.setClientSecret("secret");
    getMockMvc()/*from   w w w.  j  ava  2  s.  c o m*/
            .perform(post("/oauth/clients").header(headerKey, headerValue)
                    .header("Authorization", "Bearer " + accessToken).accept(APPLICATION_JSON)
                    .contentType(APPLICATION_JSON).content(JsonUtils.writeValueAsString(client)))
            .andExpect(statusMatcher);
    return client;
}

From source file:org.cloudfoundry.identity.uaa.oauth.AccessController.java

@RequestMapping("/oauth/confirm_access")
public String confirm(Map<String, Object> model, final HttpServletRequest request, Principal principal,
        SessionStatus sessionStatus) throws Exception {

    if (!(principal instanceof Authentication)) {
        sessionStatus.setComplete();//from   w ww  .ja  v  a  2 s.  c o  m
        throw new InsufficientAuthenticationException(
                "User must be authenticated with before authorizing access.");
    }

    AuthorizationRequest clientAuthRequest = (AuthorizationRequest) model.remove("authorizationRequest");
    if (clientAuthRequest == null) {
        model.put("error",
                "No authorization request is present, so we cannot confirm access (we don't know what you are asking for).");
        // response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    } else {
        String clientId = clientAuthRequest.getClientId();
        BaseClientDetails client = (BaseClientDetails) clientDetailsService.loadClientByClientId(clientId);
        // TODO: Need to fix the copy constructor to copy additionalInfo
        BaseClientDetails modifiableClient = new BaseClientDetails(client);
        modifiableClient.setClientSecret(null);
        model.put("auth_request", clientAuthRequest);
        model.put("redirect_uri", getRedirectUri(modifiableClient, clientAuthRequest));

        Map<String, Object> additionalInfo = client.getAdditionalInformation();
        String clientDisplayName = (String) additionalInfo.get(ClientConstants.CLIENT_NAME);
        model.put("client_display_name", (clientDisplayName != null) ? clientDisplayName : clientId);

        // Find the auto approved scopes for this clients
        Set<String> autoApproved = client.getAutoApproveScopes();
        Set<String> autoApprovedScopes = new HashSet<>();
        if (autoApproved != null) {
            if (autoApproved.contains("true")) {
                autoApprovedScopes.addAll(client.getScope());
            } else {
                autoApprovedScopes.addAll(autoApproved);
            }
        }

        List<Approval> filteredApprovals = new ArrayList<Approval>();
        // Remove auto approved scopes
        List<Approval> approvals = approvalStore.getApprovals(Origin.getUserId((Authentication) principal),
                clientId);
        for (Approval approval : approvals) {
            if (!(autoApprovedScopes.contains(approval.getScope()))) {
                filteredApprovals.add(approval);
            }
        }

        ArrayList<String> approvedScopes = new ArrayList<String>();
        ArrayList<String> deniedScopes = new ArrayList<String>();

        for (Approval approval : filteredApprovals) {
            switch (approval.getStatus()) {
            case APPROVED:
                approvedScopes.add(approval.getScope());
                break;
            case DENIED:
                deniedScopes.add(approval.getScope());
                break;
            default:
                logger.error("Encountered an unknown scope. This is not supposed to happen");
                break;
            }
        }

        ArrayList<String> undecidedScopes = new ArrayList<String>();

        // Filter the scopes approved/denied from the ones requested
        for (String scope : clientAuthRequest.getScope()) {
            if (!approvedScopes.contains(scope) && !deniedScopes.contains(scope)
                    && !autoApprovedScopes.contains(scope)) {
                undecidedScopes.add(scope);
            }
        }

        List<Map<String, String>> approvedScopeDetails = getScopes(approvedScopes);
        model.put("approved_scopes", approvedScopeDetails);
        List<Map<String, String>> undecidedScopeDetails = getScopes(undecidedScopes);
        model.put("undecided_scopes", undecidedScopeDetails);
        List<Map<String, String>> deniedScopeDetails = getScopes(deniedScopes);
        model.put("denied_scopes", deniedScopeDetails);

        List<Map<String, String>> allScopes = new ArrayList<>();
        allScopes.addAll(approvedScopeDetails);
        allScopes.addAll(undecidedScopeDetails);
        allScopes.addAll(deniedScopeDetails);

        model.put("scopes", allScopes);

        model.put("message",
                "To confirm or deny access POST to the following locations with the parameters requested.");
        Map<String, Object> options = new HashMap<String, Object>() {
            {
                put("confirm", new HashMap<String, String>() {
                    {
                        put("location", getLocation(request, "oauth/authorize"));
                        put("path", getPath(request, "oauth/authorize"));
                        put("key", OAuth2Utils.USER_OAUTH_APPROVAL);
                        put("value", "true");
                    }

                });
                put("deny", new HashMap<String, String>() {
                    {
                        put("location", getLocation(request, "oauth/authorize"));
                        put("path", getPath(request, "oauth/authorize"));
                        put("key", OAuth2Utils.USER_OAUTH_APPROVAL);
                        put("value", "false");
                    }

                });
            }
        };
        model.put("options", options);
    }

    return "access_confirmation";

}

From source file:org.cloudfoundry.identity.uaa.oauth.ClientAdminBootstrap.java

private void addNewClients() throws Exception {
    for (String clientId : clients.keySet()) {
        Map<String, Object> map = clients.get(clientId);
        BaseClientDetails client = new BaseClientDetails(clientId, (String) map.get("resource-ids"),
                (String) map.get("scope"), (String) map.get("authorized-grant-types"),
                (String) map.get("authorities"), (String) map.get("redirect-uri"));
        client.setClientSecret((String) map.get("secret"));
        Integer validity = (Integer) map.get("access-token-validity");
        Boolean override = (Boolean) map.get("override");
        if (override == null) {
            override = defaultOverride;/*from  w  ww .ja va2s  .c  o m*/
        }
        Map<String, Object> info = new HashMap<String, Object>(map);
        if (validity != null) {
            client.setAccessTokenValiditySeconds(validity);
        }
        validity = (Integer) map.get("refresh-token-validity");
        if (validity != null) {
            client.setRefreshTokenValiditySeconds(validity);
        }
        // UAA does not use the resource ids in client registrations
        client.setResourceIds(Collections.singleton("none"));
        if (client.getScope().isEmpty()) {
            client.setScope(Collections.singleton("uaa.none"));
        }
        if (client.getAuthorities().isEmpty()) {
            client.setAuthorities(Collections.singleton(UaaAuthority.UAA_NONE));
        }
        if (client.getAuthorizedGrantTypes().contains("authorization_code")) {
            client.getAuthorizedGrantTypes().add("refresh_token");
        }
        for (String key : Arrays.asList("resource-ids", "scope", "authorized-grant-types", "authorities",
                "redirect-uri", "secret", "id", "override", "access-token-validity",
                "refresh-token-validity")) {
            info.remove(key);
        }
        client.setAdditionalInformation(info);
        try {
            clientRegistrationService.addClientDetails(client);
        } catch (ClientAlreadyExistsException e) {
            if (override == null || override) {
                logger.debug("Overriding client details for " + clientId);
                clientRegistrationService.updateClientDetails(client);
                if (StringUtils.hasText(client.getClientSecret())) {
                    clientRegistrationService.updateClientSecret(clientId, client.getClientSecret());
                }
            } else {
                // ignore it
                logger.debug(e.getMessage());
            }
        }
    }
}

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

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

    String zonedClientId = "zonedClientId";
    String zonedClientSecret = "zonedClientSecret";
    BaseClientDetails zonedClientDetails = (BaseClientDetails) utils().createClient(getMockMvc(),
            result.getZoneAdminToken(), zonedClientId, zonedClientSecret, Collections.singleton("oauth"),
            Arrays.asList("scim.read"), Arrays.asList("client_credentials", "password"), "scim.read", null,
            result.getIdentityZone());/*from w  w  w .  j a v a  2 s.  c  o m*/
    zonedClientDetails.setClientSecret(zonedClientSecret);

    ScimUser zoneUser = createUserAndAddToGroups(result.getIdentityZone(),
            new HashSet(Arrays.asList("scim.read")));

    String basicDigestHeaderValue = "Basic "
            + new String(Base64.encodeBase64((zonedClientId + ":" + zonedClientSecret).getBytes()));
    MockHttpServletRequestBuilder oauthTokenPost = post("/oauth/token")
            .with(new SetServerNameRequestPostProcessor(result.getIdentityZone().getSubdomain() + ".localhost"))
            .header("Authorization", basicDigestHeaderValue).param("grant_type", "password")
            .param("client_id", zonedClientId).param("username", zoneUser.getUserName())
            .param("password", "password").param("scope", "scim.read");
    MvcResult tokenResult = getMockMvc().perform(oauthTokenPost).andExpect(status().isOk()).andReturn();
    OAuthToken oauthToken = JsonUtils.readValue(tokenResult.getResponse().getContentAsString(),
            OAuthToken.class);
    String zoneUserToken = oauthToken.accessToken;

    MockHttpServletRequestBuilder get = get("/Groups")
            .with(new SetServerNameRequestPostProcessor(result.getIdentityZone().getSubdomain() + ".localhost"))
            .header("Authorization", "Bearer " + zoneUserToken)
            //                .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()));

    get = get("/Groups")
            .with(new SetServerNameRequestPostProcessor(result.getIdentityZone().getSubdomain() + ".localhost"))
            .header("Authorization", "Bearer " + zoneUserToken)
            //                .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()));
}