private Object[] getFieldsForUpdate(ClientDetails clientDetails) { String json = null; try { json = mapper.write(clientDetails.getAdditionalInformation()); } catch (Exception e) { logger.warn("Could not serialize additional information: " + clientDetails, e); } return new Object[] { clientDetails.getResourceIds() != null ? StringUtils.collectionToCommaDelimitedString(clientDetails .getResourceIds()) : null, clientDetails.getScope() != null ? StringUtils.collectionToCommaDelimitedString(clientDetails .getScope()) : null, clientDetails.getAuthorizedGrantTypes() != null ? StringUtils .collectionToCommaDelimitedString(clientDetails.getAuthorizedGrantTypes()) : null, clientDetails.getRegisteredRedirectUri() != null ? StringUtils .collectionToCommaDelimitedString(clientDetails.getRegisteredRedirectUri()) : null, clientDetails.getAuthorities() != null ? StringUtils.collectionToCommaDelimitedString(clientDetails .getAuthorities()) : null, clientDetails.getAccessTokenValiditySeconds(), clientDetails.getRefreshTokenValiditySeconds(), json, getAutoApproveScopes(clientDetails), clientDetails.getClientId() }; }
private Object[] getFields(ClientDetails clientDetails) { Object[] fieldsForUpdate = getFieldsForUpdate(clientDetails); Object[] fields = new Object[fieldsForUpdate.length + 1]; System.arraycopy(fieldsForUpdate, 0, fields, 1, fieldsForUpdate.length); fields[0] = clientDetails.getClientSecret() != null ? passwordEncoder.encode(clientDetails.getClientSecret()) : null; return fields; }
private String getAutoApproveScopes(ClientDetails clientDetails) { if (clientDetails.isAutoApprove("true")) { return "true"; // all scopes autoapproved } Set<String> scopes = new HashSet<String>(); for (String scope : clientDetails.getScope()) { if (clientDetails.isAutoApprove(scope)) { scopes.add(scope); } } return StringUtils.collectionToCommaDelimitedString(scopes); }
public static String getRevocableTokenSignature(ClientDetails client, String clientSecret, UaaUser user) { String tokenSalt = (String) client.getAdditionalInformation().get(ClientConstants.TOKEN_SALT); String clientId = client.getClientId(); return getRevocableTokenSignature(user, tokenSalt, clientId, clientSecret); }
assertSet((String) map.get("scope"), Collections.singleton("uaa.none"), created.getScope(), String.class); assertSet((String) map.get("resource-ids"), new HashSet(Arrays.asList("none")), created.getResourceIds(), String.class); authTypes+=",refresh_token"; assertSet(authTypes, Collections.emptySet(), created.getAuthorizedGrantTypes(), String.class); assertEquals(validity, created.getAccessTokenValiditySeconds()); validity = (Integer) map.get("refresh-token-validity"); assertEquals(validity, created.getRefreshTokenValiditySeconds()); assertSet((String) map.get("authorities"), Collections.emptySet(), created.getAuthorities(), GrantedAuthority.class); assertTrue("Client should contain additional information key:"+ entry.getKey(), created.getAdditionalInformation().containsKey(entry.getKey())); if (entry.getValue()!=null) { assertEquals(entry.getValue(), created.getAdditionalInformation().get(entry.getKey()));
@Test public void testCreateLimitedClient() { BaseClientDetails clientDetails = new BaseClientDetails("valid-client", null, "openid", "authorization_code,password", "uaa.resource"); clientDetails.setClientSecret("secret"); clientDetails.addAdditionalInformation(ALLOWED_PROVIDERS, Collections.singletonList(OriginKeys.UAA)); ClientDetails validatedClientDetails = zoneEndpointsClientDetailsValidator.validate(clientDetails, Mode.CREATE); assertEquals(clientDetails.getClientId(), validatedClientDetails.getClientId()); assertEquals(clientDetails.getScope(), validatedClientDetails.getScope()); assertEquals(clientDetails.getAuthorizedGrantTypes(), validatedClientDetails.getAuthorizedGrantTypes()); assertEquals(clientDetails.getAuthorities(), validatedClientDetails.getAuthorities()); assertEquals(Collections.singleton("none"), validatedClientDetails.getResourceIds()); assertEquals(Collections.singletonList(OriginKeys.UAA), validatedClientDetails.getAdditionalInformation().get(ALLOWED_PROVIDERS)); }
@Test public void testEnvironmentalOverrides() { this.context = new AnnotationConfigServletWebServerApplicationContext(); TestPropertyValues .of("security.oauth2.client.clientId:myclientid", "security.oauth2.client.clientSecret:mysecret", "security.oauth2.client.autoApproveScopes:read,write", "security.oauth2.client.accessTokenValiditySeconds:40", "security.oauth2.client.refreshTokenValiditySeconds:80") .applyTo(this.context); this.context.register(AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); ClientDetails config = this.context.getBean(ClientDetails.class); assertThat(config.getClientId()).isEqualTo("myclientid"); assertThat(config.getClientSecret()).isEqualTo("mysecret"); assertThat(config.isAutoApprove("read")).isTrue(); assertThat(config.isAutoApprove("write")).isTrue(); assertThat(config.isAutoApprove("foo")).isFalse(); assertThat(config.getAccessTokenValiditySeconds()).isEqualTo(40); assertThat(config.getRefreshTokenValiditySeconds()).isEqualTo(80); verifyAuthentication(config); }
@Test void testDeleteClientsTxRollbackInvalidId() throws Exception { int count = 5; BaseClientDetails[] details = new BaseClientDetails[count]; for (int i = 0; i < details.length; i++) { details[i] = (BaseClientDetails) createClient(adminToken, null, SECRET, null); } String firstId = details[0].getClientId(); details[0].setClientId("unknown.client.id"); MockHttpServletRequestBuilder deleteClientsPost = post("/oauth/clients/tx/delete") .header("Authorization", "Bearer " + adminToken) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON) .content(JsonUtils.writeValueAsString(details)); ResultActions result = mockMvc.perform(deleteClientsPost); result.andExpect(status().isNotFound()); details[0].setClientId(firstId); for (ClientDetails client : details) { ClientDetails c = getClient(client.getClientId()); assertNotNull(c); assertNull(c.getClientSecret()); assertNull(c.getRefreshTokenValiditySeconds()); } verify(mockApplicationEventPublisher, times(count)).publishEvent(abstractUaaEventCaptor.capture()); }
@Override public AuditEvent getAuditEvent() { ClientDetails clientDetails = Optional.ofNullable(getClient()).orElse(nonExistent); Map<String, Object> auditData = new HashMap(); auditData.put("scopes", clientDetails.getScope()); List<String> authorities = clientDetails .getAuthorities() .stream() .map(a -> a.getAuthority()) .collect(Collectors.toList()); auditData.put("authorities", authorities); return createAuditRecord( clientDetails.getClientId(), getAuditEventType(), getOrigin(getPrincipal()), JsonUtils.writeValueAsString(auditData) ); }
private Collection<GrantedAuthority> getClientPermissions(ClientDetails client) { Collection<GrantedAuthority> clientScopes; clientScopes = new ArrayList<>(); for(String scope : client.getScope()) { clientScopes.add(new XOAuthUserAuthority(scope)); } return clientScopes; }
public void validateScope(AuthorizationRequest authorizationRequest, ClientDetails client) throws InvalidScopeException { if (GRANT_TYPE_CLIENT_CREDENTIALS.equalsIgnoreCase(authorizationRequest.getRequestParameters().get(OAuth2Utils.GRANT_TYPE))) { validateScope(authorizationRequest.getScope(), getAuthorities(client.getAuthorities()), false); } else { validateScope(authorizationRequest.getScope(), client.getScope(), true); } }
@Test public void testClientinfo() { Mockito.when(clientDetailsService.loadClientByClientId("foo", "uaa")).thenReturn(foo); ClientDetails client = endpoint.clientinfo(new UsernamePasswordAuthenticationToken("foo", "<NONE>")); assertEquals("foo", client.getClientId()); assertNull(client.getClientSecret()); assertTrue(client.getAdditionalInformation().isEmpty()); }
public OAuth2Request createOAuth2Request(ClientDetails client) { Map<String, String> requestParameters = getRequestParameters(); HashMap<String, String> modifiable = new HashMap<String, String>(requestParameters); // Remove password if present to prevent leaks modifiable.remove("password"); modifiable.remove("client_secret"); // Add grant type so it can be retrieved from OAuth2Request modifiable.put("grant_type", grantType); return new OAuth2Request(modifiable, client.getClientId(), client.getAuthorities(), true, this.getScope(), client.getResourceIds(), null, null, null); }
public void updateClientDetails(ClientDetails clientDetails) throws NoSuchClientException { int count = jdbcTemplate.update(updateClientDetailsSql, getFieldsForUpdate(clientDetails)); if (count != 1) { throw new NoSuchClientException("No client found with id = " + clientDetails.getClientId()); } }
@Override public OAuth2Request createOAuth2Request(ClientDetails client, TokenRequest tokenRequest, JWT assertion) { try { JWTClaimsSet claims = assertion.getJWTClaimsSet(); Set<String> scope = OAuth2Utils.parseParameterList(claims.getStringClaim("scope")); Set<String> resources = Sets.newHashSet(claims.getAudience()); return new OAuth2Request(tokenRequest.getRequestParameters(), client.getClientId(), client.getAuthorities(), true, scope, resources, null, null, null); } catch (ParseException e) { return null; } }
@Test public void testCreateClientDetails() throws Exception { when(clientDetailsService.retrieve(anyString(), anyString())).thenReturn(input); ClientDetails result = endpoints.createClientDetails(input); assertNull(result.getClientSecret()); verify(clientDetailsService).create(detail, IdentityZoneHolder.get().getId()); assertEquals(1463510591, result.getAdditionalInformation().get("lastModified")); }
@Test public void testPasswordHashDidNotChangeDuringBootstrap() throws Exception { Map<String, Object> map = createClientMap("foo"); ClientDetails created = doSimpleTest(map); assertSet((String) map.get("redirect-uri"), null, created.getRegisteredRedirectUri(), String.class); ClientDetails details = clientRegistrationService.loadClientByClientId("foo"); assertTrue("Password should match bar:", bootstrap.getPasswordEncoder().matches("bar", details.getClientSecret())); String hash = details.getClientSecret(); created = doSimpleTest(map); assertSet((String) map.get("redirect-uri"), null, created.getRegisteredRedirectUri(), String.class); details = clientRegistrationService.loadClientByClientId("foo"); assertTrue("Password should match bar:", bootstrap.getPasswordEncoder().matches("bar", details.getClientSecret())); assertEquals("Password hash must not change on an update:", hash, details.getClientSecret()); }
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { ClientDetails clientDetails; try { clientDetails = clientDetailsService.loadClientByClientId(username); } catch (NoSuchClientException e) { throw new UsernameNotFoundException(e.getMessage(), e); } String clientSecret = clientDetails.getClientSecret(); if (clientSecret== null || clientSecret.trim().length()==0) { clientSecret = emptyPassword; } return new User(username, clientSecret, clientDetails.getAuthorities()); }
protected void validateGrantType(String grantType, ClientDetails clientDetails) { Collection<String> authorizedGrantTypes = clientDetails.getAuthorizedGrantTypes(); if (authorizedGrantTypes != null && !authorizedGrantTypes.isEmpty() && !authorizedGrantTypes.contains(grantType)) { throw new InvalidClientException("Unauthorized grant type: " + grantType); } }
public String resolveRedirect(String requestedRedirect, ClientDetails client) throws OAuth2Exception { Set<String> authorizedGrantTypes = client.getAuthorizedGrantTypes(); if (authorizedGrantTypes.isEmpty()) { throw new InvalidGrantException("A client must have at least one authorized grant type."); } if (!containsRedirectGrantType(authorizedGrantTypes)) { throw new InvalidGrantException( "A redirect_uri can only be used by implicit or authorization_code grant types."); } Set<String> registeredRedirectUris = client.getRegisteredRedirectUri(); if (registeredRedirectUris == null || registeredRedirectUris.isEmpty()) { throw new InvalidRequestException("At least one redirect_uri must be registered with the client."); } return obtainMatchingRedirect(registeredRedirectUris, requestedRedirect); }