repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospectorTests.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.introspection; import java.io.IOException; import java.time.Instant; import java.util.Arrays; import java.util.Base64; import java.util.HashMap; import java.util.Map; import java.util.Optional; import net.minidev.json.JSONArray; import net.minidev.json.JSONObject; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.springframework.core.convert.converter.Converter; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames; import org.springframework.web.client.RestOperations; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assumptions.assumeThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Tests for {@link NimbusOpaqueTokenIntrospector} */ public class NimbusOpaqueTokenIntrospectorTests { private static final String INTROSPECTION_URL = "https://server.example.com"; private static final String CLIENT_ID = "client"; private static final String CLIENT_SECRET = "secret"; // @formatter:off private static final String ACTIVE_RESPONSE = "{\n" + " \"active\": true,\n" + " \"client_id\": \"l238j323ds-23ij4\",\n" + " \"username\": \"jdoe\",\n" + " \"scope\": \"read write dolphin\",\n" + " \"sub\": \"Z5O3upPC88QrAjx00dis\",\n" + " \"aud\": \"https://protected.example.net/resource\",\n" + " \"iss\": \"https://server.example.com/\",\n" + " \"exp\": 1419356238,\n" + " \"iat\": 1419350238,\n" + " \"extension_field\": \"twenty-seven\"\n" + " }"; // @formatter:on // @formatter:off private static final String INACTIVE_RESPONSE = "{\n" + " \"active\": false\n" + " }"; // @formatter:on // @formatter:off private static final String INVALID_RESPONSE = "{\n" + " \"client_id\": \"l238j323ds-23ij4\",\n" + " \"username\": \"jdoe\",\n" + " \"scope\": \"read write dolphin\",\n" + " \"sub\": \"Z5O3upPC88QrAjx00dis\",\n" + " \"aud\": \"https://protected.example.net/resource\",\n" + " \"iss\": \"https://server.example.com/\",\n" + " \"exp\": 1419356238,\n" + " \"iat\": 1419350238,\n" + " \"extension_field\": \"twenty-seven\"\n" + " }"; // @formatter:on // @formatter:off private static final String MALFORMED_ISSUER_RESPONSE = "{\n" + " \"active\" : \"true\",\n" + " \"iss\" : \"badissuer\"\n" + " }"; // @formatter:on // @formatter:off private static final String MALFORMED_SCOPE_RESPONSE = "{\n" + " \"active\": true,\n" + " \"client_id\": \"l238j323ds-23ij4\",\n" + " \"username\": \"jdoe\",\n" + " \"scope\": [ \"read\", \"write\", \"dolphin\" ],\n" + " \"sub\": \"Z5O3upPC88QrAjx00dis\",\n" + " \"aud\": \"https://protected.example.net/resource\",\n" + " \"iss\": \"https://server.example.com/\",\n" + " \"exp\": 1419356238,\n" + " \"iat\": 1419350238,\n" + " \"extension_field\": \"twenty-seven\"\n" + " }"; // @formatter:on private static final ResponseEntity<String> ACTIVE = response(ACTIVE_RESPONSE); private static final ResponseEntity<String> INACTIVE = response(INACTIVE_RESPONSE); private static final ResponseEntity<String> INVALID = response(INVALID_RESPONSE); private static final ResponseEntity<String> MALFORMED_ISSUER = response(MALFORMED_ISSUER_RESPONSE); private static final ResponseEntity<String> MALFORMED_SCOPE = response(MALFORMED_SCOPE_RESPONSE); @Test public void introspectWhenActiveTokenThenOk() throws Exception { try (MockWebServer server = new MockWebServer()) { server.setDispatcher(requiresAuth(CLIENT_ID, CLIENT_SECRET, ACTIVE_RESPONSE)); String introspectUri = server.url("/introspect").toString(); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(introspectUri, CLIENT_ID, CLIENT_SECRET); OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token"); // @formatter:off assertThat(authority.getAttributes()) .isNotNull() .containsEntry(OAuth2TokenIntrospectionClaimNames.ACTIVE, true) .containsEntry(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("https://protected.example.net/resource")) .containsEntry(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, "l238j323ds-23ij4") .containsEntry(OAuth2TokenIntrospectionClaimNames.EXP, Instant.ofEpochSecond(1419356238)) .containsEntry(OAuth2TokenIntrospectionClaimNames.ISS, "https://server.example.com/") .containsEntry(OAuth2TokenIntrospectionClaimNames.SCOPE, Arrays.asList("read", "write", "dolphin")) .containsEntry(OAuth2TokenIntrospectionClaimNames.SUB, "Z5O3upPC88QrAjx00dis") .containsEntry(OAuth2TokenIntrospectionClaimNames.USERNAME, "jdoe") .containsEntry("extension_field", "twenty-seven"); // @formatter:on } } @Test public void introspectWhenBadClientCredentialsThenError() throws IOException { try (MockWebServer server = new MockWebServer()) { server.setDispatcher(requiresAuth(CLIENT_ID, CLIENT_SECRET, ACTIVE_RESPONSE)); String introspectUri = server.url("/introspect").toString(); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(introspectUri, CLIENT_ID, "wrong"); assertThatExceptionOfType(OAuth2IntrospectionException.class) .isThrownBy(() -> introspectionClient.introspect("token")); } } @Test public void introspectWhenInactiveTokenThenInvalidToken() { RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(INACTIVE); // @formatter:off assertThatExceptionOfType(OAuth2IntrospectionException.class) .isThrownBy(() -> introspectionClient.introspect("token")) .withMessage("Provided token isn't active"); // @formatter:on } @Test public void introspectWhenActiveTokenThenParsesValuesInResponse() { Map<String, Object> introspectedValues = new HashMap<>(); introspectedValues.put(OAuth2TokenIntrospectionClaimNames.ACTIVE, true); introspectedValues.put(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("aud")); introspectedValues.put(OAuth2TokenIntrospectionClaimNames.NBF, 29348723984L); RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))) .willReturn(response(new JSONObject(introspectedValues).toJSONString())); OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token"); // @formatter:off assertThat(authority.getAttributes()) .isNotNull() .containsEntry(OAuth2TokenIntrospectionClaimNames.ACTIVE, true) .containsEntry(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("aud")) .containsEntry(OAuth2TokenIntrospectionClaimNames.NBF, Instant.ofEpochSecond(29348723984L)) .doesNotContainKey(OAuth2TokenIntrospectionClaimNames.CLIENT_ID) .doesNotContainKey(OAuth2TokenIntrospectionClaimNames.SCOPE); // @formatter:on } @Test public void introspectWhenIntrospectionEndpointThrowsExceptionThenInvalidToken() { RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))) .willThrow(new IllegalStateException("server was unresponsive")); // @formatter:off assertThatExceptionOfType(OAuth2IntrospectionException.class) .isThrownBy(() -> introspectionClient.introspect("token")) .withMessage("server was unresponsive"); // @formatter:on } @Test public void introspectWhenIntrospectionEndpointReturnsMalformedResponseThenInvalidToken() { RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(response("malformed")); assertThatExceptionOfType(OAuth2IntrospectionException.class) .isThrownBy(() -> introspectionClient.introspect("token")); } @Test public void introspectWhenIntrospectionTokenReturnsInvalidResponseThenInvalidToken() { RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(INVALID); assertThatExceptionOfType(OAuth2IntrospectionException.class) .isThrownBy(() -> introspectionClient.introspect("token")); } @Test public void introspectWhenIntrospectionTokenReturnsMalformedIssuerResponseThenInvalidToken() { RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(MALFORMED_ISSUER); assertThatExceptionOfType(OAuth2IntrospectionException.class) .isThrownBy(() -> introspectionClient.introspect("token")); } // gh-7563 @Test public void introspectWhenIntrospectionTokenReturnsMalformedScopeThenEmptyAuthorities() { RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(MALFORMED_SCOPE); OAuth2AuthenticatedPrincipal principal = introspectionClient.introspect("token"); assertThat(principal.getAuthorities()).isEmpty(); JSONArray scope = principal.getAttribute("scope"); assertThat(scope).containsExactly("read", "write", "dolphin"); } @Test public void constructorWhenIntrospectionUriIsNullThenIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new NimbusOpaqueTokenIntrospector(null, CLIENT_ID, CLIENT_SECRET)); } @Test public void constructorWhenClientIdIsNullThenIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, null, CLIENT_SECRET)); } @Test public void constructorWhenClientSecretIsNullThenIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, CLIENT_ID, null)); } @Test public void constructorWhenRestOperationsIsNullThenIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, null)); } @Test public void setRequestEntityConverterWhenConverterIsNullThenExceptionIsThrown() { RestOperations restOperations = mock(RestOperations.class); NimbusOpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> introspectionClient.setRequestEntityConverter(null)); } @SuppressWarnings("unchecked") @Test public void setRequestEntityConverterWhenNonNullConverterGivenThenConverterUsed() { RestOperations restOperations = mock(RestOperations.class); Converter<String, RequestEntity<?>> requestEntityConverter = mock(Converter.class); RequestEntity requestEntity = mock(RequestEntity.class); String tokenToIntrospect = "some token"; given(requestEntityConverter.convert(tokenToIntrospect)).willReturn(requestEntity); given(restOperations.exchange(requestEntity, String.class)).willReturn(ACTIVE); NimbusOpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); introspectionClient.setRequestEntityConverter(requestEntityConverter); introspectionClient.introspect(tokenToIntrospect); verify(requestEntityConverter).convert(tokenToIntrospect); } @Test public void handleMissingContentType() { RestOperations restOperations = mock(RestOperations.class); ResponseEntity<String> stubResponse = ResponseEntity.ok(ACTIVE_RESPONSE); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(stubResponse); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); // Protect against potential regressions where a default content type might be // added by default. assumeThat(stubResponse.getHeaders().getContentType()).isNull(); assertThatExceptionOfType(OAuth2IntrospectionException.class) .isThrownBy(() -> introspectionClient.introspect("sometokenhere")); } @ParameterizedTest(name = "{displayName} when Content-Type={0}") @ValueSource(strings = { MediaType.APPLICATION_CBOR_VALUE, MediaType.TEXT_MARKDOWN_VALUE, MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE }) public void handleNonJsonContentType(String type) { RestOperations restOperations = mock(RestOperations.class); ResponseEntity<String> stubResponse = ResponseEntity.ok().contentType(MediaType.parseMediaType(type)) .body(ACTIVE_RESPONSE); given(restOperations.exchange(any(RequestEntity.class), eq(String.class))).willReturn(stubResponse); OpaqueTokenIntrospector introspectionClient = new NimbusOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); assertThatExceptionOfType(OAuth2IntrospectionException.class) .isThrownBy(() -> introspectionClient.introspect("sometokenhere")); } private static ResponseEntity<String> response(String content) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new ResponseEntity<>(content, headers, HttpStatus.OK); } private static Dispatcher requiresAuth(String username, String password, String response) { return new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) { String authorization = request.getHeader(HttpHeaders.AUTHORIZATION); // @formatter:off return Optional.ofNullable(authorization) .filter((a) -> isAuthorized(authorization, username, password)) .map((a) -> ok(response)) .orElse(unauthorized()); // @formatter:on } }; } private static boolean isAuthorized(String authorization, String username, String password) { String[] values = new String(Base64.getDecoder().decode(authorization.substring(6))).split(":"); return username.equals(values[0]) && password.equals(values[1]); } private static MockResponse ok(String response) { // @formatter:off return new MockResponse().setBody(response) .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); // @formatter:on } private static MockResponse unauthorized() { return new MockResponse().setResponseCode(401); } }
16,769
42.785901
111
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/SpringOpaqueTokenIntrospectorTests.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.introspection; import java.io.IOException; import java.time.Instant; import java.util.Arrays; import java.util.Base64; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Optional; import com.nimbusds.jose.util.JSONObjectUtils; import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.RecordedRequest; import org.junit.jupiter.api.Test; import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.convert.converter.Converter; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames; import org.springframework.web.client.RestOperations; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Tests for {@link SpringOpaqueTokenIntrospector} */ public class SpringOpaqueTokenIntrospectorTests { private static final ParameterizedTypeReference<Map<String, Object>> STRING_OBJECT_MAP = new ParameterizedTypeReference<Map<String, Object>>() { }; private static final String INTROSPECTION_URL = "https://server.example.com"; private static final String CLIENT_ID = "client"; private static final String CLIENT_SECRET = "secret"; // @formatter:off private static final String ACTIVE_RESPONSE = "{\n" + " \"active\": true,\n" + " \"client_id\": \"l238j323ds-23ij4\",\n" + " \"username\": \"jdoe\",\n" + " \"scope\": \"read write dolphin\",\n" + " \"sub\": \"Z5O3upPC88QrAjx00dis\",\n" + " \"aud\": \"https://protected.example.net/resource\",\n" + " \"iss\": \"https://server.example.com/\",\n" + " \"exp\": 1419356238,\n" + " \"iat\": 1419350238,\n" + " \"extension_field\": \"twenty-seven\"\n" + " }"; // @formatter:on // @formatter:off private static final String INACTIVE_RESPONSE = "{\n" + " \"active\": false\n" + " }"; // @formatter:on // @formatter:off private static final String INVALID_RESPONSE = "{\n" + " \"client_id\": \"l238j323ds-23ij4\",\n" + " \"username\": \"jdoe\",\n" + " \"scope\": \"read write dolphin\",\n" + " \"sub\": \"Z5O3upPC88QrAjx00dis\",\n" + " \"aud\": \"https://protected.example.net/resource\",\n" + " \"iss\": \"https://server.example.com/\",\n" + " \"exp\": 1419356238,\n" + " \"iat\": 1419350238,\n" + " \"extension_field\": \"twenty-seven\"\n" + " }"; // @formatter:on // @formatter:off private static final String MALFORMED_SCOPE_RESPONSE = "{\n" + " \"active\": true,\n" + " \"client_id\": \"l238j323ds-23ij4\",\n" + " \"username\": \"jdoe\",\n" + " \"scope\": [ \"read\", \"write\", \"dolphin\" ],\n" + " \"sub\": \"Z5O3upPC88QrAjx00dis\",\n" + " \"aud\": \"https://protected.example.net/resource\",\n" + " \"iss\": \"https://server.example.com/\",\n" + " \"exp\": 1419356238,\n" + " \"iat\": 1419350238,\n" + " \"extension_field\": \"twenty-seven\"\n" + " }"; // @formatter:on private static final ResponseEntity<Map<String, Object>> ACTIVE = response(ACTIVE_RESPONSE); private static final ResponseEntity<Map<String, Object>> INACTIVE = response(INACTIVE_RESPONSE); private static final ResponseEntity<Map<String, Object>> INVALID = response(INVALID_RESPONSE); private static final ResponseEntity<Map<String, Object>> MALFORMED_SCOPE = response(MALFORMED_SCOPE_RESPONSE); @Test public void introspectWhenActiveTokenThenOk() throws Exception { try (MockWebServer server = new MockWebServer()) { server.setDispatcher(requiresAuth(CLIENT_ID, CLIENT_SECRET, ACTIVE_RESPONSE)); String introspectUri = server.url("/introspect").toString(); OpaqueTokenIntrospector introspectionClient = new SpringOpaqueTokenIntrospector(introspectUri, CLIENT_ID, CLIENT_SECRET); OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token"); // @formatter:off assertThat(authority.getAttributes()) .isNotNull() .containsEntry(OAuth2TokenIntrospectionClaimNames.ACTIVE, true) .containsEntry(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("https://protected.example.net/resource")) .containsEntry(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, "l238j323ds-23ij4") .containsEntry(OAuth2TokenIntrospectionClaimNames.EXP, Instant.ofEpochSecond(1419356238)) .containsEntry(OAuth2TokenIntrospectionClaimNames.ISS, "https://server.example.com/") .containsEntry(OAuth2TokenIntrospectionClaimNames.SCOPE, Arrays.asList("read", "write", "dolphin")) .containsEntry(OAuth2TokenIntrospectionClaimNames.SUB, "Z5O3upPC88QrAjx00dis") .containsEntry(OAuth2TokenIntrospectionClaimNames.USERNAME, "jdoe") .containsEntry("extension_field", "twenty-seven"); // @formatter:on } } @Test public void introspectWhenBadClientCredentialsThenError() throws IOException { try (MockWebServer server = new MockWebServer()) { server.setDispatcher(requiresAuth(CLIENT_ID, CLIENT_SECRET, ACTIVE_RESPONSE)); String introspectUri = server.url("/introspect").toString(); OpaqueTokenIntrospector introspectionClient = new SpringOpaqueTokenIntrospector(introspectUri, CLIENT_ID, "wrong"); assertThatExceptionOfType(OAuth2IntrospectionException.class) .isThrownBy(() -> introspectionClient.introspect("token")); } } @Test public void introspectWhenInactiveTokenThenInvalidToken() { RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new SpringOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); given(restOperations.exchange(any(RequestEntity.class), eq(STRING_OBJECT_MAP))).willReturn(INACTIVE); // @formatter:off assertThatExceptionOfType(OAuth2IntrospectionException.class) .isThrownBy(() -> introspectionClient.introspect("token")) .withMessage("Provided token isn't active"); // @formatter:on } @Test public void introspectWhenActiveTokenThenParsesValuesInResponse() { Map<String, Object> introspectedValues = new HashMap<>(); introspectedValues.put(OAuth2TokenIntrospectionClaimNames.ACTIVE, true); introspectedValues.put(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("aud")); introspectedValues.put(OAuth2TokenIntrospectionClaimNames.NBF, 29348723984L); RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new SpringOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); given(restOperations.exchange(any(RequestEntity.class), eq(STRING_OBJECT_MAP))) .willReturn(response(introspectedValues)); OAuth2AuthenticatedPrincipal authority = introspectionClient.introspect("token"); // @formatter:off assertThat(authority.getAttributes()) .isNotNull() .containsEntry(OAuth2TokenIntrospectionClaimNames.ACTIVE, true) .containsEntry(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("aud")) .containsEntry(OAuth2TokenIntrospectionClaimNames.NBF, Instant.ofEpochSecond(29348723984L)) .doesNotContainKey(OAuth2TokenIntrospectionClaimNames.CLIENT_ID) .doesNotContainKey(OAuth2TokenIntrospectionClaimNames.SCOPE); // @formatter:on } @Test public void introspectWhenIntrospectionEndpointThrowsExceptionThenInvalidToken() { RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new SpringOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); given(restOperations.exchange(any(RequestEntity.class), eq(STRING_OBJECT_MAP))) .willThrow(new IllegalStateException("server was unresponsive")); // @formatter:off assertThatExceptionOfType(OAuth2IntrospectionException.class) .isThrownBy(() -> introspectionClient.introspect("token")) .withMessage("server was unresponsive"); // @formatter:on } @Test public void introspectWhenIntrospectionEndpointReturnsMalformedResponseThenInvalidToken() { RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new SpringOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); given(restOperations.exchange(any(RequestEntity.class), eq(STRING_OBJECT_MAP))).willReturn(response("{}")); assertThatExceptionOfType(OAuth2IntrospectionException.class) .isThrownBy(() -> introspectionClient.introspect("token")); } @Test public void introspectWhenIntrospectionTokenReturnsInvalidResponseThenInvalidToken() { RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new SpringOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); given(restOperations.exchange(any(RequestEntity.class), eq(STRING_OBJECT_MAP))).willReturn(INVALID); assertThatExceptionOfType(OAuth2IntrospectionException.class) .isThrownBy(() -> introspectionClient.introspect("token")); } // gh-7563 @Test public void introspectWhenIntrospectionTokenReturnsMalformedScopeThenEmptyAuthorities() { RestOperations restOperations = mock(RestOperations.class); OpaqueTokenIntrospector introspectionClient = new SpringOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); given(restOperations.exchange(any(RequestEntity.class), eq(STRING_OBJECT_MAP))).willReturn(MALFORMED_SCOPE); OAuth2AuthenticatedPrincipal principal = introspectionClient.introspect("token"); assertThat(principal.getAuthorities()).isEmpty(); Collection<String> scope = principal.getAttribute("scope"); assertThat(scope).containsExactly("read", "write", "dolphin"); } @Test public void constructorWhenIntrospectionUriIsNullThenIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new SpringOpaqueTokenIntrospector(null, CLIENT_ID, CLIENT_SECRET)); } @Test public void constructorWhenClientIdIsNullThenIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new SpringOpaqueTokenIntrospector(INTROSPECTION_URL, null, CLIENT_SECRET)); } @Test public void constructorWhenClientSecretIsNullThenIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new SpringOpaqueTokenIntrospector(INTROSPECTION_URL, CLIENT_ID, null)); } @Test public void constructorWhenRestOperationsIsNullThenIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new SpringOpaqueTokenIntrospector(INTROSPECTION_URL, null)); } @Test public void setRequestEntityConverterWhenConverterIsNullThenExceptionIsThrown() { RestOperations restOperations = mock(RestOperations.class); SpringOpaqueTokenIntrospector introspectionClient = new SpringOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> introspectionClient.setRequestEntityConverter(null)); } @SuppressWarnings("unchecked") @Test public void setRequestEntityConverterWhenNonNullConverterGivenThenConverterUsed() { RestOperations restOperations = mock(RestOperations.class); Converter<String, RequestEntity<?>> requestEntityConverter = mock(Converter.class); RequestEntity requestEntity = mock(RequestEntity.class); String tokenToIntrospect = "some token"; given(requestEntityConverter.convert(tokenToIntrospect)).willReturn(requestEntity); given(restOperations.exchange(requestEntity, STRING_OBJECT_MAP)).willReturn(ACTIVE); SpringOpaqueTokenIntrospector introspectionClient = new SpringOpaqueTokenIntrospector(INTROSPECTION_URL, restOperations); introspectionClient.setRequestEntityConverter(requestEntityConverter); introspectionClient.introspect(tokenToIntrospect); verify(requestEntityConverter).convert(tokenToIntrospect); } private static ResponseEntity<Map<String, Object>> response(String content) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); try { return new ResponseEntity<>(JSONObjectUtils.parse(content), headers, HttpStatus.OK); } catch (Exception ex) { throw new IllegalArgumentException(ex); } } private static ResponseEntity<Map<String, Object>> response(Map<String, Object> content) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); try { return new ResponseEntity<>(content, headers, HttpStatus.OK); } catch (Exception ex) { throw new IllegalArgumentException(ex); } } private static Dispatcher requiresAuth(String username, String password, String response) { return new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) { String authorization = request.getHeader(HttpHeaders.AUTHORIZATION); // @formatter:off return Optional.ofNullable(authorization) .filter((a) -> isAuthorized(authorization, username, password)) .map((a) -> ok(response)) .orElse(unauthorized()); // @formatter:on } }; } private static boolean isAuthorized(String authorization, String username, String password) { String[] values = new String(Base64.getDecoder().decode(authorization.substring(6))).split(":"); return username.equals(values[0]) && password.equals(values[1]); } private static MockResponse ok(String response) { // @formatter:off return new MockResponse().setBody(response) .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); // @formatter:on } private static MockResponse unauthorized() { return new MockResponse().setResponseCode(401); } }
14,949
41.714286
145
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/introspection/OAuth2IntrospectionAuthenticatedPrincipalTests.java
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.introspection; import java.time.Instant; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link OAuth2IntrospectionAuthenticatedPrincipal} * * @author David Kovac */ public class OAuth2IntrospectionAuthenticatedPrincipalTests { private static final String AUTHORITY = "SCOPE_read"; private static final Collection<GrantedAuthority> AUTHORITIES = AuthorityUtils.createAuthorityList(AUTHORITY); private static final String SUBJECT = "test-subject"; private static final String ACTIVE_CLAIM = "active"; private static final String CLIENT_ID_CLAIM = "client_id"; private static final String USERNAME_CLAIM = "username"; private static final String TOKEN_TYPE_CLAIM = "token_type"; private static final String EXP_CLAIM = "exp"; private static final String IAT_CLAIM = "iat"; private static final String NBF_CLAIM = "nbf"; private static final String SUB_CLAIM = "sub"; private static final String AUD_CLAIM = "aud"; private static final String ISS_CLAIM = "iss"; private static final String JTI_CLAIM = "jti"; private static final boolean ACTIVE_VALUE = true; private static final String CLIENT_ID_VALUE = "client-id-1"; private static final String USERNAME_VALUE = "username-1"; private static final String TOKEN_TYPE_VALUE = "token-type-1"; private static final long EXP_VALUE = Instant.now().plusSeconds(60).getEpochSecond(); private static final long IAT_VALUE = Instant.now().getEpochSecond(); private static final long NBF_VALUE = Instant.now().plusSeconds(5).getEpochSecond(); private static final String SUB_VALUE = "subject1"; private static final List<String> AUD_VALUE = Arrays.asList("aud1", "aud2"); private static final String ISS_VALUE = "https://provider.com"; private static final String JTI_VALUE = "jwt-id-1"; private static final Map<String, Object> CLAIMS; static { CLAIMS = new HashMap<>(); CLAIMS.put(ACTIVE_CLAIM, ACTIVE_VALUE); CLAIMS.put(CLIENT_ID_CLAIM, CLIENT_ID_VALUE); CLAIMS.put(USERNAME_CLAIM, USERNAME_VALUE); CLAIMS.put(TOKEN_TYPE_CLAIM, TOKEN_TYPE_VALUE); CLAIMS.put(EXP_CLAIM, EXP_VALUE); CLAIMS.put(IAT_CLAIM, IAT_VALUE); CLAIMS.put(NBF_CLAIM, NBF_VALUE); CLAIMS.put(SUB_CLAIM, SUB_VALUE); CLAIMS.put(AUD_CLAIM, AUD_VALUE); CLAIMS.put(ISS_CLAIM, ISS_VALUE); CLAIMS.put(JTI_CLAIM, JTI_VALUE); } @Test public void constructorWhenAttributesIsNullOrEmptyThenIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> new OAuth2IntrospectionAuthenticatedPrincipal(null, AUTHORITIES)); assertThatIllegalArgumentException() .isThrownBy(() -> new OAuth2IntrospectionAuthenticatedPrincipal(Collections.emptyMap(), AUTHORITIES)); } @Test public void constructorWhenAuthoritiesIsNullOrEmptyThenNoAuthorities() { Collection<? extends GrantedAuthority> authorities = new OAuth2IntrospectionAuthenticatedPrincipal(CLAIMS, null) .getAuthorities(); assertThat(authorities).isEmpty(); authorities = new OAuth2IntrospectionAuthenticatedPrincipal(CLAIMS, Collections.emptyList()).getAuthorities(); assertThat(authorities).isEmpty(); } @Test public void constructorWhenNameIsNullThenFallsbackToSubAttribute() { OAuth2AuthenticatedPrincipal principal = new OAuth2IntrospectionAuthenticatedPrincipal(null, CLAIMS, AUTHORITIES); assertThat(principal.getName()).isEqualTo(CLAIMS.get(SUB_CLAIM)); } @Test public void constructorWhenAttributesAuthoritiesProvidedThenCreated() { OAuth2IntrospectionAuthenticatedPrincipal principal = new OAuth2IntrospectionAuthenticatedPrincipal(CLAIMS, AUTHORITIES); assertThat(principal.getName()).isEqualTo(CLAIMS.get(SUB_CLAIM)); assertThat(principal.getAttributes()).isEqualTo(CLAIMS); assertThat(principal.getClaims()).isEqualTo(CLAIMS); assertThat(principal.isActive()).isEqualTo(ACTIVE_VALUE); assertThat(principal.getClientId()).isEqualTo(CLIENT_ID_VALUE); assertThat(principal.getUsername()).isEqualTo(USERNAME_VALUE); assertThat(principal.getTokenType()).isEqualTo(TOKEN_TYPE_VALUE); assertThat(principal.getExpiresAt().getEpochSecond()).isEqualTo(EXP_VALUE); assertThat(principal.getIssuedAt().getEpochSecond()).isEqualTo(IAT_VALUE); assertThat(principal.getNotBefore().getEpochSecond()).isEqualTo(NBF_VALUE); assertThat(principal.getSubject()).isEqualTo(SUB_VALUE); assertThat(principal.getAudience()).isEqualTo(AUD_VALUE); assertThat(principal.getIssuer().toString()).isEqualTo(ISS_VALUE); assertThat(principal.getId()).isEqualTo(JTI_VALUE); assertThat(principal.getAuthorities()).hasSize(1); assertThat(principal.getAuthorities().iterator().next().getAuthority()).isEqualTo(AUTHORITY); } @Test public void constructorWhenAllParametersProvidedAndValidThenCreated() { OAuth2IntrospectionAuthenticatedPrincipal principal = new OAuth2IntrospectionAuthenticatedPrincipal(SUBJECT, CLAIMS, AUTHORITIES); assertThat(principal.getName()).isEqualTo(SUBJECT); assertThat(principal.getAttributes()).isEqualTo(CLAIMS); assertThat(principal.getClaims()).isEqualTo(CLAIMS); assertThat(principal.isActive()).isEqualTo(ACTIVE_VALUE); assertThat(principal.getClientId()).isEqualTo(CLIENT_ID_VALUE); assertThat(principal.getUsername()).isEqualTo(USERNAME_VALUE); assertThat(principal.getTokenType()).isEqualTo(TOKEN_TYPE_VALUE); assertThat(principal.getExpiresAt().getEpochSecond()).isEqualTo(EXP_VALUE); assertThat(principal.getIssuedAt().getEpochSecond()).isEqualTo(IAT_VALUE); assertThat(principal.getNotBefore().getEpochSecond()).isEqualTo(NBF_VALUE); assertThat(principal.getSubject()).isEqualTo(SUB_VALUE); assertThat(principal.getAudience()).isEqualTo(AUD_VALUE); assertThat(principal.getIssuer().toString()).isEqualTo(ISS_VALUE); assertThat(principal.getId()).isEqualTo(JTI_VALUE); assertThat(principal.getAuthorities()).hasSize(1); assertThat(principal.getAuthorities().iterator().next().getAuthority()).isEqualTo(AUTHORITY); } @Test public void getNameWhenInConstructorThenReturns() { OAuth2AuthenticatedPrincipal principal = new OAuth2IntrospectionAuthenticatedPrincipal(SUB_VALUE, CLAIMS, AUTHORITIES); assertThat(principal.getName()).isEqualTo(SUB_VALUE); } @Test public void getAttributeWhenGivenKeyThenReturnsValue() { OAuth2AuthenticatedPrincipal principal = new OAuth2IntrospectionAuthenticatedPrincipal(CLAIMS, AUTHORITIES); assertHasEqualAttribute(principal, ACTIVE_CLAIM, ACTIVE_VALUE); assertHasEqualAttribute(principal, CLIENT_ID_CLAIM, CLIENT_ID_VALUE); assertHasEqualAttribute(principal, USERNAME_CLAIM, USERNAME_VALUE); assertHasEqualAttribute(principal, TOKEN_TYPE_CLAIM, TOKEN_TYPE_VALUE); assertHasEqualAttribute(principal, EXP_CLAIM, EXP_VALUE); assertHasEqualAttribute(principal, IAT_CLAIM, IAT_VALUE); assertHasEqualAttribute(principal, NBF_CLAIM, NBF_VALUE); assertHasEqualAttribute(principal, SUB_CLAIM, SUB_VALUE); assertHasEqualAttribute(principal, AUD_CLAIM, AUD_VALUE); assertHasEqualAttribute(principal, ISS_CLAIM, ISS_VALUE); assertHasEqualAttribute(principal, JTI_CLAIM, JTI_VALUE); } private void assertHasEqualAttribute(OAuth2AuthenticatedPrincipal principal, String name, Object expected) { Object value = principal.getAttribute(name); assertThat(value).isEqualTo(expected); } }
8,430
39.927184
114
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationConverterTests.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Arrays; import java.util.Collection; import org.junit.jupiter.api.Test; import org.springframework.core.convert.converter.Converter; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.TestJwts; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link JwtAuthenticationConverter} * * @author Josh Cummings * @author Evgeniy Cheban * @author Olivier Antoine */ public class JwtAuthenticationConverterTests { JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter(); @Test public void convertWhenDefaultGrantedAuthoritiesConverterSet() { Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt); Collection<GrantedAuthority> authorities = authentication.getAuthorities(); assertThat(authorities).containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"), new SimpleGrantedAuthority("SCOPE_message:write")); } @Test public void whenSettingNullGrantedAuthoritiesConverter() { assertThatIllegalArgumentException() .isThrownBy(() -> this.jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(null)) .withMessage("jwtGrantedAuthoritiesConverter cannot be null"); } @Test public void convertWithOverriddenGrantedAuthoritiesConverter() { Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build(); Converter<Jwt, Collection<GrantedAuthority>> grantedAuthoritiesConverter = (token) -> Arrays .asList(new SimpleGrantedAuthority("blah")); this.jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt); Collection<GrantedAuthority> authorities = authentication.getAuthorities(); assertThat(authorities).containsExactly(new SimpleGrantedAuthority("blah")); } @Test public void whenSettingNullPrincipalClaimName() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.jwtAuthenticationConverter.setPrincipalClaimName(null)) .withMessage("principalClaimName cannot be empty"); // @formatter:on } @Test public void whenSettingEmptyPrincipalClaimName() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.jwtAuthenticationConverter.setPrincipalClaimName("")) .withMessage("principalClaimName cannot be empty"); // @formatter:on } @Test public void whenSettingBlankPrincipalClaimName() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.jwtAuthenticationConverter.setPrincipalClaimName(" ")) .withMessage("principalClaimName cannot be empty"); // @formatter:on } @Test public void convertWhenPrincipalClaimNameSet() { this.jwtAuthenticationConverter.setPrincipalClaimName("user_id"); Jwt jwt = TestJwts.jwt().claim("user_id", "100").build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt); assertThat(authentication.getName()).isEqualTo("100"); } @Test public void convertWhenPrincipalClaimNameSetAndClaimValueIsNotString() { this.jwtAuthenticationConverter.setPrincipalClaimName("user_id"); Jwt jwt = TestJwts.jwt().claim("user_id", 100).build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt); assertThat(authentication.getName()).isEqualTo("100"); } }
4,531
38.068966
97
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationProviderTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.function.Predicate; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.core.convert.converter.Converter; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.AuthenticationException; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.jwt.BadJwtException; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.JwtException; import org.springframework.security.oauth2.jwt.TestJwts; import org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Tests for {@link JwtAuthenticationProvider} * * @author Josh Cummings * @author Jerome Wacongne ch4mp&#64;c4-soft.com */ @ExtendWith(MockitoExtension.class) public class JwtAuthenticationProviderTests { @Mock Converter<Jwt, AbstractAuthenticationToken> jwtAuthenticationConverter; @Mock JwtDecoder jwtDecoder; JwtAuthenticationProvider provider; @BeforeEach public void setup() { this.provider = new JwtAuthenticationProvider(this.jwtDecoder); this.provider.setJwtAuthenticationConverter(this.jwtAuthenticationConverter); } @Test public void authenticateWhenJwtDecodesThenAuthenticationHasAttributesContainedInJwt() { BearerTokenAuthenticationToken token = this.authentication(); Jwt jwt = TestJwts.jwt().claim("name", "value").build(); given(this.jwtDecoder.decode("token")).willReturn(jwt); given(this.jwtAuthenticationConverter.convert(jwt)).willReturn(new JwtAuthenticationToken(jwt)); JwtAuthenticationToken authentication = (JwtAuthenticationToken) this.provider.authenticate(token); assertThat(authentication.getTokenAttributes()).containsEntry("name", "value"); } @Test public void authenticateWhenJwtDecodeFailsThenRespondsWithInvalidToken() { BearerTokenAuthenticationToken token = this.authentication(); given(this.jwtDecoder.decode("token")).willThrow(BadJwtException.class); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate(token)) .matches(errorCode(BearerTokenErrorCodes.INVALID_TOKEN)); // @formatter:on } @Test public void authenticateWhenDecoderThrowsIncompatibleErrorMessageThenWrapsWithGenericOne() { BearerTokenAuthenticationToken token = this.authentication(); given(this.jwtDecoder.decode(token.getToken())).willThrow(new BadJwtException("with \"invalid\" chars")); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate(token)) .satisfies((ex) -> assertThat(ex).hasFieldOrPropertyWithValue("error.description", "Invalid token")); // @formatter:on } // gh-7785 @Test public void authenticateWhenDecoderFailsGenericallyThenThrowsGenericException() { BearerTokenAuthenticationToken token = this.authentication(); given(this.jwtDecoder.decode(token.getToken())).willThrow(new JwtException("no jwk set")); // @formatter:off assertThatExceptionOfType(AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate(token)) .isNotInstanceOf(OAuth2AuthenticationException.class); // @formatter:on } @Test public void authenticateWhenConverterReturnsAuthenticationThenProviderPropagatesIt() { BearerTokenAuthenticationToken token = this.authentication(); Jwt jwt = TestJwts.jwt().build(); JwtAuthenticationToken authentication = new JwtAuthenticationToken(jwt); given(this.jwtDecoder.decode(token.getToken())).willReturn(jwt); given(this.jwtAuthenticationConverter.convert(jwt)).willReturn(authentication); assertThat(this.provider.authenticate(token)).isEqualTo(authentication); } @Test public void authenticateWhenConverterDoesNotSetAuthenticationDetailsThenProviderSetsItWithTokenDetails() { BearerTokenAuthenticationToken token = this.authentication(); Object details = mock(Object.class); token.setDetails(details); Jwt jwt = TestJwts.jwt().build(); JwtAuthenticationToken authentication = new JwtAuthenticationToken(jwt); given(this.jwtDecoder.decode(token.getToken())).willReturn(jwt); given(this.jwtAuthenticationConverter.convert(jwt)).willReturn(authentication); // @formatter:off assertThat(this.provider.authenticate(token)) .isEqualTo(authentication).hasFieldOrPropertyWithValue("details", details); // @formatter:on } @Test public void authenticateWhenConverterSetsAuthenticationDetailsThenProviderDoesNotOverwriteIt() { BearerTokenAuthenticationToken token = this.authentication(); Object details = mock(Object.class); token.setDetails(details); Jwt jwt = TestJwts.jwt().build(); JwtAuthenticationToken authentication = new JwtAuthenticationToken(jwt); Object expectedDetails = "To be kept as is"; authentication.setDetails(expectedDetails); given(this.jwtDecoder.decode(token.getToken())).willReturn(jwt); given(this.jwtAuthenticationConverter.convert(jwt)).willReturn(authentication); // @formatter:off assertThat(this.provider.authenticate(token)) .isEqualTo(authentication).hasFieldOrPropertyWithValue("details", expectedDetails); // @formatter:on } @Test public void supportsWhenBearerTokenAuthenticationTokenThenReturnsTrue() { assertThat(this.provider.supports(BearerTokenAuthenticationToken.class)).isTrue(); } private BearerTokenAuthenticationToken authentication() { return new BearerTokenAuthenticationToken("token"); } private Predicate<? super Throwable> errorCode(String errorCode) { return (failed) -> ((OAuth2AuthenticationException) failed).getError().getErrorCode() == errorCode; } }
6,828
39.408284
107
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/TestBearerTokenAuthentications.java
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.time.Instant; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; /** * Test instances of {@link BearerTokenAuthentication} * * @author Josh Cummings */ public final class TestBearerTokenAuthentications { private TestBearerTokenAuthentications() { } public static BearerTokenAuthentication bearer() { Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("SCOPE_USER"); OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal( Collections.singletonMap("sub", "user"), authorities); OAuth2AccessToken token = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(), Instant.now().plusSeconds(86400), new HashSet<>(Arrays.asList("USER"))); return new BearerTokenAuthentication(principal, token, authorities); } }
1,940
37.058824
109
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/DelegatingJwtGrantedAuthoritiesConverterTests.java
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Collection; import java.util.LinkedHashSet; import org.junit.jupiter.api.Test; import org.springframework.core.convert.converter.Converter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.TestJwts; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for verifying {@link DelegatingJwtGrantedAuthoritiesConverter} * * @author Laszlo Stahorszki * @author Josh Cummings */ public class DelegatingJwtGrantedAuthoritiesConverterTests { @Test public void convertWhenNoConvertersThenNoAuthorities() { DelegatingJwtGrantedAuthoritiesConverter converter = new DelegatingJwtGrantedAuthoritiesConverter(); Jwt jwt = TestJwts.jwt().build(); assertThat(converter.convert(jwt)).isEmpty(); } @Test public void convertWhenConverterThenAuthorities() { DelegatingJwtGrantedAuthoritiesConverter converter = new DelegatingJwtGrantedAuthoritiesConverter( ((jwt) -> AuthorityUtils.createAuthorityList("one"))); Jwt jwt = TestJwts.jwt().build(); Collection<GrantedAuthority> authorities = converter.convert(jwt); assertThat(authorityListToOrderedSet(authorities)).containsExactly("one"); } @Test public void convertWhenMultipleConvertersThenDuplicatesRemoved() { Converter<Jwt, Collection<GrantedAuthority>> one = (jwt) -> AuthorityUtils.createAuthorityList("one", "two"); Converter<Jwt, Collection<GrantedAuthority>> two = (jwt) -> AuthorityUtils.createAuthorityList("one", "three"); DelegatingJwtGrantedAuthoritiesConverter composite = new DelegatingJwtGrantedAuthoritiesConverter(one, two); Jwt jwt = TestJwts.jwt().build(); Collection<GrantedAuthority> authorities = composite.convert(jwt); assertThat(authorityListToOrderedSet(authorities)).containsExactly("one", "two", "three"); } @Test public void constructorWhenAuthoritiesConverterIsNullThenIllegalArgumentException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> new DelegatingJwtGrantedAuthoritiesConverter( (Collection<Converter<Jwt, Collection<GrantedAuthority>>>) null)); } private Collection<String> authorityListToOrderedSet(Collection<GrantedAuthority> grantedAuthorities) { Collection<String> authorities = new LinkedHashSet<>(grantedAuthorities.size()); for (GrantedAuthority authority : grantedAuthorities) { authorities.add(authority.getAuthority()); } return authorities; } }
3,325
39.072289
113
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtBearerTokenAuthenticationConverterTests.java
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Arrays; import org.junit.jupiter.api.Test; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JwtBearerTokenAuthenticationConverter} * * @author Josh Cummings */ public class JwtBearerTokenAuthenticationConverterTests { private final JwtBearerTokenAuthenticationConverter converter = new JwtBearerTokenAuthenticationConverter(); @Test public void convertWhenJwtThenBearerTokenAuthentication() { // @formatter:off Jwt jwt = Jwt.withTokenValue("token-value") .claim("claim", "value") .header("header", "value") .build(); // @formatter:on AbstractAuthenticationToken token = this.converter.convert(jwt); assertThat(token).isInstanceOf(BearerTokenAuthentication.class); BearerTokenAuthentication bearerToken = (BearerTokenAuthentication) token; assertThat(bearerToken.getToken().getTokenValue()).isEqualTo("token-value"); assertThat(bearerToken.getTokenAttributes()).containsOnlyKeys("claim"); assertThat(bearerToken.getAuthorities()).isEmpty(); } @Test public void convertWhenJwtWithScopeAttributeThenBearerTokenAuthentication() { // @formatter:off Jwt jwt = Jwt.withTokenValue("token-value") .claim("scope", "message:read message:write") .header("header", "value") .build(); // @formatter:on AbstractAuthenticationToken token = this.converter.convert(jwt); assertThat(token).isInstanceOf(BearerTokenAuthentication.class); BearerTokenAuthentication bearerToken = (BearerTokenAuthentication) token; assertThat(bearerToken.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"), new SimpleGrantedAuthority("SCOPE_message:write")); } @Test public void convertWhenJwtWithScpAttributeThenBearerTokenAuthentication() { // @formatter:off Jwt jwt = Jwt.withTokenValue("token-value") .claim("scp", Arrays.asList("message:read", "message:write")) .header("header", "value") .build(); // @formatter:on AbstractAuthenticationToken token = this.converter.convert(jwt); assertThat(token).isInstanceOf(BearerTokenAuthentication.class); BearerTokenAuthentication bearerToken = (BearerTokenAuthentication) token; assertThat(bearerToken.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"), new SimpleGrantedAuthority("SCOPE_message:write")); } }
3,251
37.258824
109
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolverTests.java
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSHeader; import com.nimbusds.jose.JWSObject; import com.nimbusds.jose.Payload; import com.nimbusds.jose.crypto.RSASSASigner; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.PlainJWT; import net.minidev.json.JSONObject; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import org.springframework.security.authentication.ReactiveAuthenticationManager; import org.springframework.security.authentication.ReactiveAuthenticationManagerResolver; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.jose.TestKeys; import org.springframework.security.oauth2.jwt.JwtClaimNames; import org.springframework.security.oauth2.server.resource.authentication.JwtIssuerReactiveAuthenticationManagerResolver.TrustedIssuerJwtAuthenticationManagerResolver; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.mock; import static org.mockito.BDDMockito.verify; /** * Tests for {@link JwtIssuerReactiveAuthenticationManagerResolver} */ public class JwtIssuerReactiveAuthenticationManagerResolverTests { // @formatter:off private static final String DEFAULT_RESPONSE_TEMPLATE = "{\n" + " \"issuer\": \"%s\", \n" + " \"jwks_uri\": \"%s/.well-known/jwks.json\" \n" + "}"; // @formatter:on private static final String JWK_SET = "{\"keys\":[{\"kty\":\"RSA\",\"e\":\"AQAB\",\"use\":\"sig\",\"kid\":\"one\",\"n\":\"3FlqJr5TRskIQIgdE3Dd7D9lboWdcTUT8a-fJR7MAvQm7XXNoYkm3v7MQL1NYtDvL2l8CAnc0WdSTINU6IRvc5Kqo2Q4csNX9SHOmEfzoROjQqahEcve1jBXluoCXdYuYpx4_1tfRgG6ii4Uhxh6iI8qNMJQX-fLfqhbfYfxBQVRPywBkAbIP4x1EAsbC6FSNmkhCxiMNqEgxaIpY8C2kJdJ_ZIV-WW4noDdzpKqHcwmB8FsrumlVY_DNVvUSDIipiq9PbP4H99TXN1o746oRaNa07rq1hoCgMSSy-85SagCoxlmyE-D-of9SsMY8Ol9t0rdzpobBuhyJ_o5dfvjKw\"}]}"; private String jwt = jwt("iss", "trusted"); private String evil = jwt("iss", "\""); private String noIssuer = jwt("sub", "sub"); @Test public void resolveWhenUsingTrustedIssuerThenReturnsAuthenticationManager() throws Exception { try (MockWebServer server = new MockWebServer()) { String issuer = server.url("").toString(); server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer))); server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") .setBody(JWK_SET)); server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") .setBody(JWK_SET)); JWSObject jws = new JWSObject(new JWSHeader(JWSAlgorithm.RS256), new Payload(new JSONObject(Collections.singletonMap(JwtClaimNames.ISS, issuer)))); jws.sign(new RSASSASigner(TestKeys.DEFAULT_PRIVATE_KEY)); JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver( issuer); ReactiveAuthenticationManager authenticationManager = authenticationManagerResolver.resolve(null).block(); assertThat(authenticationManager).isNotNull(); BearerTokenAuthenticationToken token = withBearerToken(jws.serialize()); Authentication authentication = authenticationManager.authenticate(token).block(); assertThat(authentication).isNotNull(); assertThat(authentication.isAuthenticated()).isTrue(); } } // gh-10444 @Test public void resolveWhednUsingTrustedIssuerThenReturnsAuthenticationManager() throws Exception { try (MockWebServer server = new MockWebServer()) { String issuer = server.url("").toString(); // @formatter:off server.enqueue(new MockResponse().setResponseCode(500).setHeader("Content-Type", "application/json") .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer))); server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer))); server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") .setBody(JWK_SET)); // @formatter:on JWSObject jws = new JWSObject(new JWSHeader(JWSAlgorithm.RS256), new Payload(new JSONObject(Collections.singletonMap(JwtClaimNames.ISS, issuer)))); jws.sign(new RSASSASigner(TestKeys.DEFAULT_PRIVATE_KEY)); JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver( issuer); ReactiveAuthenticationManager authenticationManager = authenticationManagerResolver.resolve(null).block(); assertThat(authenticationManager).isNotNull(); Authentication token = withBearerToken(jws.serialize()); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> authenticationManager.authenticate(token).block()); Authentication authentication = authenticationManager.authenticate(token).block(); assertThat(authentication.isAuthenticated()).isTrue(); } } @Test public void resolveWhenUsingSameIssuerThenReturnsSameAuthenticationManager() throws Exception { try (MockWebServer server = new MockWebServer()) { String issuer = server.url("").toString(); server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer))); server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") .setBody(JWK_SET)); TrustedIssuerJwtAuthenticationManagerResolver resolver = new TrustedIssuerJwtAuthenticationManagerResolver( (iss) -> iss.equals(issuer)); ReactiveAuthenticationManager authenticationManager = resolver.resolve(issuer).block(); ReactiveAuthenticationManager cachedAuthenticationManager = resolver.resolve(issuer).block(); assertThat(authenticationManager).isSameAs(cachedAuthenticationManager); } } @Test public void resolveWhenUsingUntrustedIssuerThenException() { JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver( "other", "issuers"); Authentication token = withBearerToken(this.jwt); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> authenticationManagerResolver.resolve(null) .flatMap((authenticationManager) -> authenticationManager.authenticate(token)) .block()) .withMessageContaining("Invalid issuer"); // @formatter:on } @Test public void resolveWhenUsingCustomIssuerAuthenticationManagerResolverThenUses() { Authentication token = withBearerToken(this.jwt); ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class); given(authenticationManager.authenticate(token)).willReturn(Mono.empty()); JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver( (issuer) -> Mono.just(authenticationManager)); authenticationManagerResolver.resolve(null).flatMap((manager) -> manager.authenticate(token)).block(); verify(authenticationManager).authenticate(any()); } @Test public void resolveWhenUsingExternalSourceThenRespondsToChanges() { Authentication token = withBearerToken(this.jwt); Map<String, ReactiveAuthenticationManager> authenticationManagers = new HashMap<>(); JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver( (issuer) -> Mono.justOrEmpty(authenticationManagers.get(issuer))); assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> authenticationManagerResolver.resolve(null) .flatMap((manager) -> manager.authenticate(token)).block()) .withMessageContaining("Invalid issuer"); ReactiveAuthenticationManager authenticationManager = mock(ReactiveAuthenticationManager.class); given(authenticationManager.authenticate(token)).willReturn(Mono.empty()); authenticationManagers.put("trusted", authenticationManager); authenticationManagerResolver.resolve(null).flatMap((manager) -> manager.authenticate(token)).block(); verify(authenticationManager).authenticate(token); authenticationManagers.clear(); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> authenticationManagerResolver.resolve(null) .flatMap((manager) -> manager.authenticate(token)) .block()) .withMessageContaining("Invalid issuer"); // @formatter:on } @Test public void resolveWhenBearerTokenMalformedThenException() { JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver( "trusted"); Authentication token = withBearerToken("jwt"); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> authenticationManagerResolver.resolve(null) .flatMap((manager) -> manager.authenticate(token)) .block()) .withMessageNotContaining("Invalid issuer"); // @formatter:on } @Test public void resolveWhenBearerTokenNoIssuerThenException() { JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver( "trusted"); Authentication token = withBearerToken(this.noIssuer); assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> authenticationManagerResolver.resolve(null) .flatMap((manager) -> manager.authenticate(token)).block()) .withMessageContaining("Missing issuer"); } @Test public void resolveWhenBearerTokenEvilThenGenericException() { JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver( "trusted"); Authentication token = withBearerToken(this.evil); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> authenticationManagerResolver.resolve(null) .flatMap((manager) -> manager.authenticate(token)) .block()) .withMessage("Invalid token"); // @formatter:on } @Test public void constructorWhenNullOrEmptyIssuersThenException() { assertThatIllegalArgumentException() .isThrownBy(() -> new JwtIssuerReactiveAuthenticationManagerResolver((Collection) null)); assertThatIllegalArgumentException() .isThrownBy(() -> new JwtIssuerReactiveAuthenticationManagerResolver(Collections.emptyList())); } @Test public void constructorWhenNullAuthenticationManagerResolverThenException() { assertThatIllegalArgumentException().isThrownBy( () -> new JwtIssuerReactiveAuthenticationManagerResolver((ReactiveAuthenticationManagerResolver) null)); } private String jwt(String claim, String value) { PlainJWT jwt = new PlainJWT(new JWTClaimsSet.Builder().claim(claim, value).build()); return jwt.serialize(); } private BearerTokenAuthenticationToken withBearerToken(String token) { return new BearerTokenAuthenticationToken(token); } }
12,367
47.692913
472
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManagerTests.java
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import reactor.core.publisher.Mono; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.jwt.BadJwtException; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtException; import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder; import org.springframework.security.oauth2.jwt.TestJwts; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; /** * @author Rob Winch * @since 5.1 */ @ExtendWith(MockitoExtension.class) public class JwtReactiveAuthenticationManagerTests { @Mock private ReactiveJwtDecoder jwtDecoder; private JwtReactiveAuthenticationManager manager; private Jwt jwt; @BeforeEach public void setup() { this.manager = new JwtReactiveAuthenticationManager(this.jwtDecoder); // @formatter:off this.jwt = TestJwts.jwt() .claim("scope", "message:read message:write") .build(); // @formatter:on } @Test public void constructorWhenJwtDecoderNullThenIllegalArgumentException() { this.jwtDecoder = null; // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> new JwtReactiveAuthenticationManager(this.jwtDecoder)); // @formatter:on } @Test public void authenticateWhenWrongTypeThenEmpty() { TestingAuthenticationToken token = new TestingAuthenticationToken("foo", "bar"); assertThat(this.manager.authenticate(token).block()).isNull(); } @Test public void authenticateWhenEmptyJwtThenEmpty() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); given(this.jwtDecoder.decode(token.getToken())).willReturn(Mono.empty()); assertThat(this.manager.authenticate(token).block()).isNull(); } @Test public void authenticateWhenJwtExceptionThenOAuth2AuthenticationException() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); given(this.jwtDecoder.decode(any())).willReturn(Mono.error(new BadJwtException("Oops"))); assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.manager.authenticate(token).block()); } // gh-7549 @Test public void authenticateWhenDecoderThrowsIncompatibleErrorMessageThenWrapsWithGenericOne() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); given(this.jwtDecoder.decode(token.getToken())).willThrow(new BadJwtException("with \"invalid\" chars")); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.manager.authenticate(token).block()) .satisfies((ex) -> assertThat(ex) .hasFieldOrPropertyWithValue("error.description", "Invalid token") ); // @formatter:on } // gh-7785 @Test public void authenticateWhenDecoderFailsGenericallyThenThrowsGenericException() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); given(this.jwtDecoder.decode(token.getToken())).willThrow(new JwtException("no jwk set")); // @formatter:off assertThatExceptionOfType(AuthenticationException.class) .isThrownBy(() -> this.manager.authenticate(token).block()) .isNotInstanceOf(OAuth2AuthenticationException.class); // @formatter:on } @Test public void authenticateWhenNotJwtExceptionThenPropagates() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); given(this.jwtDecoder.decode(any())).willReturn(Mono.error(new RuntimeException("Oops"))); // @formatter:off assertThatExceptionOfType(RuntimeException.class) .isThrownBy(() -> this.manager.authenticate(token).block()); // @formatter:on } @Test public void authenticateWhenJwtThenSuccess() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token-1"); given(this.jwtDecoder.decode(token.getToken())).willReturn(Mono.just(this.jwt)); Authentication authentication = this.manager.authenticate(token).block(); assertThat(authentication).isNotNull(); assertThat(authentication.isAuthenticated()).isTrue(); // @formatter:off assertThat(authentication.getAuthorities()) .extracting(GrantedAuthority::getAuthority) .containsOnly("SCOPE_message:read", "SCOPE_message:write"); // @formatter:on } }
5,675
37.351351
107
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManagerTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.net.URL; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.Map; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames; import org.springframework.security.oauth2.core.TestOAuth2AuthenticatedPrincipals; import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal; import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionException; import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenAuthenticationConverter; import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Tests for {@link OpaqueTokenReactiveAuthenticationManager} * * @author Josh Cummings */ public class OpaqueTokenReactiveAuthenticationManagerTests { @Test public void authenticateWhenActiveTokenThenOk() throws Exception { OAuth2AuthenticatedPrincipal authority = TestOAuth2AuthenticatedPrincipals .active((attributes) -> attributes.put("extension_field", "twenty-seven")); ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class); given(introspector.introspect(any())).willReturn(Mono.just(authority)); OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector); Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token")).block(); assertThat(result.getPrincipal()).isInstanceOf(OAuth2IntrospectionAuthenticatedPrincipal.class); Map<String, Object> attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes(); // @formatter:off assertThat(attributes) .isNotNull() .containsEntry(OAuth2TokenIntrospectionClaimNames.ACTIVE, true) .containsEntry(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("https://protected.example.net/resource")) .containsEntry(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, "l238j323ds-23ij4") .containsEntry(OAuth2TokenIntrospectionClaimNames.EXP, Instant.ofEpochSecond(1419356238)) .containsEntry(OAuth2TokenIntrospectionClaimNames.ISS, new URL("https://server.example.com/")) .containsEntry(OAuth2TokenIntrospectionClaimNames.NBF, Instant.ofEpochSecond(29348723984L)) .containsEntry(OAuth2TokenIntrospectionClaimNames.SCOPE, Arrays.asList("read", "write", "dolphin")) .containsEntry(OAuth2TokenIntrospectionClaimNames.SUB, "Z5O3upPC88QrAjx00dis") .containsEntry(OAuth2TokenIntrospectionClaimNames.USERNAME, "jdoe") .containsEntry("extension_field", "twenty-seven"); assertThat(result.getAuthorities()) .extracting("authority") .containsExactly("SCOPE_read", "SCOPE_write", "SCOPE_dolphin"); // @formatter:on } @Test public void authenticateWhenMissingScopeAttributeThenNoAuthorities() { OAuth2AuthenticatedPrincipal authority = new OAuth2IntrospectionAuthenticatedPrincipal( Collections.singletonMap("claim", "value"), null); ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class); given(introspector.introspect(any())).willReturn(Mono.just(authority)); OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector); Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token")).block(); assertThat(result.getPrincipal()).isInstanceOf(OAuth2IntrospectionAuthenticatedPrincipal.class); Map<String, Object> attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes(); assertThat(attributes).isNotNull().doesNotContainKey(OAuth2TokenIntrospectionClaimNames.SCOPE); assertThat(result.getAuthorities()).isEmpty(); } @Test public void authenticateWhenIntrospectionEndpointThrowsExceptionThenInvalidToken() { ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class); given(introspector.introspect(any())) .willReturn(Mono.error(new OAuth2IntrospectionException("with \"invalid\" chars"))); OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector); assertThatExceptionOfType(AuthenticationServiceException.class) .isThrownBy(() -> provider.authenticate(new BearerTokenAuthenticationToken("token")).block()); } @Test public void constructorWhenIntrospectionClientIsNullThenIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> new OpaqueTokenReactiveAuthenticationManager(null)); // @formatter:on } @Test public void setAuthenticationConverterWhenNullThenThrowsIllegalArgumentException() { ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class); OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector); // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> provider.setAuthenticationConverter(null)) .withMessage("authenticationConverter cannot be null"); // @formatter:on } @Test public void authenticateWhenCustomAuthenticationConverterThenUses() { ReactiveOpaqueTokenIntrospector introspector = mock(ReactiveOpaqueTokenIntrospector.class); OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals.active(); given(introspector.introspect(any())).willReturn(Mono.just(principal)); OpaqueTokenReactiveAuthenticationManager provider = new OpaqueTokenReactiveAuthenticationManager(introspector); ReactiveOpaqueTokenAuthenticationConverter authenticationConverter = mock( ReactiveOpaqueTokenAuthenticationConverter.class); given(authenticationConverter.convert(any(), any(OAuth2AuthenticatedPrincipal.class))) .willReturn(Mono.just(new TestingAuthenticationToken(principal, null, Collections.emptyList()))); provider.setAuthenticationConverter(authenticationConverter); Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token")).block(); assertThat(result).isNotNull(); verify(introspector).introspect("token"); verify(authenticationConverter).convert("token", principal); verifyNoMoreInteractions(introspector, authenticationConverter); } }
7,809
51.416107
116
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtGrantedAuthoritiesConverterTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import org.junit.jupiter.api.Test; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.TestJwts; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link JwtGrantedAuthoritiesConverter} * * @author Eric Deandrea * @since 5.2 */ public class JwtGrantedAuthoritiesConverterTests { @Test public void setAuthorityPrefixWithNullThenException() { JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); assertThatIllegalArgumentException().isThrownBy(() -> jwtGrantedAuthoritiesConverter.setAuthorityPrefix(null)); } @Test public void convertWhenTokenHasScopeAttributeThenTranslatedToAuthorities() { // @formatter:off Jwt jwt = TestJwts.jwt() .claim("scope", "message:read message:write") .build(); // @formatter:on JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt); assertThat(authorities).containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"), new SimpleGrantedAuthority("SCOPE_message:write")); } @Test public void convertWithCustomAuthorityPrefixWhenTokenHasScopeAttributeThenTranslatedToAuthorities() { // @formatter:off Jwt jwt = TestJwts.jwt() .claim("scope", "message:read message:write") .build(); // @formatter:on JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); jwtGrantedAuthoritiesConverter.setAuthorityPrefix("ROLE_"); Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt); assertThat(authorities).containsExactly(new SimpleGrantedAuthority("ROLE_message:read"), new SimpleGrantedAuthority("ROLE_message:write")); } @Test public void convertWithBlankAsCustomAuthorityPrefixWhenTokenHasScopeAttributeThenTranslatedToAuthorities() { // @formatter:off Jwt jwt = TestJwts.jwt() .claim("scope", "message:read message:write") .build(); // @formatter:on JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); jwtGrantedAuthoritiesConverter.setAuthorityPrefix(""); Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt); assertThat(authorities).containsExactly(new SimpleGrantedAuthority("message:read"), new SimpleGrantedAuthority("message:write")); } @Test public void convertWhenTokenHasEmptyScopeAttributeThenTranslatedToNoAuthorities() { // @formatter:off Jwt jwt = TestJwts.jwt() .claim("scope", "") .build(); // @formatter:on JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt); assertThat(authorities).isEmpty(); } @Test public void convertWhenTokenHasScpAttributeThenTranslatedToAuthorities() { // @formatter:off Jwt jwt = TestJwts.jwt() .claim("scp", Arrays.asList("message:read", "message:write")) .build(); // @formatter:on JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt); assertThat(authorities).containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"), new SimpleGrantedAuthority("SCOPE_message:write")); } @Test public void convertWithCustomAuthorityPrefixWhenTokenHasScpAttributeThenTranslatedToAuthorities() { // @formatter:off Jwt jwt = TestJwts.jwt() .claim("scp", Arrays.asList("message:read", "message:write")) .build(); // @formatter:on JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); jwtGrantedAuthoritiesConverter.setAuthorityPrefix("ROLE_"); Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt); assertThat(authorities).containsExactly(new SimpleGrantedAuthority("ROLE_message:read"), new SimpleGrantedAuthority("ROLE_message:write")); } @Test public void convertWithBlankAsCustomAuthorityPrefixWhenTokenHasScpAttributeThenTranslatedToAuthorities() { // @formatter:off Jwt jwt = TestJwts.jwt() .claim("scp", "message:read message:write") .build(); // @formatter:on JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); jwtGrantedAuthoritiesConverter.setAuthorityPrefix(""); Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt); assertThat(authorities).containsExactly(new SimpleGrantedAuthority("message:read"), new SimpleGrantedAuthority("message:write")); } @Test public void convertWhenTokenHasEmptyScpAttributeThenTranslatedToNoAuthorities() { // @formatter:off Jwt jwt = TestJwts.jwt() .claim("scp", Collections.emptyList()) .build(); // @formatter:on JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt); assertThat(authorities).isEmpty(); } @Test public void convertWhenTokenHasBothScopeAndScpThenScopeAttributeIsTranslatedToAuthorities() { // @formatter:off Jwt jwt = TestJwts.jwt() .claim("scp", Arrays.asList("message:read", "message:write")) .claim("scope", "missive:read missive:write") .build(); // @formatter:on JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt); assertThat(authorities).containsExactly(new SimpleGrantedAuthority("SCOPE_missive:read"), new SimpleGrantedAuthority("SCOPE_missive:write")); } @Test public void convertWhenTokenHasEmptyScopeAndNonEmptyScpThenScopeAttributeIsTranslatedToNoAuthorities() { // @formatter:off Jwt jwt = TestJwts.jwt() .claim("scp", Arrays.asList("message:read", "message:write")) .claim("scope", "") .build(); // @formatter:on JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt); assertThat(authorities).isEmpty(); } @Test public void convertWhenTokenHasEmptyScopeAndEmptyScpAttributeThenTranslatesToNoAuthorities() { // @formatter:off Jwt jwt = TestJwts.jwt() .claim("scp", Collections.emptyList()) .claim("scope", Collections.emptyList()) .build(); // @formatter:on JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt); assertThat(authorities).isEmpty(); } @Test public void convertWhenTokenHasNoScopeAndNoScpAttributeThenTranslatesToNoAuthorities() { // @formatter:off Jwt jwt = TestJwts.jwt() .claim("roles", Arrays.asList("message:read", "message:write")) .build(); // @formatter:on JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt); assertThat(authorities).isEmpty(); } @Test public void convertWhenTokenHasUnsupportedTypeForScopeThenTranslatesToNoAuthorities() { // @formatter:off Jwt jwt = TestJwts.jwt() .claim("scope", new String[] { "message:read", "message:write" }) .build(); // @formatter:on JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt); assertThat(authorities).isEmpty(); } @Test public void convertWhenTokenHasCustomClaimNameThenCustomClaimNameAttributeIsTranslatedToAuthorities() { // @formatter:off Jwt jwt = TestJwts.jwt() .claim("roles", Arrays.asList("message:read", "message:write")) .claim("scope", "missive:read missive:write") .build(); // @formatter:on JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("roles"); Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt); assertThat(authorities).containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"), new SimpleGrantedAuthority("SCOPE_message:write")); } @Test public void convertWhenTokenHasEmptyCustomClaimNameThenCustomClaimNameAttributeIsTranslatedToNoAuthorities() { // @formatter:off Jwt jwt = TestJwts.jwt() .claim("roles", Collections.emptyList()) .claim("scope", "missive:read missive:write") .build(); // @formatter:on JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("roles"); Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt); assertThat(authorities).isEmpty(); } @Test public void convertWhenTokenHasNoCustomClaimNameThenCustomClaimNameAttributeIsTranslatedToNoAuthorities() { // @formatter:off Jwt jwt = TestJwts.jwt() .claim("scope", "missive:read missive:write") .build(); // @formatter:on JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("roles"); Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt); assertThat(authorities).isEmpty(); } @Test public void convertWithCustomAuthoritiesSplitRegexWhenTokenHasScopeAttributeThenTranslatedToAuthorities() { // @formatter:off Jwt jwt = TestJwts.jwt() .claim("scope", "message:read,message:write") .build(); // @formatter:on JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); jwtGrantedAuthoritiesConverter.setAuthoritiesClaimDelimiter(","); Collection<GrantedAuthority> authorities = jwtGrantedAuthoritiesConverter.convert(jwt); assertThat(authorities).containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"), new SimpleGrantedAuthority("SCOPE_message:write")); } }
11,397
40.59854
113
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/BearerTokenAuthenticationTokenTests.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link BearerTokenAuthenticationToken} * * @author Josh Cummings */ public class BearerTokenAuthenticationTokenTests { @Test public void constructorWhenTokenIsNullThenThrowsException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> new BearerTokenAuthenticationToken(null)) .withMessageContaining("token cannot be empty"); // @formatter:on } @Test public void constructorWhenTokenIsEmptyThenThrowsException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> new BearerTokenAuthenticationToken("")) .withMessageContaining("token cannot be empty"); // @formatter:on } @Test public void constructorWhenTokenHasValueThenConstructedCorrectly() { BearerTokenAuthenticationToken token = new BearerTokenAuthenticationToken("token"); assertThat(token.getToken()).isEqualTo("token"); assertThat(token.getPrincipal()).isEqualTo("token"); assertThat(token.getCredentials()).isEqualTo("token"); } }
1,886
31.534483
85
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtAuthenticationConverterTests.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Collection; import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; import org.springframework.core.convert.converter.Converter; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.TestJwts; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ReactiveJwtAuthenticationConverter} * * @author Eric Deandrea * @author Marcus Kainth * @since 5.2 */ public class ReactiveJwtAuthenticationConverterTests { ReactiveJwtAuthenticationConverter jwtAuthenticationConverter = new ReactiveJwtAuthenticationConverter(); @Test public void convertWhenDefaultGrantedAuthoritiesConverterSet() { Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block(); Collection<GrantedAuthority> authorities = authentication.getAuthorities(); assertThat(authorities).containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"), new SimpleGrantedAuthority("SCOPE_message:write")); } @Test public void whenSettingNullGrantedAuthoritiesConverter() { assertThatIllegalArgumentException() .isThrownBy(() -> this.jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(null)) .withMessage("jwtGrantedAuthoritiesConverter cannot be null"); } @Test public void convertWithOverriddenGrantedAuthoritiesConverter() { Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build(); Converter<Jwt, Flux<GrantedAuthority>> grantedAuthoritiesConverter = (token) -> Flux .just(new SimpleGrantedAuthority("blah")); this.jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block(); Collection<GrantedAuthority> authorities = authentication.getAuthorities(); assertThat(authorities).containsExactly(new SimpleGrantedAuthority("blah")); } @Test public void whenSettingNullPrincipalClaimName() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.jwtAuthenticationConverter.setPrincipalClaimName(null)) .withMessage("principalClaimName cannot be empty"); // @formatter:on } @Test public void whenSettingEmptyPrincipalClaimName() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.jwtAuthenticationConverter.setPrincipalClaimName("")) .withMessage("principalClaimName cannot be empty"); // @formatter:on } @Test public void whenSettingBlankPrincipalClaimName() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.jwtAuthenticationConverter.setPrincipalClaimName(" ")) .withMessage("principalClaimName cannot be empty"); // @formatter:on } @Test public void convertWhenPrincipalClaimNameSet() { this.jwtAuthenticationConverter.setPrincipalClaimName("user_id"); Jwt jwt = TestJwts.jwt().claim("user_id", "100").build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block(); assertThat(authentication.getName()).isEqualTo("100"); } @Test public void convertWhenPrincipalClaimNameSetAndClaimValueIsNotString() { this.jwtAuthenticationConverter.setPrincipalClaimName("user_id"); Jwt jwt = TestJwts.jwt().claim("user_id", 100).build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block(); assertThat(authentication.getName()).isEqualTo("100"); } }
4,582
38.508621
106
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationTokenTests.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Collection; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.oauth2.jose.jws.JwsAlgorithms; import org.springframework.security.oauth2.jwt.Jwt; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link JwtAuthenticationToken} * * @author Josh Cummings */ @ExtendWith(MockitoExtension.class) public class JwtAuthenticationTokenTests { @Test public void getNameWhenJwtHasSubjectThenReturnsSubject() { Jwt jwt = builder().subject("Carl").build(); JwtAuthenticationToken token = new JwtAuthenticationToken(jwt); assertThat(token.getName()).isEqualTo("Carl"); } @Test public void getNameWhenJwtHasNoSubjectThenReturnsNull() { Jwt jwt = builder().claim("claim", "value").build(); JwtAuthenticationToken token = new JwtAuthenticationToken(jwt); assertThat(token.getName()).isNull(); } @Test public void constructorWhenJwtIsNullThenThrowsException() { assertThatIllegalArgumentException().isThrownBy(() -> new JwtAuthenticationToken(null)) .withMessageContaining("token cannot be null"); } @Test public void constructorWhenUsingCorrectParametersThenConstructedCorrectly() { Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("test"); Jwt jwt = builder().claim("claim", "value").build(); JwtAuthenticationToken token = new JwtAuthenticationToken(jwt, authorities); assertThat(token.getAuthorities()).isEqualTo(authorities); assertThat(token.getPrincipal()).isEqualTo(jwt); assertThat(token.getCredentials()).isEqualTo(jwt); assertThat(token.getToken()).isEqualTo(jwt); assertThat(token.getTokenAttributes()).isEqualTo(jwt.getClaims()); assertThat(token.isAuthenticated()).isTrue(); } @Test public void constructorWhenUsingOnlyJwtThenConstructedCorrectly() { Jwt jwt = builder().claim("claim", "value").build(); JwtAuthenticationToken token = new JwtAuthenticationToken(jwt); assertThat(token.getAuthorities()).isEmpty(); assertThat(token.getPrincipal()).isEqualTo(jwt); assertThat(token.getCredentials()).isEqualTo(jwt); assertThat(token.getToken()).isEqualTo(jwt); assertThat(token.getTokenAttributes()).isEqualTo(jwt.getClaims()); assertThat(token.isAuthenticated()).isFalse(); } @Test public void getNameWhenConstructedWithJwtThenReturnsSubject() { Jwt jwt = builder().subject("Hayden").build(); JwtAuthenticationToken token = new JwtAuthenticationToken(jwt); assertThat(token.getName()).isEqualTo("Hayden"); } @Test public void getNameWhenConstructedWithJwtAndAuthoritiesThenReturnsSubject() { Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("test"); Jwt jwt = builder().subject("Hayden").build(); JwtAuthenticationToken token = new JwtAuthenticationToken(jwt, authorities); assertThat(token.getName()).isEqualTo("Hayden"); } @Test public void getNameWhenConstructedWithNameThenReturnsProvidedName() { Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("test"); Jwt jwt = builder().claim("claim", "value").build(); JwtAuthenticationToken token = new JwtAuthenticationToken(jwt, authorities, "Hayden"); assertThat(token.getName()).isEqualTo("Hayden"); } @Test public void getNameWhenConstructedWithNoSubjectThenReturnsNull() { Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("test"); Jwt jwt = builder().claim("claim", "value").build(); assertThat(new JwtAuthenticationToken(jwt, authorities, null).getName()).isNull(); assertThat(new JwtAuthenticationToken(jwt, authorities).getName()).isNull(); assertThat(new JwtAuthenticationToken(jwt).getName()).isNull(); } private Jwt.Builder builder() { return Jwt.withTokenValue("token").header("alg", JwsAlgorithms.RS256); } }
4,784
37.902439
89
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/BearerTokenAuthenticationTests.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.net.URL; import java.time.Instant; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import net.minidev.json.JSONObject; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link BearerTokenAuthentication} * * @author Josh Cummings */ public class BearerTokenAuthenticationTests { private final OAuth2AccessToken token = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token", Instant.now(), Instant.now().plusSeconds(3600)); private final String name = "sub"; private Map<String, Object> attributesMap = new HashMap<>(); private DefaultOAuth2AuthenticatedPrincipal principal; private final Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("USER"); @BeforeEach public void setUp() { this.attributesMap.put(OAuth2TokenIntrospectionClaimNames.SUB, this.name); this.attributesMap.put(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, "client_id"); this.attributesMap.put(OAuth2TokenIntrospectionClaimNames.USERNAME, "username"); this.principal = new DefaultOAuth2AuthenticatedPrincipal(this.attributesMap, null); } @Test public void getNameWhenConfiguredInConstructorThenReturnsName() { OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(this.name, this.attributesMap, this.authorities); BearerTokenAuthentication authenticated = new BearerTokenAuthentication(principal, this.token, this.authorities); assertThat(authenticated.getName()).isEqualTo(this.name); } @Test public void getNameWhenHasNoSubjectThenReturnsNull() { OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal( Collections.singletonMap("claim", "value"), null); BearerTokenAuthentication authenticated = new BearerTokenAuthentication(principal, this.token, null); assertThat(authenticated.getName()).isNull(); } @Test public void getNameWhenTokenHasUsernameThenReturnsUsernameAttribute() { BearerTokenAuthentication authenticated = new BearerTokenAuthentication(this.principal, this.token, null); // @formatter:off assertThat(authenticated.getName()) .isEqualTo(this.principal.getAttribute(OAuth2TokenIntrospectionClaimNames.SUB)); // @formatter:on } @Test public void constructorWhenTokenIsNullThenThrowsException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> new BearerTokenAuthentication(this.principal, null, null)) .withMessageContaining("token cannot be null"); // @formatter:on } @Test public void constructorWhenCredentialIsNullThenThrowsException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> new BearerTokenAuthentication(null, this.token, null)) .withMessageContaining("principal cannot be null"); // @formatter:on } @Test public void constructorWhenPassingAllAttributesThenTokenIsAuthenticated() { OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal("harris", Collections.singletonMap("claim", "value"), null); BearerTokenAuthentication authenticated = new BearerTokenAuthentication(principal, this.token, null); assertThat(authenticated.isAuthenticated()).isTrue(); } @Test public void getTokenAttributesWhenHasTokenThenReturnsThem() { BearerTokenAuthentication authenticated = new BearerTokenAuthentication(this.principal, this.token, Collections.emptyList()); assertThat(authenticated.getTokenAttributes()).isEqualTo(this.principal.getAttributes()); } @Test public void getAuthoritiesWhenHasAuthoritiesThenReturnsThem() { List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("USER"); BearerTokenAuthentication authenticated = new BearerTokenAuthentication(this.principal, this.token, authorities); assertThat(authenticated.getAuthorities()).isEqualTo(authorities); } // gh-6843 @Test public void constructorWhenDefaultParametersThenSetsPrincipalToAttributesCopy() { JSONObject attributes = new JSONObject(); attributes.put("active", true); OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(attributes, null); BearerTokenAuthentication token = new BearerTokenAuthentication(principal, this.token, null); assertThat(token.getPrincipal()).isNotSameAs(attributes); assertThat(token.getTokenAttributes()).isNotSameAs(attributes); } // gh-6843 @Test public void toStringWhenAttributesContainsURLThenDoesNotFail() throws Exception { JSONObject attributes = new JSONObject(Collections.singletonMap("iss", new URL("https://idp.example.com"))); OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(attributes, null); BearerTokenAuthentication token = new BearerTokenAuthentication(principal, this.token, null); token.toString(); } }
6,165
38.780645
113
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtAuthenticationConverterAdapterTests.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Arrays; import java.util.Collection; import org.junit.jupiter.api.Test; import org.springframework.core.convert.converter.Converter; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.TestJwts; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link ReactiveJwtAuthenticationConverterAdapter} * * @author Josh Cummings */ public class ReactiveJwtAuthenticationConverterAdapterTests { Converter<Jwt, AbstractAuthenticationToken> converter = new JwtAuthenticationConverter(); ReactiveJwtAuthenticationConverterAdapter jwtAuthenticationConverter = new ReactiveJwtAuthenticationConverterAdapter( this.converter); @Test public void convertWhenTokenHasScopeAttributeThenTranslatedToAuthorities() { Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block(); Collection<GrantedAuthority> authorities = authentication.getAuthorities(); // @formatter:off assertThat(authorities) .containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"), new SimpleGrantedAuthority("SCOPE_message:write")); // @formatter:on } @Test public void convertWhenTokenHasEmptyScopeAttributeThenTranslatedToNoAuthorities() { Jwt jwt = TestJwts.jwt().claim("scope", "").build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block(); Collection<GrantedAuthority> authorities = authentication.getAuthorities(); assertThat(authorities).containsExactly(); } @Test public void convertWhenTokenHasScpAttributeThenTranslatedToAuthorities() { Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList("message:read", "message:write")).build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block(); Collection<GrantedAuthority> authorities = authentication.getAuthorities(); // @formatter:off assertThat(authorities) .containsExactly(new SimpleGrantedAuthority("SCOPE_message:read"), new SimpleGrantedAuthority("SCOPE_message:write")); // @formatter:on } @Test public void convertWhenTokenHasEmptyScpAttributeThenTranslatedToNoAuthorities() { Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList()).build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block(); Collection<GrantedAuthority> authorities = authentication.getAuthorities(); assertThat(authorities).containsExactly(); } @Test public void convertWhenTokenHasBothScopeAndScpThenScopeAttributeIsTranslatedToAuthorities() { Jwt jwt = TestJwts.jwt().claim("scp", Arrays.asList("message:read", "message:write")) .claim("scope", "missive:read missive:write").build(); AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block(); Collection<GrantedAuthority> authorities = authentication.getAuthorities(); // @formatter:off assertThat(authorities) .containsExactly(new SimpleGrantedAuthority("SCOPE_missive:read"), new SimpleGrantedAuthority("SCOPE_missive:write")); // @formatter:on } @Test public void convertWhenTokenHasEmptyScopeAndNonEmptyScpThenScopeAttributeIsTranslatedToNoAuthorities() { // @formatter:off Jwt jwt = TestJwts.jwt() .claim("scp", Arrays.asList("message:read", "message:write")) .claim("scope", "") .build(); // @formatter:on AbstractAuthenticationToken authentication = this.jwtAuthenticationConverter.convert(jwt).block(); Collection<GrantedAuthority> authorities = authentication.getAuthorities(); assertThat(authorities).containsExactly(); } }
4,627
40.321429
118
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerAuthenticationManagerResolverTests.java
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSHeader; import com.nimbusds.jose.JWSObject; import com.nimbusds.jose.Payload; import com.nimbusds.jose.crypto.RSASSASigner; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.PlainJWT; import net.minidev.json.JSONObject; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import org.junit.jupiter.api.Test; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManagerResolver; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.jose.TestKeys; import org.springframework.security.oauth2.jwt.JwtClaimNames; import org.springframework.security.oauth2.server.resource.authentication.JwtIssuerAuthenticationManagerResolver.TrustedIssuerJwtAuthenticationManagerResolver; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.BDDMockito.mock; import static org.mockito.BDDMockito.verify; /** * Tests for {@link JwtIssuerAuthenticationManagerResolver} */ public class JwtIssuerAuthenticationManagerResolverTests { private static final String DEFAULT_RESPONSE_TEMPLATE = "{\n" + " \"issuer\": \"%s\", \n" + " \"jwks_uri\": \"%s/.well-known/jwks.json\" \n" + "}"; private static final String JWK_SET = "{\"keys\":[{\"kty\":\"RSA\",\"e\":\"AQAB\",\"use\":\"sig\",\"kid\":\"one\",\"n\":\"3FlqJr5TRskIQIgdE3Dd7D9lboWdcTUT8a-fJR7MAvQm7XXNoYkm3v7MQL1NYtDvL2l8CAnc0WdSTINU6IRvc5Kqo2Q4csNX9SHOmEfzoROjQqahEcve1jBXluoCXdYuYpx4_1tfRgG6ii4Uhxh6iI8qNMJQX-fLfqhbfYfxBQVRPywBkAbIP4x1EAsbC6FSNmkhCxiMNqEgxaIpY8C2kJdJ_ZIV-WW4noDdzpKqHcwmB8FsrumlVY_DNVvUSDIipiq9PbP4H99TXN1o746oRaNa07rq1hoCgMSSy-85SagCoxlmyE-D-of9SsMY8Ol9t0rdzpobBuhyJ_o5dfvjKw\"}]}"; private String jwt = jwt("iss", "trusted"); private String evil = jwt("iss", "\""); private String noIssuer = jwt("sub", "sub"); @Test public void resolveWhenUsingTrustedIssuerThenReturnsAuthenticationManager() throws Exception { try (MockWebServer server = new MockWebServer()) { server.start(); String issuer = server.url("").toString(); // @formatter:off server.enqueue(new MockResponse().setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer) )); server.enqueue(new MockResponse().setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody(JWK_SET) ); server.enqueue(new MockResponse().setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody(JWK_SET) ); // @formatter:on JWSObject jws = new JWSObject(new JWSHeader(JWSAlgorithm.RS256), new Payload(new JSONObject(Collections.singletonMap(JwtClaimNames.ISS, issuer)))); jws.sign(new RSASSASigner(TestKeys.DEFAULT_PRIVATE_KEY)); JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver( issuer); Authentication token = withBearerToken(jws.serialize()); AuthenticationManager authenticationManager = authenticationManagerResolver.resolve(null); assertThat(authenticationManager).isNotNull(); Authentication authentication = authenticationManager.authenticate(token); assertThat(authentication.isAuthenticated()).isTrue(); } } @Test public void resolveWhednUsingTrustedIssuerThenReturnsAuthenticationManager() throws Exception { try (MockWebServer server = new MockWebServer()) { server.start(); String issuer = server.url("").toString(); // @formatter:off server.enqueue(new MockResponse().setResponseCode(500) .setHeader("Content-Type", "application/json") .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer)) ); server.enqueue(new MockResponse().setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer)) ); server.enqueue(new MockResponse().setResponseCode(200) .setHeader("Content-Type", "application/json") .setBody(JWK_SET) ); // @formatter:on JWSObject jws = new JWSObject(new JWSHeader(JWSAlgorithm.RS256), new Payload(new JSONObject(Collections.singletonMap(JwtClaimNames.ISS, issuer)))); jws.sign(new RSASSASigner(TestKeys.DEFAULT_PRIVATE_KEY)); JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver( issuer); Authentication token = withBearerToken(jws.serialize()); AuthenticationManager authenticationManager = authenticationManagerResolver.resolve(null); assertThat(authenticationManager).isNotNull(); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> authenticationManager.authenticate(token)); Authentication authentication = authenticationManager.authenticate(token); assertThat(authentication.isAuthenticated()).isTrue(); } } @Test public void resolveWhenUsingSameIssuerThenReturnsSameAuthenticationManager() throws Exception { try (MockWebServer server = new MockWebServer()) { String issuer = server.url("").toString(); server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") .setBody(String.format(DEFAULT_RESPONSE_TEMPLATE, issuer, issuer))); server.enqueue(new MockResponse().setResponseCode(200).setHeader("Content-Type", "application/json") .setBody(JWK_SET)); TrustedIssuerJwtAuthenticationManagerResolver resolver = new TrustedIssuerJwtAuthenticationManagerResolver( (iss) -> iss.equals(issuer)); AuthenticationManager authenticationManager = resolver.resolve(issuer); AuthenticationManager cachedAuthenticationManager = resolver.resolve(issuer); assertThat(authenticationManager).isSameAs(cachedAuthenticationManager); } } @Test public void resolveWhenUsingUntrustedIssuerThenException() { JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver( "other", "issuers"); Authentication token = withBearerToken(this.jwt); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> authenticationManagerResolver.resolve(null).authenticate(token)) .withMessageContaining("Invalid issuer"); // @formatter:on } @Test public void resolveWhenUsingCustomIssuerAuthenticationManagerResolverThenUses() { AuthenticationManager authenticationManager = mock(AuthenticationManager.class); JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver( (issuer) -> authenticationManager); Authentication token = withBearerToken(this.jwt); authenticationManagerResolver.resolve(null).authenticate(token); verify(authenticationManager).authenticate(token); } @Test public void resolveWhenUsingExternalSourceThenRespondsToChanges() { Authentication token = withBearerToken(this.jwt); Map<String, AuthenticationManager> authenticationManagers = new HashMap<>(); JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver( authenticationManagers::get); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> authenticationManagerResolver.resolve(null).authenticate(token)) .withMessageContaining("Invalid issuer"); // @formatter:on AuthenticationManager authenticationManager = mock(AuthenticationManager.class); authenticationManagers.put("trusted", authenticationManager); authenticationManagerResolver.resolve(null).authenticate(token); verify(authenticationManager).authenticate(token); authenticationManagers.clear(); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> authenticationManagerResolver.resolve(null).authenticate(token)) .withMessageContaining("Invalid issuer"); // @formatter:on } @Test public void resolveWhenBearerTokenMalformedThenException() { JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver( "trusted"); Authentication token = withBearerToken("jwt"); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> authenticationManagerResolver.resolve(null).authenticate(token)) .withMessageNotContaining("Invalid issuer"); // @formatter:on } @Test public void resolveWhenBearerTokenNoIssuerThenException() { JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver( "trusted"); Authentication token = withBearerToken(this.noIssuer); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> authenticationManagerResolver.resolve(null).authenticate(token)) .withMessageContaining("Missing issuer"); // @formatter:on } @Test public void resolveWhenBearerTokenEvilThenGenericException() { JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver( "trusted"); Authentication token = withBearerToken(this.evil); // @formatter:off assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> authenticationManagerResolver .resolve(null).authenticate(token) ) .withMessage("Invalid issuer"); // @formatter:on } @Test public void constructorWhenNullOrEmptyIssuersThenException() { assertThatIllegalArgumentException() .isThrownBy(() -> new JwtIssuerAuthenticationManagerResolver((Collection) null)); assertThatIllegalArgumentException() .isThrownBy(() -> new JwtIssuerAuthenticationManagerResolver(Collections.emptyList())); } @Test public void constructorWhenNullAuthenticationManagerResolverThenException() { assertThatIllegalArgumentException() .isThrownBy(() -> new JwtIssuerAuthenticationManagerResolver((AuthenticationManagerResolver) null)); } private Authentication withBearerToken(String token) { return new BearerTokenAuthenticationToken(token); } private String jwt(String claim, String value) { PlainJWT jwt = new PlainJWT(new JWTClaimsSet.Builder().claim(claim, value).build()); return jwt.serialize(); } }
11,412
43.756863
472
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtGrantedAuthoritiesConverterAdapterTests.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Arrays; import java.util.Collection; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.springframework.core.convert.converter.Converter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.TestJwts; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link ReactiveJwtGrantedAuthoritiesConverterAdapter} * * @author Eric Deandrea * @since 5.2 */ public class ReactiveJwtGrantedAuthoritiesConverterAdapterTests { @Test public void convertWithGrantedAuthoritiesConverter() { Jwt jwt = TestJwts.jwt().claim("scope", "message:read message:write").build(); Converter<Jwt, Collection<GrantedAuthority>> grantedAuthoritiesConverter = (token) -> Arrays .asList(new SimpleGrantedAuthority("blah")); Collection<GrantedAuthority> authorities = new ReactiveJwtGrantedAuthoritiesConverterAdapter( grantedAuthoritiesConverter).convert(jwt).toStream().collect(Collectors.toList()); assertThat(authorities).containsExactly(new SimpleGrantedAuthority("blah")); } @Test public void whenConstructingWithInvalidConverter() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> new ReactiveJwtGrantedAuthoritiesConverterAdapter(null)) .withMessage("grantedAuthoritiesConverter cannot be null"); // @formatter:on } }
2,299
36.096774
95
java
null
spring-security-main/oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProviderTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.net.URL; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames; import org.springframework.security.oauth2.core.TestOAuth2AuthenticatedPrincipals; import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionAuthenticatedPrincipal; import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionException; import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenAuthenticationConverter; import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Tests for {@link OpaqueTokenAuthenticationProvider} * * @author Josh Cummings */ public class OpaqueTokenAuthenticationProviderTests { @Test public void authenticateWhenActiveTokenThenOk() throws Exception { OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals .active((attributes) -> attributes.put("extension_field", "twenty-seven")); OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class); given(introspector.introspect(any())).willReturn(principal); OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector); Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token")); assertThat(result.getPrincipal()).isInstanceOf(OAuth2IntrospectionAuthenticatedPrincipal.class); Map<String, Object> attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes(); // @formatter:off assertThat(attributes) .isNotNull() .containsEntry(OAuth2TokenIntrospectionClaimNames.ACTIVE, true) .containsEntry(OAuth2TokenIntrospectionClaimNames.AUD, Arrays.asList("https://protected.example.net/resource")) .containsEntry(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, "l238j323ds-23ij4") .containsEntry(OAuth2TokenIntrospectionClaimNames.EXP, Instant.ofEpochSecond(1419356238)) .containsEntry(OAuth2TokenIntrospectionClaimNames.ISS, new URL("https://server.example.com/")) .containsEntry(OAuth2TokenIntrospectionClaimNames.NBF, Instant.ofEpochSecond(29348723984L)) .containsEntry(OAuth2TokenIntrospectionClaimNames.SCOPE, Arrays.asList("read", "write", "dolphin")) .containsEntry(OAuth2TokenIntrospectionClaimNames.SUB, "Z5O3upPC88QrAjx00dis") .containsEntry(OAuth2TokenIntrospectionClaimNames.USERNAME, "jdoe") .containsEntry("extension_field", "twenty-seven"); assertThat(result.getAuthorities()) .extracting("authority") .containsExactly("SCOPE_read", "SCOPE_write", "SCOPE_dolphin"); // @formatter:on } @Test public void authenticateWhenMissingScopeAttributeThenNoAuthorities() { OAuth2AuthenticatedPrincipal principal = new OAuth2IntrospectionAuthenticatedPrincipal( Collections.singletonMap("claim", "value"), null); OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class); given(introspector.introspect(any())).willReturn(principal); OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector); Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token")); assertThat(result.getPrincipal()).isInstanceOf(OAuth2AuthenticatedPrincipal.class); Map<String, Object> attributes = ((OAuth2AuthenticatedPrincipal) result.getPrincipal()).getAttributes(); // @formatter:off assertThat(attributes) .isNotNull() .doesNotContainKey(OAuth2TokenIntrospectionClaimNames.SCOPE); // @formatter:on assertThat(result.getAuthorities()).isEmpty(); } @Test public void authenticateWhenIntrospectionEndpointThrowsExceptionThenInvalidToken() { OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class); given(introspector.introspect(any())).willThrow(new OAuth2IntrospectionException("with \"invalid\" chars")); OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector); assertThatExceptionOfType(AuthenticationServiceException.class) .isThrownBy(() -> provider.authenticate(new BearerTokenAuthenticationToken("token"))); } @Test public void constructorWhenIntrospectionClientIsNullThenIllegalArgumentException() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> new OpaqueTokenAuthenticationProvider(null)); // @formatter:on } @Test public void setAuthenticationConverterWhenNullThenThrowsIllegalArgumentException() { OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class); OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector); // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> provider.setAuthenticationConverter(null)) .withMessage("authenticationConverter cannot be null"); // @formatter:on } @Test public void authenticateWhenCustomAuthenticationConverterThenUses() { OpaqueTokenIntrospector introspector = mock(OpaqueTokenIntrospector.class); OAuth2AuthenticatedPrincipal principal = TestOAuth2AuthenticatedPrincipals.active(); given(introspector.introspect(any())).willReturn(principal); OpaqueTokenAuthenticationProvider provider = new OpaqueTokenAuthenticationProvider(introspector); OpaqueTokenAuthenticationConverter authenticationConverter = mock(OpaqueTokenAuthenticationConverter.class); given(authenticationConverter.convert(any(), any(OAuth2AuthenticatedPrincipal.class))) .willReturn(new TestingAuthenticationToken(principal, null, Collections.emptyList())); provider.setAuthenticationConverter(authenticationConverter); Authentication result = provider.authenticate(new BearerTokenAuthenticationToken("token")); assertThat(result).isNotNull(); verify(introspector).introspect("token"); verify(authenticationConverter).convert("token", principal); verifyNoMoreInteractions(introspector, authenticationConverter); } }
7,507
49.053333
115
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenErrorCodes.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource; /** * Standard error codes defined by the OAuth 2.0 Authorization Framework: Bearer Token * Usage. * * @author Vedran Pavic * @since 5.1 * @see <a href="https://tools.ietf.org/html/rfc6750#section-3.1" target="_blank">RFC 6750 * Section 3.1: Error Codes</a> */ public final class BearerTokenErrorCodes { /** * {@code invalid_request} - The request is missing a required parameter, includes an * unsupported parameter or parameter value, repeats the same parameter, uses more * than one method for including an access token, or is otherwise malformed. */ public static final String INVALID_REQUEST = "invalid_request"; /** * {@code invalid_token} - The access token provided is expired, revoked, malformed, * or invalid for other reasons. */ public static final String INVALID_TOKEN = "invalid_token"; /** * {@code insufficient_scope} - The request requires higher privileges than provided * by the access token. */ public static final String INSUFFICIENT_SCOPE = "insufficient_scope"; private BearerTokenErrorCodes() { } }
1,749
32.018868
90
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/package-info.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * OAuth 2.0 Resource Server core classes and interfaces providing support. */ package org.springframework.security.oauth2.server.resource;
768
35.619048
75
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenAuthenticationToken.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource; import org.springframework.security.core.SpringSecurityCoreVersion; /** * @deprecated Please use * {@link org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthenticationToken} */ @Deprecated public class BearerTokenAuthenticationToken extends org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthenticationToken { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; /** * Create a {@code BearerTokenAuthenticationToken} using the provided parameter(s) * @param token - the bearer token */ public BearerTokenAuthenticationToken(String token) { super(token); } }
1,364
33.125
109
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenErrors.java
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource; import org.springframework.http.HttpStatus; /** * A factory for creating {@link BearerTokenError} instances that correspond to the * registered <a href="https://tools.ietf.org/html/rfc6750#section-3.1">Bearer Token Error * Codes</a>. * * @author Josh Cummings * @since 5.3 */ public final class BearerTokenErrors { private static final BearerTokenError DEFAULT_INVALID_REQUEST = invalidRequest("Invalid request"); private static final BearerTokenError DEFAULT_INVALID_TOKEN = invalidToken("Invalid token"); private static final BearerTokenError DEFAULT_INSUFFICIENT_SCOPE = insufficientScope("Insufficient scope", null); private static final String DEFAULT_URI = "https://tools.ietf.org/html/rfc6750#section-3.1"; private BearerTokenErrors() { } /** * Create a {@link BearerTokenError} caused by an invalid request * @param message a description of the error * @return a {@link BearerTokenError} */ public static BearerTokenError invalidRequest(String message) { try { return new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST, message, DEFAULT_URI); } catch (IllegalArgumentException ex) { // some third-party library error messages are not suitable for RFC 6750's // error message charset return DEFAULT_INVALID_REQUEST; } } /** * Create a {@link BearerTokenError} caused by an invalid token * @param message a description of the error * @return a {@link BearerTokenError} */ public static BearerTokenError invalidToken(String message) { try { return new BearerTokenError(BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.UNAUTHORIZED, message, DEFAULT_URI); } catch (IllegalArgumentException ex) { // some third-party library error messages are not suitable for RFC 6750's // error message charset return DEFAULT_INVALID_TOKEN; } } /** * Create a {@link BearerTokenError} caused by an invalid token * @param scope the scope attribute to use in the error * @return a {@link BearerTokenError} */ public static BearerTokenError insufficientScope(String message, String scope) { try { return new BearerTokenError(BearerTokenErrorCodes.INSUFFICIENT_SCOPE, HttpStatus.FORBIDDEN, message, DEFAULT_URI, scope); } catch (IllegalArgumentException ex) { // some third-party library error messages are not suitable for RFC 6750's // error message charset return DEFAULT_INSUFFICIENT_SCOPE; } } }
3,133
32.340426
114
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/BearerTokenError.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource; import org.springframework.http.HttpStatus; import org.springframework.security.oauth2.core.OAuth2Error; import org.springframework.util.Assert; /** * A representation of a * <a href="https://tools.ietf.org/html/rfc6750#section-3.1" target="_blank">Bearer Token * Error</a>. * * @author Vedran Pavic * @author Josh Cummings * @since 5.1 * @see BearerTokenErrorCodes * @see <a href="https://tools.ietf.org/html/rfc6750#section-3" target="_blank">RFC 6750 * Section 3: The WWW-Authenticate Response Header Field</a> */ public final class BearerTokenError extends OAuth2Error { private final HttpStatus httpStatus; private final String scope; /** * Create a {@code BearerTokenError} using the provided parameters * @param errorCode the error code * @param httpStatus the HTTP status */ public BearerTokenError(String errorCode, HttpStatus httpStatus, String description, String errorUri) { this(errorCode, httpStatus, description, errorUri, null); } /** * Create a {@code BearerTokenError} using the provided parameters * @param errorCode the error code * @param httpStatus the HTTP status * @param description the description * @param errorUri the URI * @param scope the scope */ public BearerTokenError(String errorCode, HttpStatus httpStatus, String description, String errorUri, String scope) { super(errorCode, description, errorUri); Assert.notNull(httpStatus, "httpStatus cannot be null"); Assert.isTrue(isDescriptionValid(description), "description contains invalid ASCII characters, it must conform to RFC 6750"); Assert.isTrue(isErrorCodeValid(errorCode), "errorCode contains invalid ASCII characters, it must conform to RFC 6750"); Assert.isTrue(isErrorUriValid(errorUri), "errorUri contains invalid ASCII characters, it must conform to RFC 6750"); Assert.isTrue(isScopeValid(scope), "scope contains invalid ASCII characters, it must conform to RFC 6750"); this.httpStatus = httpStatus; this.scope = scope; } /** * Return the HTTP status. * @return the HTTP status */ public HttpStatus getHttpStatus() { return this.httpStatus; } /** * Return the scope. * @return the scope */ public String getScope() { return this.scope; } private static boolean isDescriptionValid(String description) { // @formatter:off return description == null || description.chars().allMatch((c) -> withinTheRangeOf(c, 0x20, 0x21) || withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E)); // @formatter:on } private static boolean isErrorCodeValid(String errorCode) { // @formatter:off return errorCode.chars().allMatch((c) -> withinTheRangeOf(c, 0x20, 0x21) || withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E)); // @formatter:on } private static boolean isErrorUriValid(String errorUri) { return errorUri == null || errorUri.chars() .allMatch((c) -> c == 0x21 || withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E)); } private static boolean isScopeValid(String scope) { // @formatter:off return scope == null || scope.chars().allMatch((c) -> withinTheRangeOf(c, 0x20, 0x21) || withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E)); // @formatter:on } private static boolean withinTheRangeOf(int c, int min, int max) { return c >= min && c <= max; } }
4,062
31.246032
109
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/InvalidBearerTokenException.java
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; /** * An {@link OAuth2AuthenticationException} that indicates an invalid bearer token. * * @author Josh Cummings * @since 5.3 */ public class InvalidBearerTokenException extends OAuth2AuthenticationException { /** * Construct an instance of {@link InvalidBearerTokenException} given the provided * description. * * The description will be wrapped into an * {@link org.springframework.security.oauth2.core.OAuth2Error} instance as the * {@code error_description}. * @param description the description */ public InvalidBearerTokenException(String description) { super(BearerTokenErrors.invalidToken(description)); } /** * Construct an instance of {@link InvalidBearerTokenException} given the provided * description and cause * * The description will be wrapped into an * {@link org.springframework.security.oauth2.core.OAuth2Error} instance as the * {@code error_description}. * @param description the description * @param cause the causing exception */ public InvalidBearerTokenException(String description, Throwable cause) { super(BearerTokenErrors.invalidToken(description), cause); } }
1,907
32.473684
83
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/package-info.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * OAuth 2.0 Resource Server {@code Filter}'s and supporting classes and interfaces. */ package org.springframework.security.oauth2.server.resource.web;
781
36.238095
84
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/DefaultBearerTokenResolver.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.web; import java.util.regex.Matcher; import java.util.regex.Pattern; import jakarta.servlet.http.HttpServletRequest; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.server.resource.BearerTokenError; import org.springframework.security.oauth2.server.resource.BearerTokenErrors; import org.springframework.util.StringUtils; /** * The default {@link BearerTokenResolver} implementation based on RFC 6750. * * @author Vedran Pavic * @since 5.1 * @see <a href="https://tools.ietf.org/html/rfc6750#section-2" target="_blank">RFC 6750 * Section 2: Authenticated Requests</a> */ public final class DefaultBearerTokenResolver implements BearerTokenResolver { private static final String ACCESS_TOKEN_PARAMETER_NAME = "access_token"; private static final Pattern authorizationPattern = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-._~+/]+=*)$", Pattern.CASE_INSENSITIVE); private boolean allowFormEncodedBodyParameter = false; private boolean allowUriQueryParameter = false; private String bearerTokenHeaderName = HttpHeaders.AUTHORIZATION; @Override public String resolve(final HttpServletRequest request) { final String authorizationHeaderToken = resolveFromAuthorizationHeader(request); final String parameterToken = isParameterTokenSupportedForRequest(request) ? resolveFromRequestParameters(request) : null; if (authorizationHeaderToken != null) { if (parameterToken != null) { final BearerTokenError error = BearerTokenErrors .invalidRequest("Found multiple bearer tokens in the request"); throw new OAuth2AuthenticationException(error); } return authorizationHeaderToken; } if (parameterToken != null && isParameterTokenEnabledForRequest(request)) { return parameterToken; } return null; } /** * Set if transport of access token using form-encoded body parameter is supported. * Defaults to {@code false}. * @param allowFormEncodedBodyParameter if the form-encoded body parameter is * supported */ public void setAllowFormEncodedBodyParameter(boolean allowFormEncodedBodyParameter) { this.allowFormEncodedBodyParameter = allowFormEncodedBodyParameter; } /** * Set if transport of access token using URI query parameter is supported. Defaults * to {@code false}. * * The spec recommends against using this mechanism for sending bearer tokens, and * even goes as far as stating that it was only included for completeness. * @param allowUriQueryParameter if the URI query parameter is supported */ public void setAllowUriQueryParameter(boolean allowUriQueryParameter) { this.allowUriQueryParameter = allowUriQueryParameter; } /** * Set this value to configure what header is checked when resolving a Bearer Token. * This value is defaulted to {@link HttpHeaders#AUTHORIZATION}. * * This allows other headers to be used as the Bearer Token source such as * {@link HttpHeaders#PROXY_AUTHORIZATION} * @param bearerTokenHeaderName the header to check when retrieving the Bearer Token. * @since 5.4 */ public void setBearerTokenHeaderName(String bearerTokenHeaderName) { this.bearerTokenHeaderName = bearerTokenHeaderName; } private String resolveFromAuthorizationHeader(HttpServletRequest request) { String authorization = request.getHeader(this.bearerTokenHeaderName); if (!StringUtils.startsWithIgnoreCase(authorization, "bearer")) { return null; } Matcher matcher = authorizationPattern.matcher(authorization); if (!matcher.matches()) { BearerTokenError error = BearerTokenErrors.invalidToken("Bearer token is malformed"); throw new OAuth2AuthenticationException(error); } return matcher.group("token"); } private static String resolveFromRequestParameters(HttpServletRequest request) { String[] values = request.getParameterValues(ACCESS_TOKEN_PARAMETER_NAME); if (values == null || values.length == 0) { return null; } if (values.length == 1) { return values[0]; } BearerTokenError error = BearerTokenErrors.invalidRequest("Found multiple bearer tokens in the request"); throw new OAuth2AuthenticationException(error); } private boolean isParameterTokenSupportedForRequest(final HttpServletRequest request) { return isFormEncodedRequest(request) || isGetRequest(request); } private static boolean isGetRequest(HttpServletRequest request) { return HttpMethod.GET.name().equals(request.getMethod()); } private static boolean isFormEncodedRequest(HttpServletRequest request) { return MediaType.APPLICATION_FORM_URLENCODED_VALUE.equals(request.getContentType()); } private static boolean hasAccessTokenInQueryString(HttpServletRequest request) { return (request.getQueryString() != null) && request.getQueryString().contains(ACCESS_TOKEN_PARAMETER_NAME); } private boolean isParameterTokenEnabledForRequest(HttpServletRequest request) { return ((this.allowFormEncodedBodyParameter && isFormEncodedRequest(request) && !isGetRequest(request) && !hasAccessTokenInQueryString(request)) || (this.allowUriQueryParameter && isGetRequest(request))); } }
5,935
37.545455
111
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenResolver.java
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.web; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; /** * A strategy for resolving * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a>s from the {@link HttpServletRequest}. * * @author Vedran Pavic * @since 5.1 * @see <a href="https://tools.ietf.org/html/rfc6750#section-2" target="_blank">RFC 6750 * Section 2: Authenticated Requests</a> */ @FunctionalInterface public interface BearerTokenResolver { /** * Resolve any * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a> value from the request. * @param request the request * @return the Bearer Token value or {@code null} if none found * @throws OAuth2AuthenticationException if the found token is invalid */ String resolve(HttpServletRequest request); }
1,586
32.765957
88
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/HeaderBearerTokenResolver.java
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.web; import jakarta.servlet.http.HttpServletRequest; import org.springframework.util.Assert; /** * Generic resolver extracting pre-authenticated JWT identity from a custom header. * * @author Elena Felder * @since 5.2 */ public class HeaderBearerTokenResolver implements BearerTokenResolver { private String header; public HeaderBearerTokenResolver(String header) { Assert.hasText(header, "header cannot be empty"); this.header = header; } @Override public String resolve(HttpServletRequest request) { return request.getHeader(this.header); } }
1,252
27.477273
83
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationFilter.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.web; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManagerResolver; /** * @deprecated Use * {@link org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter} * instead */ @Deprecated public final class BearerTokenAuthenticationFilter extends org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter { /** * Construct a {@code BearerTokenAuthenticationFilter} using the provided parameter(s) * @param authenticationManagerResolver */ public BearerTokenAuthenticationFilter( AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver) { super(authenticationManagerResolver); } /** * Construct a {@code BearerTokenAuthenticationFilter} using the provided parameter(s) * @param authenticationManager */ public BearerTokenAuthenticationFilter(AuthenticationManager authenticationManager) { super(authenticationManager); } }
1,792
34.156863
114
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationEntryPoint.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.web; import java.util.LinkedHashMap; import java.util.Map; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.security.core.AuthenticationException; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.core.OAuth2Error; import org.springframework.security.oauth2.server.resource.BearerTokenError; import org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.util.StringUtils; /** * An {@link AuthenticationEntryPoint} implementation used to commence authentication of * protected resource requests using {@link BearerTokenAuthenticationFilter}. * <p> * Uses information provided by {@link BearerTokenError} to set HTTP response status code * and populate {@code WWW-Authenticate} HTTP header. * * @author Vedran Pavic * @since 5.1 * @see BearerTokenError * @see <a href="https://tools.ietf.org/html/rfc6750#section-3" target="_blank">RFC 6750 * Section 3: The WWW-Authenticate Response Header Field</a> */ public final class BearerTokenAuthenticationEntryPoint implements AuthenticationEntryPoint { private String realmName; /** * Collect error details from the provided parameters and format according to RFC * 6750, specifically {@code error}, {@code error_description}, {@code error_uri}, and * {@code scope}. * @param request that resulted in an <code>AuthenticationException</code> * @param response so that the user agent can begin authentication * @param authException that caused the invocation */ @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) { HttpStatus status = HttpStatus.UNAUTHORIZED; Map<String, String> parameters = new LinkedHashMap<>(); if (this.realmName != null) { parameters.put("realm", this.realmName); } if (authException instanceof OAuth2AuthenticationException) { OAuth2Error error = ((OAuth2AuthenticationException) authException).getError(); parameters.put("error", error.getErrorCode()); if (StringUtils.hasText(error.getDescription())) { parameters.put("error_description", error.getDescription()); } if (StringUtils.hasText(error.getUri())) { parameters.put("error_uri", error.getUri()); } if (error instanceof BearerTokenError bearerTokenError) { if (StringUtils.hasText(bearerTokenError.getScope())) { parameters.put("scope", bearerTokenError.getScope()); } status = ((BearerTokenError) error).getHttpStatus(); } } String wwwAuthenticate = computeWWWAuthenticateHeaderValue(parameters); response.addHeader(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticate); response.setStatus(status.value()); } /** * Set the default realm name to use in the bearer token error response * @param realmName */ public void setRealmName(String realmName) { this.realmName = realmName; } private static String computeWWWAuthenticateHeaderValue(Map<String, String> parameters) { StringBuilder wwwAuthenticate = new StringBuilder(); wwwAuthenticate.append("Bearer"); if (!parameters.isEmpty()) { wwwAuthenticate.append(" "); int i = 0; for (Map.Entry<String, String> entry : parameters.entrySet()) { wwwAuthenticate.append(entry.getKey()).append("=\"").append(entry.getValue()).append("\""); if (i != parameters.size() - 1) { wwwAuthenticate.append(", "); } i++; } } return wwwAuthenticate.toString(); } }
4,421
37.452174
110
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServerBearerExchangeFilterFunction.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.web.reactive.function.client; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.oauth2.core.OAuth2Token; import org.springframework.web.reactive.function.client.ClientRequest; import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.ExchangeFilterFunction; import org.springframework.web.reactive.function.client.ExchangeFunction; /** * An {@link ExchangeFilterFunction} that adds the * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a> from an existing {@link OAuth2Token} tied to the current * {@link Authentication}. * * Suitable for Reactive applications, applying it to a typical * {@link org.springframework.web.reactive.function.client.WebClient} configuration: * * <pre> * &#64;Bean * WebClient webClient() { * ServerBearerExchangeFilterFunction bearer = new ServerBearerExchangeFilterFunction(); * return WebClient.builder() * .filter(bearer).build(); * } * </pre> * * @author Josh Cummings * @since 5.2 */ public final class ServerBearerExchangeFilterFunction implements ExchangeFilterFunction { @Override public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) { // @formatter:off return oauth2Token().map((token) -> bearer(request, token)) .defaultIfEmpty(request) .flatMap(next::exchange); // @formatter:on } private Mono<OAuth2Token> oauth2Token() { // @formatter:off return currentAuthentication() .filter((authentication) -> authentication.getCredentials() instanceof OAuth2Token) .map(Authentication::getCredentials) .cast(OAuth2Token.class); // @formatter:on } private Mono<Authentication> currentAuthentication() { // @formatter:off return ReactiveSecurityContextHolder.getContext() .map(SecurityContext::getAuthentication); // @formatter:on } private ClientRequest bearer(ClientRequest request, OAuth2Token token) { // @formatter:off return ClientRequest.from(request) .headers((headers) -> headers.setBearerAuth(token.getTokenValue())) .build(); // @formatter:on } }
3,055
33.727273
93
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServletBearerExchangeFilterFunction.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.web.reactive.function.client; import java.util.Map; import reactor.core.publisher.Mono; import reactor.util.context.Context; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.core.OAuth2Token; import org.springframework.web.reactive.function.client.ClientRequest; import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.ExchangeFilterFunction; import org.springframework.web.reactive.function.client.ExchangeFunction; /** * An {@link ExchangeFilterFunction} that adds the * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a> from an existing {@link OAuth2Token} tied to the current * {@link Authentication}. * * Suitable for Servlet applications, applying it to a typical * {@link org.springframework.web.reactive.function.client.WebClient} configuration: * * <pre> * &#64;Bean * WebClient webClient() { * ServletBearerExchangeFilterFunction bearer = new ServletBearerExchangeFilterFunction(); * return WebClient.builder() * .filter(bearer).build(); * } * </pre> * * To locate the bearer token, this looks in the Reactor {@link Context} for a key of type * {@link Authentication}. * * Registering * {@see org.springframework.security.config.annotation.web.configuration.OAuth2ResourceServerConfiguration.OAuth2ResourceServerWebFluxSecurityConfiguration.BearerRequestContextSubscriberRegistrar}, * as a {@code @Bean} will take care of this automatically, but certainly an application * can supply a {@link Context} of its own to override. * * @author Josh Cummings * @since 5.2 */ public final class ServletBearerExchangeFilterFunction implements ExchangeFilterFunction { static final String SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY = "org.springframework.security.SECURITY_CONTEXT_ATTRIBUTES"; @Override public Mono<ClientResponse> filter(ClientRequest request, ExchangeFunction next) { // @formatter:off return oauth2Token().map((token) -> bearer(request, token)) .defaultIfEmpty(request) .flatMap(next::exchange); // @formatter:on } private Mono<OAuth2Token> oauth2Token() { // @formatter:off return Mono.deferContextual(Mono::just) .cast(Context.class) .flatMap(this::currentAuthentication) .filter((authentication) -> authentication.getCredentials() instanceof OAuth2Token) .map(Authentication::getCredentials) .cast(OAuth2Token.class); // @formatter:on } private Mono<Authentication> currentAuthentication(Context ctx) { return Mono.justOrEmpty(getAttribute(ctx, Authentication.class)); } private <T> T getAttribute(Context ctx, Class<T> clazz) { // NOTE: SecurityReactorContextConfiguration.SecurityReactorContextSubscriber adds // this key if (!ctx.hasKey(SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY)) { return null; } Map<Class<T>, T> attributes = ctx.get(SECURITY_REACTOR_CONTEXT_ATTRIBUTES_KEY); return attributes.get(clazz); } private ClientRequest bearer(ClientRequest request, OAuth2Token token) { // @formatter:off return ClientRequest.from(request) .headers((headers) -> headers.setBearerAuth(token.getTokenValue())) .build(); // @formatter:on } }
3,954
35.62037
198
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/access/package-info.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * OAuth 2.0 Resource Server access denial classes and interfaces. */ package org.springframework.security.oauth2.server.resource.web.access;
770
35.714286
75
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/access/BearerTokenAccessDeniedHandler.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.web.access; import java.util.LinkedHashMap; import java.util.Map; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes; import org.springframework.security.oauth2.server.resource.authentication.AbstractOAuth2TokenAuthenticationToken; import org.springframework.security.web.access.AccessDeniedHandler; /** * Translates any {@link AccessDeniedException} into an HTTP response in accordance with * <a href="https://tools.ietf.org/html/rfc6750#section-3" target="_blank">RFC 6750 * Section 3: The WWW-Authenticate</a>. * <p> * So long as the class can prove that the request has a valid OAuth 2.0 * {@link Authentication}, then will return an * <a href="https://tools.ietf.org/html/rfc6750#section-3.1" target="_blank">insufficient * scope error</a>; otherwise, it will simply indicate the scheme (Bearer) and any * configured realm. * * @author Josh Cummings * @since 5.1 */ public final class BearerTokenAccessDeniedHandler implements AccessDeniedHandler { private String realmName; /** * Collect error details from the provided parameters and format according to RFC * 6750, specifically {@code error}, {@code error_description}, {@code error_uri}, and * {@code scope}. * @param request that resulted in an <code>AccessDeniedException</code> * @param response so that the user agent can be advised of the failure * @param accessDeniedException that caused the invocation */ @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) { Map<String, String> parameters = new LinkedHashMap<>(); if (this.realmName != null) { parameters.put("realm", this.realmName); } if (request.getUserPrincipal() instanceof AbstractOAuth2TokenAuthenticationToken) { parameters.put("error", BearerTokenErrorCodes.INSUFFICIENT_SCOPE); parameters.put("error_description", "The request requires higher privileges than provided by the access token."); parameters.put("error_uri", "https://tools.ietf.org/html/rfc6750#section-3.1"); } String wwwAuthenticate = computeWWWAuthenticateHeaderValue(parameters); response.addHeader(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticate); response.setStatus(HttpStatus.FORBIDDEN.value()); } /** * Set the default realm name to use in the bearer token error response * @param realmName */ public void setRealmName(String realmName) { this.realmName = realmName; } private static String computeWWWAuthenticateHeaderValue(Map<String, String> parameters) { StringBuilder wwwAuthenticate = new StringBuilder(); wwwAuthenticate.append("Bearer"); if (!parameters.isEmpty()) { wwwAuthenticate.append(" "); int i = 0; for (Map.Entry<String, String> entry : parameters.entrySet()) { wwwAuthenticate.append(entry.getKey()).append("=\"").append(entry.getValue()).append("\""); if (i != parameters.size() - 1) { wwwAuthenticate.append(", "); } i++; } } return wwwAuthenticate.toString(); } }
4,016
38
113
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/access/server/BearerTokenServerAccessDeniedHandler.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.web.access.server; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import reactor.core.publisher.Mono; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.server.resource.BearerTokenErrorCodes; import org.springframework.security.oauth2.server.resource.authentication.AbstractOAuth2TokenAuthenticationToken; import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler; import org.springframework.web.server.ServerWebExchange; /** * Translates any {@link AccessDeniedException} into an HTTP response in accordance with * <a href="https://tools.ietf.org/html/rfc6750#section-3" target="_blank">RFC 6750 * Section 3: The WWW-Authenticate</a>. * * So long as the class can prove that the request has a valid OAuth 2.0 * {@link Authentication}, then will return an * <a href="https://tools.ietf.org/html/rfc6750#section-3.1" target="_blank">insufficient * scope error</a>; otherwise, it will simply indicate the scheme (Bearer) and any * configured realm. * * @author Josh Cummings * @since 5.1 * */ public class BearerTokenServerAccessDeniedHandler implements ServerAccessDeniedHandler { private static final Collection<String> WELL_KNOWN_SCOPE_ATTRIBUTE_NAMES = Arrays.asList("scope", "scp"); private String realmName; @Override public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException denied) { Map<String, String> parameters = new LinkedHashMap<>(); if (this.realmName != null) { parameters.put("realm", this.realmName); } // @formatter:off return exchange.getPrincipal() .filter(AbstractOAuth2TokenAuthenticationToken.class::isInstance) .map((token) -> errorMessageParameters(parameters)) .switchIfEmpty(Mono.just(parameters)) .flatMap((params) -> respond(exchange, params)); // @formatter:on } /** * Set the default realm name to use in the bearer token error response * @param realmName */ public final void setRealmName(String realmName) { this.realmName = realmName; } private static Map<String, String> errorMessageParameters(Map<String, String> parameters) { parameters.put("error", BearerTokenErrorCodes.INSUFFICIENT_SCOPE); parameters.put("error_description", "The request requires higher privileges than provided by the access token."); parameters.put("error_uri", "https://tools.ietf.org/html/rfc6750#section-3.1"); return parameters; } private static Mono<Void> respond(ServerWebExchange exchange, Map<String, String> parameters) { String wwwAuthenticate = computeWWWAuthenticateHeaderValue(parameters); exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN); exchange.getResponse().getHeaders().set(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticate); return exchange.getResponse().setComplete(); } private static String computeWWWAuthenticateHeaderValue(Map<String, String> parameters) { StringBuilder wwwAuthenticate = new StringBuilder(); wwwAuthenticate.append("Bearer"); if (!parameters.isEmpty()) { wwwAuthenticate.append(" "); int i = 0; for (Map.Entry<String, String> entry : parameters.entrySet()) { wwwAuthenticate.append(entry.getKey()).append("=\"").append(entry.getValue()).append("\""); if (i != parameters.size() - 1) { wwwAuthenticate.append(", "); } i++; } } return wwwAuthenticate.toString(); } }
4,259
37.035714
113
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/authentication/BearerTokenAuthenticationFilter.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.web.authentication; import java.io.IOException; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.core.log.LogMessage; import org.springframework.security.authentication.AuthenticationDetailsSource; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManagerResolver; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthenticationToken; import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider; import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationEntryPoint; import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver; import org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.authentication.AuthenticationEntryPointFailureHandler; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.security.web.context.RequestAttributeSecurityContextRepository; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.util.Assert; import org.springframework.web.filter.OncePerRequestFilter; /** * Authenticates requests that contain an OAuth 2.0 * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a>. * * This filter should be wired with an {@link AuthenticationManager} that can authenticate * a {@link BearerTokenAuthenticationToken}. * * @author Josh Cummings * @author Vedran Pavic * @author Joe Grandja * @author Jeongjin Kim * @since 5.1 * @see <a href="https://tools.ietf.org/html/rfc6750" target="_blank">The OAuth 2.0 * Authorization Framework: Bearer Token Usage</a> * @see JwtAuthenticationProvider */ public class BearerTokenAuthenticationFilter extends OncePerRequestFilter { private final AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver; private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); private AuthenticationEntryPoint authenticationEntryPoint = new BearerTokenAuthenticationEntryPoint(); private AuthenticationFailureHandler authenticationFailureHandler = new AuthenticationEntryPointFailureHandler( (request, response, exception) -> this.authenticationEntryPoint.commence(request, response, exception)); private BearerTokenResolver bearerTokenResolver = new DefaultBearerTokenResolver(); private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new WebAuthenticationDetailsSource(); private SecurityContextRepository securityContextRepository = new RequestAttributeSecurityContextRepository(); /** * Construct a {@code BearerTokenAuthenticationFilter} using the provided parameter(s) * @param authenticationManagerResolver */ public BearerTokenAuthenticationFilter( AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver) { Assert.notNull(authenticationManagerResolver, "authenticationManagerResolver cannot be null"); this.authenticationManagerResolver = authenticationManagerResolver; } /** * Construct a {@code BearerTokenAuthenticationFilter} using the provided parameter(s) * @param authenticationManager */ public BearerTokenAuthenticationFilter(AuthenticationManager authenticationManager) { Assert.notNull(authenticationManager, "authenticationManager cannot be null"); this.authenticationManagerResolver = (request) -> authenticationManager; } /** * Extract any * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a> from the request and attempt an authentication. * @param request * @param response * @param filterChain * @throws ServletException * @throws IOException */ @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String token; try { token = this.bearerTokenResolver.resolve(request); } catch (OAuth2AuthenticationException invalid) { this.logger.trace("Sending to authentication entry point since failed to resolve bearer token", invalid); this.authenticationEntryPoint.commence(request, response, invalid); return; } if (token == null) { this.logger.trace("Did not process request since did not find bearer token"); filterChain.doFilter(request, response); return; } BearerTokenAuthenticationToken authenticationRequest = new BearerTokenAuthenticationToken(token); authenticationRequest.setDetails(this.authenticationDetailsSource.buildDetails(request)); try { AuthenticationManager authenticationManager = this.authenticationManagerResolver.resolve(request); Authentication authenticationResult = authenticationManager.authenticate(authenticationRequest); SecurityContext context = this.securityContextHolderStrategy.createEmptyContext(); context.setAuthentication(authenticationResult); this.securityContextHolderStrategy.setContext(context); this.securityContextRepository.saveContext(context, request, response); if (this.logger.isDebugEnabled()) { this.logger.debug(LogMessage.format("Set SecurityContextHolder to %s", authenticationResult)); } filterChain.doFilter(request, response); } catch (AuthenticationException failed) { this.securityContextHolderStrategy.clearContext(); this.logger.trace("Failed to process authentication request", failed); this.authenticationFailureHandler.onAuthenticationFailure(request, response, failed); } } /** * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use * the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}. * * @since 5.8 */ public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null"); this.securityContextHolderStrategy = securityContextHolderStrategy; } /** * Sets the {@link SecurityContextRepository} to save the {@link SecurityContext} on * authentication success. The default action is not to save the * {@link SecurityContext}. * @param securityContextRepository the {@link SecurityContextRepository} to use. * Cannot be null. */ public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) { Assert.notNull(securityContextRepository, "securityContextRepository cannot be null"); this.securityContextRepository = securityContextRepository; } /** * Set the {@link BearerTokenResolver} to use. Defaults to * {@link DefaultBearerTokenResolver}. * @param bearerTokenResolver the {@code BearerTokenResolver} to use */ public void setBearerTokenResolver(BearerTokenResolver bearerTokenResolver) { Assert.notNull(bearerTokenResolver, "bearerTokenResolver cannot be null"); this.bearerTokenResolver = bearerTokenResolver; } /** * Set the {@link AuthenticationEntryPoint} to use. Defaults to * {@link BearerTokenAuthenticationEntryPoint}. * @param authenticationEntryPoint the {@code AuthenticationEntryPoint} to use */ public void setAuthenticationEntryPoint(final AuthenticationEntryPoint authenticationEntryPoint) { Assert.notNull(authenticationEntryPoint, "authenticationEntryPoint cannot be null"); this.authenticationEntryPoint = authenticationEntryPoint; } /** * Set the {@link AuthenticationFailureHandler} to use. Default implementation invokes * {@link AuthenticationEntryPoint}. * @param authenticationFailureHandler the {@code AuthenticationFailureHandler} to use * @since 5.2 */ public void setAuthenticationFailureHandler(final AuthenticationFailureHandler authenticationFailureHandler) { Assert.notNull(authenticationFailureHandler, "authenticationFailureHandler cannot be null"); this.authenticationFailureHandler = authenticationFailureHandler; } /** * Set the {@link AuthenticationDetailsSource} to use. Defaults to * {@link WebAuthenticationDetailsSource}. * @param authenticationDetailsSource the {@code AuthenticationConverter} to use * @since 5.5 */ public void setAuthenticationDetailsSource( AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) { Assert.notNull(authenticationDetailsSource, "authenticationDetailsSource cannot be null"); this.authenticationDetailsSource = authenticationDetailsSource; } }
10,032
44.39819
127
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/server/BearerTokenServerAuthenticationEntryPoint.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.web.server; import java.util.LinkedHashMap; import java.util.Map; import reactor.core.publisher.Mono; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.server.reactive.ServerHttpResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.core.OAuth2Error; import org.springframework.security.oauth2.server.resource.BearerTokenError; import org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.server.ServerAuthenticationEntryPoint; import org.springframework.util.StringUtils; import org.springframework.web.server.ServerWebExchange; /** * An {@link AuthenticationEntryPoint} implementation used to commence authentication of * protected resource requests using {@link BearerTokenAuthenticationFilter}. * <p> * Uses information provided by {@link BearerTokenError} to set HTTP response status code * and populate {@code WWW-Authenticate} HTTP header. * * @author Rob Winch * @since 5.1 * @see BearerTokenError * @see <a href="https://tools.ietf.org/html/rfc6750#section-3" target="_blank">RFC 6750 * Section 3: The WWW-Authenticate Response Header Field</a> */ public final class BearerTokenServerAuthenticationEntryPoint implements ServerAuthenticationEntryPoint { private String realmName; public void setRealmName(String realmName) { this.realmName = realmName; } @Override public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException authException) { return Mono.defer(() -> { HttpStatus status = getStatus(authException); Map<String, String> parameters = createParameters(authException); String wwwAuthenticate = computeWWWAuthenticateHeaderValue(parameters); ServerHttpResponse response = exchange.getResponse(); response.getHeaders().set(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticate); response.setStatusCode(status); return response.setComplete(); }); } private Map<String, String> createParameters(AuthenticationException authException) { Map<String, String> parameters = new LinkedHashMap<>(); if (this.realmName != null) { parameters.put("realm", this.realmName); } if (authException instanceof OAuth2AuthenticationException) { OAuth2Error error = ((OAuth2AuthenticationException) authException).getError(); parameters.put("error", error.getErrorCode()); if (StringUtils.hasText(error.getDescription())) { parameters.put("error_description", error.getDescription()); } if (StringUtils.hasText(error.getUri())) { parameters.put("error_uri", error.getUri()); } if (error instanceof BearerTokenError bearerTokenError) { if (StringUtils.hasText(bearerTokenError.getScope())) { parameters.put("scope", bearerTokenError.getScope()); } } } return parameters; } private HttpStatus getStatus(AuthenticationException authException) { if (authException instanceof OAuth2AuthenticationException) { OAuth2Error error = ((OAuth2AuthenticationException) authException).getError(); if (error instanceof BearerTokenError) { return ((BearerTokenError) error).getHttpStatus(); } } return HttpStatus.UNAUTHORIZED; } private static String computeWWWAuthenticateHeaderValue(Map<String, String> parameters) { StringBuilder wwwAuthenticate = new StringBuilder(); wwwAuthenticate.append("Bearer"); if (!parameters.isEmpty()) { wwwAuthenticate.append(" "); int i = 0; for (Map.Entry<String, String> entry : parameters.entrySet()) { wwwAuthenticate.append(entry.getKey()).append("=\"").append(entry.getValue()).append("\""); if (i != parameters.size() - 1) { wwwAuthenticate.append(", "); } i++; } } return wwwAuthenticate.toString(); } }
4,674
37.319672
110
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/web/server/authentication/ServerBearerTokenAuthenticationConverter.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.web.server.authentication; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import reactor.core.publisher.Mono; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.server.resource.BearerTokenError; import org.springframework.security.oauth2.server.resource.BearerTokenErrors; import org.springframework.security.oauth2.server.resource.authentication.BearerTokenAuthenticationToken; import org.springframework.security.web.server.authentication.ServerAuthenticationConverter; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import org.springframework.web.server.ServerWebExchange; /** * A strategy for resolving * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a>s from the {@link ServerWebExchange}. * * @author Rob Winch * @since 5.1 * @see <a href="https://tools.ietf.org/html/rfc6750#section-2" target="_blank">RFC 6750 * Section 2: Authenticated Requests</a> */ public class ServerBearerTokenAuthenticationConverter implements ServerAuthenticationConverter { private static final Pattern authorizationPattern = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-._~+/]+=*)$", Pattern.CASE_INSENSITIVE); private boolean allowUriQueryParameter = false; private String bearerTokenHeaderName = HttpHeaders.AUTHORIZATION; @Override public Mono<Authentication> convert(ServerWebExchange exchange) { return Mono.fromCallable(() -> token(exchange.getRequest())).map((token) -> { if (token.isEmpty()) { BearerTokenError error = invalidTokenError(); throw new OAuth2AuthenticationException(error); } return new BearerTokenAuthenticationToken(token); }); } private String token(ServerHttpRequest request) { String authorizationHeaderToken = resolveFromAuthorizationHeader(request.getHeaders()); String parameterToken = resolveAccessTokenFromRequest(request); if (authorizationHeaderToken != null) { if (parameterToken != null) { BearerTokenError error = BearerTokenErrors .invalidRequest("Found multiple bearer tokens in the request"); throw new OAuth2AuthenticationException(error); } return authorizationHeaderToken; } if (parameterToken != null && isParameterTokenSupportedForRequest(request)) { return parameterToken; } return null; } private static String resolveAccessTokenFromRequest(ServerHttpRequest request) { List<String> parameterTokens = request.getQueryParams().get("access_token"); if (CollectionUtils.isEmpty(parameterTokens)) { return null; } if (parameterTokens.size() == 1) { return parameterTokens.get(0); } BearerTokenError error = BearerTokenErrors.invalidRequest("Found multiple bearer tokens in the request"); throw new OAuth2AuthenticationException(error); } /** * Set if transport of access token using URI query parameter is supported. Defaults * to {@code false}. * * The spec recommends against using this mechanism for sending bearer tokens, and * even goes as far as stating that it was only included for completeness. * @param allowUriQueryParameter if the URI query parameter is supported */ public void setAllowUriQueryParameter(boolean allowUriQueryParameter) { this.allowUriQueryParameter = allowUriQueryParameter; } /** * Set this value to configure what header is checked when resolving a Bearer Token. * This value is defaulted to {@link HttpHeaders#AUTHORIZATION}. * * This allows other headers to be used as the Bearer Token source such as * {@link HttpHeaders#PROXY_AUTHORIZATION} * @param bearerTokenHeaderName the header to check when retrieving the Bearer Token. * @since 5.4 */ public void setBearerTokenHeaderName(String bearerTokenHeaderName) { this.bearerTokenHeaderName = bearerTokenHeaderName; } private String resolveFromAuthorizationHeader(HttpHeaders headers) { String authorization = headers.getFirst(this.bearerTokenHeaderName); if (!StringUtils.startsWithIgnoreCase(authorization, "bearer")) { return null; } Matcher matcher = authorizationPattern.matcher(authorization); if (!matcher.matches()) { BearerTokenError error = invalidTokenError(); throw new OAuth2AuthenticationException(error); } return matcher.group("token"); } private static BearerTokenError invalidTokenError() { return BearerTokenErrors.invalidToken("Bearer token is malformed"); } private boolean isParameterTokenSupportedForRequest(ServerHttpRequest request) { return this.allowUriQueryParameter && HttpMethod.GET.equals(request.getMethod()); } }
5,550
36.761905
111
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/OAuth2IntrospectionAuthenticatedPrincipal.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.introspection; import java.io.Serializable; import java.util.Collection; import java.util.Map; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimAccessor; /** * A domain object that wraps the attributes of OAuth 2.0 Token Introspection. * * @author David Kovac * @since 5.4 * @see <a target="_blank" href= * "https://tools.ietf.org/html/rfc7662#section-2.2">Introspection Response</a> */ public final class OAuth2IntrospectionAuthenticatedPrincipal implements OAuth2TokenIntrospectionClaimAccessor, OAuth2AuthenticatedPrincipal, Serializable { private final OAuth2AuthenticatedPrincipal delegate; /** * Constructs an {@code OAuth2IntrospectionAuthenticatedPrincipal} using the provided * parameters. * @param attributes the attributes of the OAuth 2.0 Token Introspection * @param authorities the authorities of the OAuth 2.0 Token Introspection */ public OAuth2IntrospectionAuthenticatedPrincipal(Map<String, Object> attributes, Collection<GrantedAuthority> authorities) { this.delegate = new DefaultOAuth2AuthenticatedPrincipal(attributes, authorities); } /** * Constructs an {@code OAuth2IntrospectionAuthenticatedPrincipal} using the provided * parameters. * @param name the name attached to the OAuth 2.0 Token Introspection * @param attributes the attributes of the OAuth 2.0 Token Introspection * @param authorities the authorities of the OAuth 2.0 Token Introspection */ public OAuth2IntrospectionAuthenticatedPrincipal(String name, Map<String, Object> attributes, Collection<GrantedAuthority> authorities) { this.delegate = new DefaultOAuth2AuthenticatedPrincipal(name, attributes, authorities); } /** * Gets the attributes of the OAuth 2.0 Token Introspection in map form. * @return a {@link Map} of the attribute's objects keyed by the attribute's names */ @Override public Map<String, Object> getAttributes() { return this.delegate.getAttributes(); } /** * Get the {@link Collection} of {@link GrantedAuthority}s associated with this OAuth * 2.0 Token Introspection * @return the OAuth 2.0 Token Introspection authorities */ @Override public Collection<? extends GrantedAuthority> getAuthorities() { return this.delegate.getAuthorities(); } @Override public String getName() { return this.delegate.getName(); } @Override public Map<String, Object> getClaims() { return getAttributes(); } }
3,329
34.425532
96
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusOpaqueTokenIntrospector.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.introspection; import java.net.URI; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import com.nimbusds.oauth2.sdk.ErrorObject; import com.nimbusds.oauth2.sdk.TokenIntrospectionResponse; import com.nimbusds.oauth2.sdk.TokenIntrospectionSuccessResponse; import com.nimbusds.oauth2.sdk.http.HTTPResponse; import com.nimbusds.oauth2.sdk.id.Audience; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.convert.converter.Converter; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.http.client.support.BasicAuthenticationInterceptor; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames; import org.springframework.util.Assert; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestOperations; import org.springframework.web.client.RestTemplate; /** * A Nimbus implementation of {@link OpaqueTokenIntrospector} that verifies and * introspects a token using the configured * <a href="https://tools.ietf.org/html/rfc7662" target="_blank">OAuth 2.0 Introspection * Endpoint</a>. * * @author Josh Cummings * @author MD Sayem Ahmed * @since 5.2 */ public class NimbusOpaqueTokenIntrospector implements OpaqueTokenIntrospector { private static final String AUTHORITY_PREFIX = "SCOPE_"; private final Log logger = LogFactory.getLog(getClass()); private final RestOperations restOperations; private Converter<String, RequestEntity<?>> requestEntityConverter; /** * Creates a {@code OpaqueTokenAuthenticationProvider} with the provided parameters * @param introspectionUri The introspection endpoint uri * @param clientId The client id authorized to introspect * @param clientSecret The client's secret */ public NimbusOpaqueTokenIntrospector(String introspectionUri, String clientId, String clientSecret) { Assert.notNull(introspectionUri, "introspectionUri cannot be null"); Assert.notNull(clientId, "clientId cannot be null"); Assert.notNull(clientSecret, "clientSecret cannot be null"); this.requestEntityConverter = this.defaultRequestEntityConverter(URI.create(introspectionUri)); RestTemplate restTemplate = new RestTemplate(); restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor(clientId, clientSecret)); this.restOperations = restTemplate; } /** * Creates a {@code OpaqueTokenAuthenticationProvider} with the provided parameters * * The given {@link RestOperations} should perform its own client authentication * against the introspection endpoint. * @param introspectionUri The introspection endpoint uri * @param restOperations The client for performing the introspection request */ public NimbusOpaqueTokenIntrospector(String introspectionUri, RestOperations restOperations) { Assert.notNull(introspectionUri, "introspectionUri cannot be null"); Assert.notNull(restOperations, "restOperations cannot be null"); this.requestEntityConverter = this.defaultRequestEntityConverter(URI.create(introspectionUri)); this.restOperations = restOperations; } private Converter<String, RequestEntity<?>> defaultRequestEntityConverter(URI introspectionUri) { return (token) -> { HttpHeaders headers = requestHeaders(); MultiValueMap<String, String> body = requestBody(token); return new RequestEntity<>(body, headers, HttpMethod.POST, introspectionUri); }; } private HttpHeaders requestHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); return headers; } private MultiValueMap<String, String> requestBody(String token) { MultiValueMap<String, String> body = new LinkedMultiValueMap<>(); body.add("token", token); return body; } @Override public OAuth2AuthenticatedPrincipal introspect(String token) { RequestEntity<?> requestEntity = this.requestEntityConverter.convert(token); if (requestEntity == null) { throw new OAuth2IntrospectionException("requestEntityConverter returned a null entity"); } ResponseEntity<String> responseEntity = makeRequest(requestEntity); HTTPResponse httpResponse = adaptToNimbusResponse(responseEntity); TokenIntrospectionResponse introspectionResponse = parseNimbusResponse(httpResponse); TokenIntrospectionSuccessResponse introspectionSuccessResponse = castToNimbusSuccess(introspectionResponse); // relying solely on the authorization server to validate this token (not checking // 'exp', for example) if (!introspectionSuccessResponse.isActive()) { this.logger.trace("Did not validate token since it is inactive"); throw new BadOpaqueTokenException("Provided token isn't active"); } return convertClaimsSet(introspectionSuccessResponse); } /** * Sets the {@link Converter} used for converting the OAuth 2.0 access token to a * {@link RequestEntity} representation of the OAuth 2.0 token introspection request. * @param requestEntityConverter the {@link Converter} used for converting to a * {@link RequestEntity} representation of the token introspection request */ public void setRequestEntityConverter(Converter<String, RequestEntity<?>> requestEntityConverter) { Assert.notNull(requestEntityConverter, "requestEntityConverter cannot be null"); this.requestEntityConverter = requestEntityConverter; } private ResponseEntity<String> makeRequest(RequestEntity<?> requestEntity) { try { return this.restOperations.exchange(requestEntity, String.class); } catch (Exception ex) { throw new OAuth2IntrospectionException(ex.getMessage(), ex); } } private HTTPResponse adaptToNimbusResponse(ResponseEntity<String> responseEntity) { MediaType contentType = responseEntity.getHeaders().getContentType(); if (contentType == null) { this.logger.trace("Did not receive Content-Type from introspection endpoint in response"); throw new OAuth2IntrospectionException( "Introspection endpoint response was invalid, as no Content-Type header was provided"); } // Nimbus expects JSON, but does not appear to validate this header first. if (!contentType.isCompatibleWith(MediaType.APPLICATION_JSON)) { this.logger.trace("Did not receive JSON-compatible Content-Type from introspection endpoint in response"); throw new OAuth2IntrospectionException("Introspection endpoint response was invalid, as content type '" + contentType + "' is not compatible with JSON"); } HTTPResponse response = new HTTPResponse(responseEntity.getStatusCode().value()); response.setHeader(HttpHeaders.CONTENT_TYPE, contentType.toString()); response.setContent(responseEntity.getBody()); if (response.getStatusCode() != HTTPResponse.SC_OK) { this.logger.trace("Introspection endpoint returned non-OK status code"); throw new OAuth2IntrospectionException( "Introspection endpoint responded with HTTP status code " + response.getStatusCode()); } return response; } private TokenIntrospectionResponse parseNimbusResponse(HTTPResponse response) { try { return TokenIntrospectionResponse.parse(response); } catch (Exception ex) { throw new OAuth2IntrospectionException(ex.getMessage(), ex); } } private TokenIntrospectionSuccessResponse castToNimbusSuccess(TokenIntrospectionResponse introspectionResponse) { if (!introspectionResponse.indicatesSuccess()) { ErrorObject errorObject = introspectionResponse.toErrorResponse().getErrorObject(); String message = "Token introspection failed with response " + errorObject.toJSONObject().toJSONString(); this.logger.trace(message); throw new OAuth2IntrospectionException(message); } return (TokenIntrospectionSuccessResponse) introspectionResponse; } private OAuth2AuthenticatedPrincipal convertClaimsSet(TokenIntrospectionSuccessResponse response) { Collection<GrantedAuthority> authorities = new ArrayList<>(); Map<String, Object> claims = response.toJSONObject(); if (response.getAudience() != null) { List<String> audiences = new ArrayList<>(); for (Audience audience : response.getAudience()) { audiences.add(audience.getValue()); } claims.put(OAuth2TokenIntrospectionClaimNames.AUD, Collections.unmodifiableList(audiences)); } if (response.getClientID() != null) { claims.put(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, response.getClientID().getValue()); } if (response.getExpirationTime() != null) { Instant exp = response.getExpirationTime().toInstant(); claims.put(OAuth2TokenIntrospectionClaimNames.EXP, exp); } if (response.getIssueTime() != null) { Instant iat = response.getIssueTime().toInstant(); claims.put(OAuth2TokenIntrospectionClaimNames.IAT, iat); } if (response.getIssuer() != null) { // RFC-7662 page 7 directs users to RFC-7519 for defining the values of these // issuer fields. // https://datatracker.ietf.org/doc/html/rfc7662#page-7 // // RFC-7519 page 9 defines issuer fields as being 'case-sensitive' strings // containing // a 'StringOrURI', which is defined on page 5 as being any string, but // strings containing ':' // should be treated as valid URIs. // https://datatracker.ietf.org/doc/html/rfc7519#section-2 // // It is not defined however as to whether-or-not normalized URIs should be // treated as the same literal // value. It only defines validation itself, so to avoid potential ambiguity // or unwanted side effects that // may be awkward to debug, we do not want to manipulate this value. Previous // versions of Spring Security // would *only* allow valid URLs, which is not what we wish to achieve here. claims.put(OAuth2TokenIntrospectionClaimNames.ISS, response.getIssuer().getValue()); } if (response.getNotBeforeTime() != null) { claims.put(OAuth2TokenIntrospectionClaimNames.NBF, response.getNotBeforeTime().toInstant()); } if (response.getScope() != null) { List<String> scopes = Collections.unmodifiableList(response.getScope().toStringList()); claims.put(OAuth2TokenIntrospectionClaimNames.SCOPE, scopes); for (String scope : scopes) { authorities.add(new SimpleGrantedAuthority(AUTHORITY_PREFIX + scope)); } } return new OAuth2IntrospectionAuthenticatedPrincipal(claims, authorities); } }
11,479
41.835821
114
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/package-info.java
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * OAuth 2.0 Introspection supporting classes and interfaces. */ package org.springframework.security.oauth2.server.resource.introspection;
768
35.619048
75
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/OpaqueTokenIntrospector.java
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.introspection; import java.util.Map; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; /** * A contract for introspecting and verifying an OAuth 2.0 token. * * A typical implementation of this interface will make a request to an * <a href="https://tools.ietf.org/html/rfc7662" target="_blank">OAuth 2.0 Introspection * Endpoint</a> to verify the token and return its attributes, indicating a successful * verification. * * Another sensible implementation of this interface would be to query a backing store of * tokens, for example a distributed cache. * * @author Josh Cummings * @since 5.2 */ @FunctionalInterface public interface OpaqueTokenIntrospector { /** * Introspect and verify the given token, returning its attributes. * * Returning a {@link Map} is indicative that the token is valid. * @param token the token to introspect * @return the token's attributes */ OAuth2AuthenticatedPrincipal introspect(String token); }
1,672
32.46
89
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/SpringReactiveOpaqueTokenIntrospector.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.introspection; import java.net.URI; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Map; import reactor.core.publisher.Mono; import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames; import org.springframework.util.Assert; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.WebClient; /** * A Spring implementation of {@link ReactiveOpaqueTokenIntrospector} that verifies and * introspects a token using the configured * <a href="https://tools.ietf.org/html/rfc7662" target="_blank">OAuth 2.0 Introspection * Endpoint</a>. * * @author Josh Cummings * @since 5.6 */ public class SpringReactiveOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector { private static final String AUTHORITY_PREFIX = "SCOPE_"; private static final ParameterizedTypeReference<Map<String, Object>> STRING_OBJECT_MAP = new ParameterizedTypeReference<Map<String, Object>>() { }; private final URI introspectionUri; private final WebClient webClient; /** * Creates a {@code OpaqueTokenReactiveAuthenticationManager} with the provided * parameters * @param introspectionUri The introspection endpoint uri * @param clientId The client id authorized to introspect * @param clientSecret The client secret for the authorized client */ public SpringReactiveOpaqueTokenIntrospector(String introspectionUri, String clientId, String clientSecret) { Assert.hasText(introspectionUri, "introspectionUri cannot be empty"); Assert.hasText(clientId, "clientId cannot be empty"); Assert.notNull(clientSecret, "clientSecret cannot be null"); this.introspectionUri = URI.create(introspectionUri); this.webClient = WebClient.builder().defaultHeaders((h) -> h.setBasicAuth(clientId, clientSecret)).build(); } /** * Creates a {@code OpaqueTokenReactiveAuthenticationManager} with the provided * parameters * @param introspectionUri The introspection endpoint uri * @param webClient The client for performing the introspection request */ public SpringReactiveOpaqueTokenIntrospector(String introspectionUri, WebClient webClient) { Assert.hasText(introspectionUri, "introspectionUri cannot be null"); Assert.notNull(webClient, "webClient cannot be null"); this.introspectionUri = URI.create(introspectionUri); this.webClient = webClient; } @Override public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) { // @formatter:off return Mono.just(token) .flatMap(this::makeRequest) .flatMap(this::adaptToNimbusResponse) .map(this::convertClaimsSet) .onErrorMap((e) -> !(e instanceof OAuth2IntrospectionException), this::onError); // @formatter:on } private Mono<ClientResponse> makeRequest(String token) { // @formatter:off return this.webClient.post() .uri(this.introspectionUri) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .body(BodyInserters.fromFormData("token", token)) .exchange(); // @formatter:on } private Mono<Map<String, Object>> adaptToNimbusResponse(ClientResponse responseEntity) { if (responseEntity.statusCode() != HttpStatus.OK) { // @formatter:off return responseEntity.bodyToFlux(DataBuffer.class) .map(DataBufferUtils::release) .then(Mono.error(new OAuth2IntrospectionException( "Introspection endpoint responded with " + responseEntity.statusCode())) ); // @formatter:on } // relying solely on the authorization server to validate this token (not checking // 'exp', for example) return responseEntity.bodyToMono(STRING_OBJECT_MAP) .filter((body) -> (boolean) body.compute(OAuth2TokenIntrospectionClaimNames.ACTIVE, (k, v) -> { if (v instanceof String) { return Boolean.parseBoolean((String) v); } if (v instanceof Boolean) { return v; } return false; })).switchIfEmpty(Mono.error(() -> new BadOpaqueTokenException("Provided token isn't active"))); } private OAuth2AuthenticatedPrincipal convertClaimsSet(Map<String, Object> claims) { claims.computeIfPresent(OAuth2TokenIntrospectionClaimNames.AUD, (k, v) -> { if (v instanceof String) { return Collections.singletonList(v); } return v; }); claims.computeIfPresent(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, (k, v) -> v.toString()); claims.computeIfPresent(OAuth2TokenIntrospectionClaimNames.EXP, (k, v) -> Instant.ofEpochSecond(((Number) v).longValue())); claims.computeIfPresent(OAuth2TokenIntrospectionClaimNames.IAT, (k, v) -> Instant.ofEpochSecond(((Number) v).longValue())); // RFC-7662 page 7 directs users to RFC-7519 for defining the values of these // issuer fields. // https://datatracker.ietf.org/doc/html/rfc7662#page-7 // // RFC-7519 page 9 defines issuer fields as being 'case-sensitive' strings // containing // a 'StringOrURI', which is defined on page 5 as being any string, but strings // containing ':' // should be treated as valid URIs. // https://datatracker.ietf.org/doc/html/rfc7519#section-2 // // It is not defined however as to whether-or-not normalized URIs should be // treated as the same literal // value. It only defines validation itself, so to avoid potential ambiguity or // unwanted side effects that // may be awkward to debug, we do not want to manipulate this value. Previous // versions of Spring Security // would *only* allow valid URLs, which is not what we wish to achieve here. claims.computeIfPresent(OAuth2TokenIntrospectionClaimNames.ISS, (k, v) -> v.toString()); claims.computeIfPresent(OAuth2TokenIntrospectionClaimNames.NBF, (k, v) -> Instant.ofEpochSecond(((Number) v).longValue())); Collection<GrantedAuthority> authorities = new ArrayList<>(); claims.computeIfPresent(OAuth2TokenIntrospectionClaimNames.SCOPE, (k, v) -> { if (v instanceof String) { Collection<String> scopes = Arrays.asList(((String) v).split(" ")); for (String scope : scopes) { authorities.add(new SimpleGrantedAuthority(AUTHORITY_PREFIX + scope)); } return scopes; } return v; }); return new OAuth2IntrospectionAuthenticatedPrincipal(claims, authorities); } private OAuth2IntrospectionException onError(Throwable ex) { return new OAuth2IntrospectionException(ex.getMessage(), ex); } }
7,676
39.619048
145
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospector.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.introspection; import java.net.URI; import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import com.nimbusds.oauth2.sdk.ErrorObject; import com.nimbusds.oauth2.sdk.TokenIntrospectionResponse; import com.nimbusds.oauth2.sdk.TokenIntrospectionSuccessResponse; import com.nimbusds.oauth2.sdk.http.HTTPResponse; import com.nimbusds.oauth2.sdk.id.Audience; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import reactor.core.publisher.Mono; import org.springframework.core.io.buffer.DataBuffer; import org.springframework.core.io.buffer.DataBufferUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames; import org.springframework.util.Assert; import org.springframework.web.reactive.function.BodyInserters; import org.springframework.web.reactive.function.client.ClientResponse; import org.springframework.web.reactive.function.client.WebClient; /** * A Nimbus implementation of {@link ReactiveOpaqueTokenIntrospector} that verifies and * introspects a token using the configured * <a href="https://tools.ietf.org/html/rfc7662" target="_blank">OAuth 2.0 Introspection * Endpoint</a>. * * @author Josh Cummings * @since 5.2 */ public class NimbusReactiveOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector { private static final String AUTHORITY_PREFIX = "SCOPE_"; private final Log logger = LogFactory.getLog(getClass()); private final URI introspectionUri; private final WebClient webClient; /** * Creates a {@code OpaqueTokenReactiveAuthenticationManager} with the provided * parameters * @param introspectionUri The introspection endpoint uri * @param clientId The client id authorized to introspect * @param clientSecret The client secret for the authorized client */ public NimbusReactiveOpaqueTokenIntrospector(String introspectionUri, String clientId, String clientSecret) { Assert.hasText(introspectionUri, "introspectionUri cannot be empty"); Assert.hasText(clientId, "clientId cannot be empty"); Assert.notNull(clientSecret, "clientSecret cannot be null"); this.introspectionUri = URI.create(introspectionUri); this.webClient = WebClient.builder().defaultHeaders((h) -> h.setBasicAuth(clientId, clientSecret)).build(); } /** * Creates a {@code OpaqueTokenReactiveAuthenticationManager} with the provided * parameters * @param introspectionUri The introspection endpoint uri * @param webClient The client for performing the introspection request */ public NimbusReactiveOpaqueTokenIntrospector(String introspectionUri, WebClient webClient) { Assert.hasText(introspectionUri, "introspectionUri cannot be null"); Assert.notNull(webClient, "webClient cannot be null"); this.introspectionUri = URI.create(introspectionUri); this.webClient = webClient; } @Override public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) { // @formatter:off return Mono.just(token) .flatMap(this::makeRequest) .flatMap(this::adaptToNimbusResponse) .map(this::parseNimbusResponse) .map(this::castToNimbusSuccess) .doOnNext((response) -> validate(token, response)) .map(this::convertClaimsSet) .onErrorMap((e) -> !(e instanceof OAuth2IntrospectionException), this::onError); // @formatter:on } private Mono<ClientResponse> makeRequest(String token) { // @formatter:off return this.webClient.post() .uri(this.introspectionUri) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) .body(BodyInserters.fromFormData("token", token)) .exchange(); // @formatter:on } private Mono<HTTPResponse> adaptToNimbusResponse(ClientResponse responseEntity) { MediaType contentType = responseEntity.headers().contentType().orElseThrow(() -> { this.logger.trace("Did not receive Content-Type from introspection endpoint in response"); return new OAuth2IntrospectionException( "Introspection endpoint response was invalid, as no Content-Type header was provided"); }); // Nimbus expects JSON, but does not appear to validate this header first. if (!contentType.isCompatibleWith(MediaType.APPLICATION_JSON)) { this.logger.trace("Did not receive JSON-compatible Content-Type from introspection endpoint in response"); throw new OAuth2IntrospectionException("Introspection endpoint response was invalid, as content type '" + contentType + "' is not compatible with JSON"); } HTTPResponse response = new HTTPResponse(responseEntity.statusCode().value()); response.setHeader(HttpHeaders.CONTENT_TYPE, contentType.toString()); if (response.getStatusCode() != HTTPResponse.SC_OK) { this.logger.trace("Introspection endpoint returned non-OK status code"); // @formatter:off return responseEntity.bodyToFlux(DataBuffer.class) .map(DataBufferUtils::release) .then(Mono.error(new OAuth2IntrospectionException( "Introspection endpoint responded with HTTP status code " + response.getStatusCode())) ); // @formatter:on } return responseEntity.bodyToMono(String.class).doOnNext(response::setContent).map((body) -> response); } private TokenIntrospectionResponse parseNimbusResponse(HTTPResponse response) { try { return TokenIntrospectionResponse.parse(response); } catch (Exception ex) { throw new OAuth2IntrospectionException(ex.getMessage(), ex); } } private TokenIntrospectionSuccessResponse castToNimbusSuccess(TokenIntrospectionResponse introspectionResponse) { if (!introspectionResponse.indicatesSuccess()) { ErrorObject errorObject = introspectionResponse.toErrorResponse().getErrorObject(); String message = "Token introspection failed with response " + errorObject.toJSONObject().toJSONString(); this.logger.trace(message); throw new OAuth2IntrospectionException(message); } return (TokenIntrospectionSuccessResponse) introspectionResponse; } private void validate(String token, TokenIntrospectionSuccessResponse response) { // relying solely on the authorization server to validate this token (not checking // 'exp', for example) if (!response.isActive()) { this.logger.trace("Did not validate token since it is inactive"); throw new BadOpaqueTokenException("Provided token isn't active"); } } private OAuth2AuthenticatedPrincipal convertClaimsSet(TokenIntrospectionSuccessResponse response) { Map<String, Object> claims = response.toJSONObject(); Collection<GrantedAuthority> authorities = new ArrayList<>(); if (response.getAudience() != null) { List<String> audiences = new ArrayList<>(); for (Audience audience : response.getAudience()) { audiences.add(audience.getValue()); } claims.put(OAuth2TokenIntrospectionClaimNames.AUD, Collections.unmodifiableList(audiences)); } if (response.getClientID() != null) { claims.put(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, response.getClientID().getValue()); } if (response.getExpirationTime() != null) { Instant exp = response.getExpirationTime().toInstant(); claims.put(OAuth2TokenIntrospectionClaimNames.EXP, exp); } if (response.getIssueTime() != null) { Instant iat = response.getIssueTime().toInstant(); claims.put(OAuth2TokenIntrospectionClaimNames.IAT, iat); } if (response.getIssuer() != null) { // RFC-7662 page 7 directs users to RFC-7519 for defining the values of these // issuer fields. // https://datatracker.ietf.org/doc/html/rfc7662#page-7 // // RFC-7519 page 9 defines issuer fields as being 'case-sensitive' strings // containing // a 'StringOrURI', which is defined on page 5 as being any string, but // strings containing ':' // should be treated as valid URIs. // https://datatracker.ietf.org/doc/html/rfc7519#section-2 // // It is not defined however as to whether-or-not normalized URIs should be // treated as the same literal // value. It only defines validation itself, so to avoid potential ambiguity // or unwanted side effects that // may be awkward to debug, we do not want to manipulate this value. Previous // versions of Spring Security // would *only* allow valid URLs, which is not what we wish to achieve here. claims.put(OAuth2TokenIntrospectionClaimNames.ISS, response.getIssuer().getValue()); } if (response.getNotBeforeTime() != null) { claims.put(OAuth2TokenIntrospectionClaimNames.NBF, response.getNotBeforeTime().toInstant()); } if (response.getScope() != null) { List<String> scopes = Collections.unmodifiableList(response.getScope().toStringList()); claims.put(OAuth2TokenIntrospectionClaimNames.SCOPE, scopes); for (String scope : scopes) { authorities.add(new SimpleGrantedAuthority(AUTHORITY_PREFIX + scope)); } } return new OAuth2IntrospectionAuthenticatedPrincipal(claims, authorities); } private OAuth2IntrospectionException onError(Throwable ex) { return new OAuth2IntrospectionException(ex.getMessage(), ex); } }
9,990
40.456432
114
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/OpaqueTokenAuthenticationConverter.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.introspection; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; /** * Convert a successful introspection result into an authentication result. * * @author Jerome Wacongne &lt;ch4mp@c4-soft.com&gt; * @since 5.8 */ @FunctionalInterface public interface OpaqueTokenAuthenticationConverter { /** * Converts a successful introspection result into an authentication result. * @param introspectedToken the bearer token used to perform token introspection * @param authenticatedPrincipal the result of token introspection * @return an {@link Authentication} instance */ Authentication convert(String introspectedToken, OAuth2AuthenticatedPrincipal authenticatedPrincipal); }
1,457
35.45
103
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/ReactiveOpaqueTokenIntrospector.java
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.introspection; import java.util.Map; import reactor.core.publisher.Mono; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; /** * A contract for introspecting and verifying an OAuth 2.0 token. * * A typical implementation of this interface will make a request to an * <a href="https://tools.ietf.org/html/rfc7662" target="_blank">OAuth 2.0 Introspection * Endpoint</a> to verify the token and return its attributes, indicating a successful * verification. * * Another sensible implementation of this interface would be to query a backing store of * tokens, for example a distributed cache. * * @author Josh Cummings * @since 5.2 */ @FunctionalInterface public interface ReactiveOpaqueTokenIntrospector { /** * Introspect and verify the given token, returning its attributes. * * Returning a {@link Map} is indicative that the token is valid. * @param token the token to introspect * @return the token's attributes */ Mono<OAuth2AuthenticatedPrincipal> introspect(String token); }
1,723
32.153846
89
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/ReactiveOpaqueTokenAuthenticationConverter.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.introspection; import reactor.core.publisher.Mono; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; /** * Convert a successful introspection result into an authentication result. * * @author Jerome Wacongne &lt;ch4mp@c4-soft.com&gt; * @since 5.8 */ @FunctionalInterface public interface ReactiveOpaqueTokenAuthenticationConverter { /** * Converts a successful introspection result into an authentication result. * @param introspectedToken the bearer token used to perform token introspection * @param authenticatedPrincipal the result of token introspection * @return an {@link Authentication} instance */ Mono<Authentication> convert(String introspectedToken, OAuth2AuthenticatedPrincipal authenticatedPrincipal); }
1,508
34.928571
109
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/SpringOpaqueTokenIntrospector.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.introspection; import java.net.URI; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.convert.converter.Converter; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.http.client.support.BasicAuthenticationInterceptor; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames; import org.springframework.util.Assert; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestOperations; import org.springframework.web.client.RestTemplate; /** * A Spring implementation of {@link OpaqueTokenIntrospector} that verifies and * introspects a token using the configured * <a href="https://tools.ietf.org/html/rfc7662" target="_blank">OAuth 2.0 Introspection * Endpoint</a>. * * @author Josh Cummings * @since 5.6 */ public class SpringOpaqueTokenIntrospector implements OpaqueTokenIntrospector { private static final String AUTHORITY_PREFIX = "SCOPE_"; private static final ParameterizedTypeReference<Map<String, Object>> STRING_OBJECT_MAP = new ParameterizedTypeReference<Map<String, Object>>() { }; private final Log logger = LogFactory.getLog(getClass()); private final RestOperations restOperations; private Converter<String, RequestEntity<?>> requestEntityConverter; /** * Creates a {@code OpaqueTokenAuthenticationProvider} with the provided parameters * @param introspectionUri The introspection endpoint uri * @param clientId The client id authorized to introspect * @param clientSecret The client's secret */ public SpringOpaqueTokenIntrospector(String introspectionUri, String clientId, String clientSecret) { Assert.notNull(introspectionUri, "introspectionUri cannot be null"); Assert.notNull(clientId, "clientId cannot be null"); Assert.notNull(clientSecret, "clientSecret cannot be null"); this.requestEntityConverter = this.defaultRequestEntityConverter(URI.create(introspectionUri)); RestTemplate restTemplate = new RestTemplate(); restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor(clientId, clientSecret)); this.restOperations = restTemplate; } /** * Creates a {@code OpaqueTokenAuthenticationProvider} with the provided parameters * * The given {@link RestOperations} should perform its own client authentication * against the introspection endpoint. * @param introspectionUri The introspection endpoint uri * @param restOperations The client for performing the introspection request */ public SpringOpaqueTokenIntrospector(String introspectionUri, RestOperations restOperations) { Assert.notNull(introspectionUri, "introspectionUri cannot be null"); Assert.notNull(restOperations, "restOperations cannot be null"); this.requestEntityConverter = this.defaultRequestEntityConverter(URI.create(introspectionUri)); this.restOperations = restOperations; } private Converter<String, RequestEntity<?>> defaultRequestEntityConverter(URI introspectionUri) { return (token) -> { HttpHeaders headers = requestHeaders(); MultiValueMap<String, String> body = requestBody(token); return new RequestEntity<>(body, headers, HttpMethod.POST, introspectionUri); }; } private HttpHeaders requestHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); return headers; } private MultiValueMap<String, String> requestBody(String token) { MultiValueMap<String, String> body = new LinkedMultiValueMap<>(); body.add("token", token); return body; } @Override public OAuth2AuthenticatedPrincipal introspect(String token) { RequestEntity<?> requestEntity = this.requestEntityConverter.convert(token); if (requestEntity == null) { throw new OAuth2IntrospectionException("requestEntityConverter returned a null entity"); } ResponseEntity<Map<String, Object>> responseEntity = makeRequest(requestEntity); Map<String, Object> claims = adaptToNimbusResponse(responseEntity); return convertClaimsSet(claims); } /** * Sets the {@link Converter} used for converting the OAuth 2.0 access token to a * {@link RequestEntity} representation of the OAuth 2.0 token introspection request. * @param requestEntityConverter the {@link Converter} used for converting to a * {@link RequestEntity} representation of the token introspection request */ public void setRequestEntityConverter(Converter<String, RequestEntity<?>> requestEntityConverter) { Assert.notNull(requestEntityConverter, "requestEntityConverter cannot be null"); this.requestEntityConverter = requestEntityConverter; } private ResponseEntity<Map<String, Object>> makeRequest(RequestEntity<?> requestEntity) { try { return this.restOperations.exchange(requestEntity, STRING_OBJECT_MAP); } catch (Exception ex) { throw new OAuth2IntrospectionException(ex.getMessage(), ex); } } private Map<String, Object> adaptToNimbusResponse(ResponseEntity<Map<String, Object>> responseEntity) { if (responseEntity.getStatusCode() != HttpStatus.OK) { throw new OAuth2IntrospectionException( "Introspection endpoint responded with " + responseEntity.getStatusCode()); } Map<String, Object> claims = responseEntity.getBody(); // relying solely on the authorization server to validate this token (not checking // 'exp', for example) if (claims == null) { return Collections.emptyMap(); } boolean active = (boolean) claims.compute(OAuth2TokenIntrospectionClaimNames.ACTIVE, (k, v) -> { if (v instanceof String) { return Boolean.parseBoolean((String) v); } if (v instanceof Boolean) { return v; } return false; }); if (!active) { this.logger.trace("Did not validate token since it is inactive"); throw new BadOpaqueTokenException("Provided token isn't active"); } return claims; } private OAuth2AuthenticatedPrincipal convertClaimsSet(Map<String, Object> claims) { claims.computeIfPresent(OAuth2TokenIntrospectionClaimNames.AUD, (k, v) -> { if (v instanceof String) { return Collections.singletonList(v); } return v; }); claims.computeIfPresent(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, (k, v) -> v.toString()); claims.computeIfPresent(OAuth2TokenIntrospectionClaimNames.EXP, (k, v) -> Instant.ofEpochSecond(((Number) v).longValue())); claims.computeIfPresent(OAuth2TokenIntrospectionClaimNames.IAT, (k, v) -> Instant.ofEpochSecond(((Number) v).longValue())); // RFC-7662 page 7 directs users to RFC-7519 for defining the values of these // issuer fields. // https://datatracker.ietf.org/doc/html/rfc7662#page-7 // // RFC-7519 page 9 defines issuer fields as being 'case-sensitive' strings // containing // a 'StringOrURI', which is defined on page 5 as being any string, but strings // containing ':' // should be treated as valid URIs. // https://datatracker.ietf.org/doc/html/rfc7519#section-2 // // It is not defined however as to whether-or-not normalized URIs should be // treated as the same literal // value. It only defines validation itself, so to avoid potential ambiguity or // unwanted side effects that // may be awkward to debug, we do not want to manipulate this value. Previous // versions of Spring Security // would *only* allow valid URLs, which is not what we wish to achieve here. claims.computeIfPresent(OAuth2TokenIntrospectionClaimNames.ISS, (k, v) -> v.toString()); claims.computeIfPresent(OAuth2TokenIntrospectionClaimNames.NBF, (k, v) -> Instant.ofEpochSecond(((Number) v).longValue())); Collection<GrantedAuthority> authorities = new ArrayList<>(); claims.computeIfPresent(OAuth2TokenIntrospectionClaimNames.SCOPE, (k, v) -> { if (v instanceof String) { Collection<String> scopes = Arrays.asList(((String) v).split(" ")); for (String scope : scopes) { authorities.add(new SimpleGrantedAuthority(AUTHORITY_PREFIX + scope)); } return scopes; } return v; }); return new OAuth2IntrospectionAuthenticatedPrincipal(claims, authorities); } }
9,460
40.31441
145
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/BadOpaqueTokenException.java
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.introspection; /** * An exception similar to * {@link org.springframework.security.authentication.BadCredentialsException} that * indicates an opaque token that is invalid in some way. * * @author Josh Cummings * @since 5.3 */ public class BadOpaqueTokenException extends OAuth2IntrospectionException { public BadOpaqueTokenException(String message) { super(message); } public BadOpaqueTokenException(String message, Throwable cause) { super(message, cause); } }
1,165
29.684211
83
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/OAuth2IntrospectionException.java
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.introspection; /** * Base exception for all OAuth 2.0 Introspection related errors * * @author Josh Cummings * @since 5.2 */ public class OAuth2IntrospectionException extends RuntimeException { public OAuth2IntrospectionException(String message) { super(message); } public OAuth2IntrospectionException(String message, Throwable cause) { super(message, cause); } }
1,064
28.583333
75
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenReactiveAuthenticationManager.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import reactor.core.publisher.Mono; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.ReactiveAuthenticationManager; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException; import org.springframework.security.oauth2.server.resource.introspection.BadOpaqueTokenException; import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionException; import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenAuthenticationConverter; import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenAuthenticationConverter; import org.springframework.security.oauth2.server.resource.introspection.ReactiveOpaqueTokenIntrospector; import org.springframework.util.Assert; /** * An {@link ReactiveAuthenticationManager} implementation for opaque * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a>s, using an * <a href="https://tools.ietf.org/html/rfc7662" target="_blank">OAuth 2.0 Introspection * Endpoint</a> to check the token's validity and reveal its attributes. * <p> * This {@link ReactiveAuthenticationManager} is responsible for introspecting and * verifying an opaque access token, returning its attributes set as part of the * {@link Authentication} statement. * <p> * A {@link ReactiveOpaqueTokenIntrospector} is responsible for retrieving token * attributes from an authorization server. * <p> * A {@link ReactiveOpaqueTokenAuthenticationConverter} is responsible for turning a * successful introspection result into an {@link Authentication} instance (which may * include mapping {@link GrantedAuthority}s from token attributes or retrieving from * another source). * * @author Josh Cummings * @author Jerome Wacongne &lt;ch4mp@c4-soft.com&gt; * @since 5.2 * @see ReactiveAuthenticationManager */ public class OpaqueTokenReactiveAuthenticationManager implements ReactiveAuthenticationManager { private final ReactiveOpaqueTokenIntrospector introspector; private ReactiveOpaqueTokenAuthenticationConverter authenticationConverter = OpaqueTokenReactiveAuthenticationManager::convert; /** * Creates a {@code OpaqueTokenReactiveAuthenticationManager} with the provided * parameters * @param introspector The {@link ReactiveOpaqueTokenIntrospector} to use */ public OpaqueTokenReactiveAuthenticationManager(ReactiveOpaqueTokenIntrospector introspector) { Assert.notNull(introspector, "introspector cannot be null"); this.introspector = introspector; } /** * Introspect and validate the opaque * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a> and then delegates {@link Authentication} instantiation to * {@link ReactiveOpaqueTokenAuthenticationConverter}. * <p> * If created Authentication is instance of {@link AbstractAuthenticationToken} and * details are null, then introspection result details are used. * @param authentication the authentication request object. * @return A successful authentication */ @Override public Mono<Authentication> authenticate(Authentication authentication) { // @formatter:off return Mono.justOrEmpty(authentication) .filter(BearerTokenAuthenticationToken.class::isInstance) .cast(BearerTokenAuthenticationToken.class) .map(BearerTokenAuthenticationToken::getToken) .flatMap(this::authenticate); // @formatter:on } private Mono<Authentication> authenticate(String token) { // @formatter:off return this.introspector.introspect(token) .flatMap((principal) -> this.authenticationConverter.convert(token, principal)) .onErrorMap(OAuth2IntrospectionException.class, this::onError); // @formatter:on } private AuthenticationException onError(OAuth2IntrospectionException ex) { if (ex instanceof BadOpaqueTokenException) { return new InvalidBearerTokenException(ex.getMessage(), ex); } return new AuthenticationServiceException(ex.getMessage(), ex); } /** * Default {@link ReactiveOpaqueTokenAuthenticationConverter}. * @param introspectedToken the bearer string that was successfully introspected * @param authenticatedPrincipal the successful introspection output * @return an async wrapper of default {@link OpaqueTokenAuthenticationConverter} * result */ static Mono<Authentication> convert(String introspectedToken, OAuth2AuthenticatedPrincipal authenticatedPrincipal) { return Mono.just(OpaqueTokenAuthenticationProvider.convert(introspectedToken, authenticatedPrincipal)); } /** * Provide with a custom bean to turn successful introspection result into an * {@link Authentication} instance of your choice. By default, * {@link BearerTokenAuthentication} will be built. * @param authenticationConverter the converter to use * @since 5.8 */ public void setAuthenticationConverter(ReactiveOpaqueTokenAuthenticationConverter authenticationConverter) { Assert.notNull(authenticationConverter, "authenticationConverter cannot be null"); this.authenticationConverter = authenticationConverter; } }
6,213
44.357664
128
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/package-info.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * OAuth 2.0 Resource Server {@code Authentication}s and supporting classes and * interfaces. */ package org.springframework.security.oauth2.server.resource.authentication;
802
35.5
79
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerAuthenticationManagerResolver.java
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; import com.nimbusds.jwt.JWTParser; import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.convert.converter.Converter; import org.springframework.core.log.LogMessage; import org.springframework.lang.NonNull; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManagerResolver; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.JwtDecoders; import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException; import org.springframework.util.Assert; /** * An implementation of {@link AuthenticationManagerResolver} that resolves a JWT-based * {@link AuthenticationManager} based on the <a href= * "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a> in * a signed JWT (JWS). * * To use, this class must be able to determine whether or not the `iss` claim is trusted. * Recall that anyone can stand up an authorization server and issue valid tokens to a * resource server. The simplest way to achieve this is to supply a list of trusted * issuers in the constructor. * * This class derives the Issuer from the `iss` claim found in the * {@link HttpServletRequest}'s * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a>. * * @author Josh Cummings * @since 5.3 */ public final class JwtIssuerAuthenticationManagerResolver implements AuthenticationManagerResolver<HttpServletRequest> { private final AuthenticationManager authenticationManager; /** * Construct a {@link JwtIssuerAuthenticationManagerResolver} using the provided * parameters * @param trustedIssuers a list of trusted issuers */ public JwtIssuerAuthenticationManagerResolver(String... trustedIssuers) { this(Arrays.asList(trustedIssuers)); } /** * Construct a {@link JwtIssuerAuthenticationManagerResolver} using the provided * parameters * @param trustedIssuers a list of trusted issuers */ public JwtIssuerAuthenticationManagerResolver(Collection<String> trustedIssuers) { Assert.notEmpty(trustedIssuers, "trustedIssuers cannot be empty"); this.authenticationManager = new ResolvingAuthenticationManager( new TrustedIssuerJwtAuthenticationManagerResolver( Collections.unmodifiableCollection(trustedIssuers)::contains)); } /** * Construct a {@link JwtIssuerAuthenticationManagerResolver} using the provided * parameters * * Note that the {@link AuthenticationManagerResolver} provided in this constructor * will need to verify that the issuer is trusted. This should be done via an * allowlist. * * One way to achieve this is with a {@link Map} where the keys are the known issuers: * <pre> * Map&lt;String, AuthenticationManager&gt; authenticationManagers = new HashMap&lt;&gt;(); * authenticationManagers.put("https://issuerOne.example.org", managerOne); * authenticationManagers.put("https://issuerTwo.example.org", managerTwo); * JwtAuthenticationManagerResolver resolver = new JwtAuthenticationManagerResolver * (authenticationManagers::get); * </pre> * * The keys in the {@link Map} are the allowed issuers. * @param issuerAuthenticationManagerResolver a strategy for resolving the * {@link AuthenticationManager} by the issuer */ public JwtIssuerAuthenticationManagerResolver( AuthenticationManagerResolver<String> issuerAuthenticationManagerResolver) { Assert.notNull(issuerAuthenticationManagerResolver, "issuerAuthenticationManagerResolver cannot be null"); this.authenticationManager = new ResolvingAuthenticationManager(issuerAuthenticationManagerResolver); } /** * Return an {@link AuthenticationManager} based off of the `iss` claim found in the * request's bearer token * @throws OAuth2AuthenticationException if the bearer token is malformed or an * {@link AuthenticationManager} can't be derived from the issuer */ @Override public AuthenticationManager resolve(HttpServletRequest request) { return this.authenticationManager; } private static class ResolvingAuthenticationManager implements AuthenticationManager { private final Converter<BearerTokenAuthenticationToken, String> issuerConverter = new JwtClaimIssuerConverter(); private final AuthenticationManagerResolver<String> issuerAuthenticationManagerResolver; ResolvingAuthenticationManager(AuthenticationManagerResolver<String> issuerAuthenticationManagerResolver) { this.issuerAuthenticationManagerResolver = issuerAuthenticationManagerResolver; } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Assert.isTrue(authentication instanceof BearerTokenAuthenticationToken, "Authentication must be of type BearerTokenAuthenticationToken"); BearerTokenAuthenticationToken token = (BearerTokenAuthenticationToken) authentication; String issuer = this.issuerConverter.convert(token); AuthenticationManager authenticationManager = this.issuerAuthenticationManagerResolver.resolve(issuer); if (authenticationManager == null) { throw new InvalidBearerTokenException("Invalid issuer"); } return authenticationManager.authenticate(authentication); } } private static class JwtClaimIssuerConverter implements Converter<BearerTokenAuthenticationToken, String> { @Override public String convert(@NonNull BearerTokenAuthenticationToken authentication) { String token = authentication.getToken(); try { String issuer = JWTParser.parse(token).getJWTClaimsSet().getIssuer(); if (issuer != null) { return issuer; } } catch (Exception ex) { throw new InvalidBearerTokenException(ex.getMessage(), ex); } throw new InvalidBearerTokenException("Missing issuer"); } } static class TrustedIssuerJwtAuthenticationManagerResolver implements AuthenticationManagerResolver<String> { private final Log logger = LogFactory.getLog(getClass()); private final Map<String, AuthenticationManager> authenticationManagers = new ConcurrentHashMap<>(); private final Predicate<String> trustedIssuer; TrustedIssuerJwtAuthenticationManagerResolver(Predicate<String> trustedIssuer) { this.trustedIssuer = trustedIssuer; } @Override public AuthenticationManager resolve(String issuer) { if (this.trustedIssuer.test(issuer)) { AuthenticationManager authenticationManager = this.authenticationManagers.computeIfAbsent(issuer, (k) -> { this.logger.debug("Constructing AuthenticationManager"); JwtDecoder jwtDecoder = JwtDecoders.fromIssuerLocation(issuer); return new JwtAuthenticationProvider(jwtDecoder)::authenticate; }); this.logger.debug(LogMessage.format("Resolved AuthenticationManager for issuer '%s'", issuer)); return authenticationManager; } else { this.logger.debug("Did not resolve AuthenticationManager since issuer is not trusted"); } return null; } } }
8,206
39.428571
120
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/BearerTokenAuthenticationToken.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Collections; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.SpringSecurityCoreVersion; import org.springframework.security.oauth2.server.resource.web.authentication.BearerTokenAuthenticationFilter; import org.springframework.util.Assert; /** * An {@link Authentication} that contains a * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a>. * * Used by {@link BearerTokenAuthenticationFilter} to prepare an authentication attempt * and supported by {@link JwtAuthenticationProvider}. * * @author Josh Cummings * @since 5.1 */ public class BearerTokenAuthenticationToken extends AbstractAuthenticationToken { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; private final String token; /** * Create a {@code BearerTokenAuthenticationToken} using the provided parameter(s) * @param token - the bearer token */ public BearerTokenAuthenticationToken(String token) { super(Collections.emptyList()); Assert.hasText(token, "token cannot be empty"); this.token = token; } /** * Get the * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a> * @return the token that proves the caller's authority to perform the * {@link jakarta.servlet.http.HttpServletRequest} */ public String getToken() { return this.token; } @Override public Object getCredentials() { return this.getToken(); } @Override public Object getPrincipal() { return this.getToken(); } }
2,376
30.276316
110
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/BearerTokenAuthentication.java
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.SpringSecurityCoreVersion; import org.springframework.security.core.Transient; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import org.springframework.util.Assert; /** * An {@link org.springframework.security.core.Authentication} token that represents a * successful authentication as obtained through a bearer token. * * @author Josh Cummings * @since 5.2 */ @Transient public class BearerTokenAuthentication extends AbstractOAuth2TokenAuthenticationToken<OAuth2AccessToken> { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; private final Map<String, Object> attributes; /** * Constructs a {@link BearerTokenAuthentication} with the provided arguments * @param principal The OAuth 2.0 attributes * @param credentials The verified token * @param authorities The authorities associated with the given token */ public BearerTokenAuthentication(OAuth2AuthenticatedPrincipal principal, OAuth2AccessToken credentials, Collection<? extends GrantedAuthority> authorities) { super(credentials, principal, credentials, authorities); Assert.isTrue(credentials.getTokenType() == OAuth2AccessToken.TokenType.BEARER, "credentials must be a bearer token"); this.attributes = Collections.unmodifiableMap(new LinkedHashMap<>(principal.getAttributes())); setAuthenticated(true); } @Override public Map<String, Object> getTokenAttributes() { return this.attributes; } }
2,456
36.227273
106
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtBearerTokenAuthenticationConverter.java
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Collection; import java.util.Map; import org.springframework.core.convert.converter.Converter; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.core.DefaultOAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.jwt.Jwt; /** * A {@link Converter} that takes a {@link Jwt} and converts it into a * {@link BearerTokenAuthentication}. * * In the process, it will attempt to parse either the "scope" or "scp" attribute, * whichever it finds first. * * It's not intended that this implementation be configured since it is simply an adapter. * If you are using, for example, a custom {@link JwtGrantedAuthoritiesConverter}, then * it's recommended that you simply create your own {@link Converter} that delegates to * your custom {@link JwtGrantedAuthoritiesConverter} and instantiates the appropriate * {@link BearerTokenAuthentication}. * * @author Josh Cummings * @since 5.2 */ public final class JwtBearerTokenAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> { private final JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter(); @Override public AbstractAuthenticationToken convert(Jwt jwt) { OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt()); Map<String, Object> attributes = jwt.getClaims(); AbstractAuthenticationToken token = this.jwtAuthenticationConverter.convert(jwt); Collection<GrantedAuthority> authorities = token.getAuthorities(); OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(attributes, authorities); return new BearerTokenAuthentication(principal, accessToken, authorities); } }
2,745
43.290323
113
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtAuthenticationConverter.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import org.springframework.core.convert.converter.Converter; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtClaimNames; import org.springframework.util.Assert; /** * Reactive version of {@link JwtAuthenticationConverter} for converting a {@link Jwt} to * a {@link AbstractAuthenticationToken Mono&lt;AbstractAuthenticationToken&gt;}. * * @author Eric Deandrea * @author Marcus Kainth * @since 5.2 */ public final class ReactiveJwtAuthenticationConverter implements Converter<Jwt, Mono<AbstractAuthenticationToken>> { private Converter<Jwt, Flux<GrantedAuthority>> jwtGrantedAuthoritiesConverter = new ReactiveJwtGrantedAuthoritiesConverterAdapter( new JwtGrantedAuthoritiesConverter()); private String principalClaimName = JwtClaimNames.SUB; @Override public Mono<AbstractAuthenticationToken> convert(Jwt jwt) { // @formatter:off return this.jwtGrantedAuthoritiesConverter.convert(jwt) .collectList() .map((authorities) -> { String principalName = jwt.getClaimAsString(this.principalClaimName); return new JwtAuthenticationToken(jwt, authorities, principalName); }); // @formatter:on } /** * Sets the {@link Converter Converter&lt;Jwt, Flux&lt;GrantedAuthority&gt;&gt;} to * use. Defaults to a reactive {@link JwtGrantedAuthoritiesConverter}. * @param jwtGrantedAuthoritiesConverter The converter * @see JwtGrantedAuthoritiesConverter */ public void setJwtGrantedAuthoritiesConverter( Converter<Jwt, Flux<GrantedAuthority>> jwtGrantedAuthoritiesConverter) { Assert.notNull(jwtGrantedAuthoritiesConverter, "jwtGrantedAuthoritiesConverter cannot be null"); this.jwtGrantedAuthoritiesConverter = jwtGrantedAuthoritiesConverter; } /** * Sets the principal claim name. Defaults to {@link JwtClaimNames#SUB}. * @param principalClaimName The principal claim name * @since 6.1 */ public void setPrincipalClaimName(String principalClaimName) { Assert.hasText(principalClaimName, "principalClaimName cannot be empty"); this.principalClaimName = principalClaimName; } }
3,011
37.126582
131
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtIssuerReactiveAuthenticationManagerResolver.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; import com.nimbusds.jwt.JWTParser; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import org.springframework.core.convert.converter.Converter; import org.springframework.lang.NonNull; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.ReactiveAuthenticationManager; import org.springframework.security.authentication.ReactiveAuthenticationManagerResolver; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.jwt.ReactiveJwtDecoders; import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException; import org.springframework.util.Assert; import org.springframework.web.server.ServerWebExchange; /** * An implementation of {@link ReactiveAuthenticationManagerResolver} that resolves a * JWT-based {@link ReactiveAuthenticationManager} based on the <a href= * "https://openid.net/specs/openid-connect-core-1_0.html#IssuerIdentifier">Issuer</a> in * a signed JWT (JWS). * * To use, this class must be able to determine whether or not the `iss` claim is trusted. * Recall that anyone can stand up an authorization server and issue valid tokens to a * resource server. The simplest way to achieve this is to supply a list of trusted * issuers in the constructor. * * This class derives the Issuer from the `iss` claim found in the * {@link ServerWebExchange}'s * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a>. * * @author Josh Cummings * @author Roman Matiushchenko * @since 5.3 */ public final class JwtIssuerReactiveAuthenticationManagerResolver implements ReactiveAuthenticationManagerResolver<ServerWebExchange> { private final ReactiveAuthenticationManager authenticationManager; /** * Construct a {@link JwtIssuerReactiveAuthenticationManagerResolver} using the * provided parameters * @param trustedIssuers a list of trusted issuers */ public JwtIssuerReactiveAuthenticationManagerResolver(String... trustedIssuers) { this(Arrays.asList(trustedIssuers)); } /** * Construct a {@link JwtIssuerReactiveAuthenticationManagerResolver} using the * provided parameters * @param trustedIssuers a collection of trusted issuers */ public JwtIssuerReactiveAuthenticationManagerResolver(Collection<String> trustedIssuers) { Assert.notEmpty(trustedIssuers, "trustedIssuers cannot be empty"); this.authenticationManager = new ResolvingAuthenticationManager( new TrustedIssuerJwtAuthenticationManagerResolver(new ArrayList<>(trustedIssuers)::contains)); } /** * Construct a {@link JwtIssuerReactiveAuthenticationManagerResolver} using the * provided parameters * * Note that the {@link ReactiveAuthenticationManagerResolver} provided in this * constructor will need to verify that the issuer is trusted. This should be done via * an allowed list of issuers. * * One way to achieve this is with a {@link Map} where the keys are the known issuers: * <pre> * Map&lt;String, ReactiveAuthenticationManager&gt; authenticationManagers = new HashMap&lt;&gt;(); * authenticationManagers.put("https://issuerOne.example.org", managerOne); * authenticationManagers.put("https://issuerTwo.example.org", managerTwo); * JwtIssuerReactiveAuthenticationManagerResolver resolver = new JwtIssuerReactiveAuthenticationManagerResolver * ((issuer) -&gt; Mono.justOrEmpty(authenticationManagers.get(issuer)); * </pre> * * The keys in the {@link Map} are the trusted issuers. * @param issuerAuthenticationManagerResolver a strategy for resolving the * {@link ReactiveAuthenticationManager} by the issuer */ public JwtIssuerReactiveAuthenticationManagerResolver( ReactiveAuthenticationManagerResolver<String> issuerAuthenticationManagerResolver) { Assert.notNull(issuerAuthenticationManagerResolver, "issuerAuthenticationManagerResolver cannot be null"); this.authenticationManager = new ResolvingAuthenticationManager(issuerAuthenticationManagerResolver); } /** * Return an {@link AuthenticationManager} based off of the `iss` claim found in the * request's bearer token * @throws OAuth2AuthenticationException if the bearer token is malformed or an * {@link ReactiveAuthenticationManager} can't be derived from the issuer */ @Override public Mono<ReactiveAuthenticationManager> resolve(ServerWebExchange exchange) { return Mono.just(this.authenticationManager); } private static class ResolvingAuthenticationManager implements ReactiveAuthenticationManager { private final Converter<BearerTokenAuthenticationToken, Mono<String>> issuerConverter = new JwtClaimIssuerConverter(); private final ReactiveAuthenticationManagerResolver<String> issuerAuthenticationManagerResolver; ResolvingAuthenticationManager( ReactiveAuthenticationManagerResolver<String> issuerAuthenticationManagerResolver) { this.issuerAuthenticationManagerResolver = issuerAuthenticationManagerResolver; } @Override public Mono<Authentication> authenticate(Authentication authentication) { Assert.isTrue(authentication instanceof BearerTokenAuthenticationToken, "Authentication must be of type BearerTokenAuthenticationToken"); BearerTokenAuthenticationToken token = (BearerTokenAuthenticationToken) authentication; return this.issuerConverter.convert(token) .flatMap((issuer) -> this.issuerAuthenticationManagerResolver.resolve(issuer).switchIfEmpty( Mono.error(() -> new InvalidBearerTokenException("Invalid issuer " + issuer)))) .flatMap((manager) -> manager.authenticate(authentication)); } } private static class JwtClaimIssuerConverter implements Converter<BearerTokenAuthenticationToken, Mono<String>> { @Override public Mono<String> convert(@NonNull BearerTokenAuthenticationToken token) { try { String issuer = JWTParser.parse(token.getToken()).getJWTClaimsSet().getIssuer(); if (issuer == null) { throw new InvalidBearerTokenException("Missing issuer"); } return Mono.just(issuer); } catch (Exception ex) { return Mono.error(() -> new InvalidBearerTokenException(ex.getMessage(), ex)); } } } static class TrustedIssuerJwtAuthenticationManagerResolver implements ReactiveAuthenticationManagerResolver<String> { private final Map<String, Mono<ReactiveAuthenticationManager>> authenticationManagers = new ConcurrentHashMap<>(); private final Predicate<String> trustedIssuer; TrustedIssuerJwtAuthenticationManagerResolver(Predicate<String> trustedIssuer) { this.trustedIssuer = trustedIssuer; } @Override public Mono<ReactiveAuthenticationManager> resolve(String issuer) { if (!this.trustedIssuer.test(issuer)) { return Mono.empty(); } // @formatter:off return this.authenticationManagers.computeIfAbsent(issuer, (k) -> Mono.<ReactiveAuthenticationManager>fromCallable(() -> new JwtReactiveAuthenticationManager(ReactiveJwtDecoders.fromIssuerLocation(k))) .subscribeOn(Schedulers.boundedElastic()) .cache((manager) -> Duration.ofMillis(Long.MAX_VALUE), (ex) -> Duration.ZERO, () -> Duration.ZERO) ); // @formatter:on } } }
8,206
40.659898
147
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProvider.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.time.Instant; import java.util.Collection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal; import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames; import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException; import org.springframework.security.oauth2.server.resource.introspection.BadOpaqueTokenException; import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionException; import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenAuthenticationConverter; import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector; import org.springframework.util.Assert; /** * An {@link AuthenticationProvider} implementation for opaque * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a>s, using an * <a href="https://tools.ietf.org/html/rfc7662" target="_blank">OAuth 2.0 Introspection * Endpoint</a> to check the token's validity and reveal its attributes. * <p> * This {@link AuthenticationProvider} is responsible for introspecting and verifying an * opaque access token, returning its attributes set as part of the {@link Authentication} * statement. * <p> * Scopes are translated into {@link GrantedAuthority}s according to the following * algorithm: * <ol> * <li>If there is a "scope" attribute, then convert to a {@link Collection} of * {@link String}s. * <li>Take the resulting {@link Collection} and prepend the "SCOPE_" keyword to each * element, adding as {@link GrantedAuthority}s. * </ol> * <p> * An {@link OpaqueTokenIntrospector} is responsible for retrieving token attributes from * an authorization server. * <p> * An {@link OpaqueTokenAuthenticationConverter} is responsible for turning a successful * introspection result into an {@link Authentication} instance (which may include mapping * {@link GrantedAuthority}s from token attributes or retrieving from another source). * * @author Josh Cummings * @author Jerome Wacongne &lt;ch4mp@c4-soft.com&gt; * @since 5.2 * @see AuthenticationProvider */ public final class OpaqueTokenAuthenticationProvider implements AuthenticationProvider { private final Log logger = LogFactory.getLog(getClass()); private final OpaqueTokenIntrospector introspector; private OpaqueTokenAuthenticationConverter authenticationConverter = OpaqueTokenAuthenticationProvider::convert; /** * Creates a {@code OpaqueTokenAuthenticationProvider} with the provided parameters * @param introspector The {@link OpaqueTokenIntrospector} to use */ public OpaqueTokenAuthenticationProvider(OpaqueTokenIntrospector introspector) { Assert.notNull(introspector, "introspector cannot be null"); this.introspector = introspector; } /** * Introspect and validate the opaque * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a> and then delegates {@link Authentication} instantiation to * {@link OpaqueTokenAuthenticationConverter}. * <p> * If created Authentication is instance of {@link AbstractAuthenticationToken} and * details are null, then introspection result details are used. * @param authentication the authentication request object. * @return A successful authentication * @throws AuthenticationException if authentication failed for some reason */ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (!(authentication instanceof BearerTokenAuthenticationToken bearer)) { return null; } OAuth2AuthenticatedPrincipal principal = getOAuth2AuthenticatedPrincipal(bearer); Authentication result = this.authenticationConverter.convert(bearer.getToken(), principal); if (result == null) { return null; } if (AbstractAuthenticationToken.class.isAssignableFrom(result.getClass())) { final AbstractAuthenticationToken auth = (AbstractAuthenticationToken) result; if (auth.getDetails() == null) { auth.setDetails(bearer.getDetails()); } } this.logger.debug("Authenticated token"); return result; } private OAuth2AuthenticatedPrincipal getOAuth2AuthenticatedPrincipal(BearerTokenAuthenticationToken bearer) { try { return this.introspector.introspect(bearer.getToken()); } catch (BadOpaqueTokenException failed) { this.logger.debug("Failed to authenticate since token was invalid"); throw new InvalidBearerTokenException(failed.getMessage(), failed); } catch (OAuth2IntrospectionException failed) { throw new AuthenticationServiceException(failed.getMessage(), failed); } } @Override public boolean supports(Class<?> authentication) { return BearerTokenAuthenticationToken.class.isAssignableFrom(authentication); } /** * Default {@link OpaqueTokenAuthenticationConverter}. * @param introspectedToken the bearer string that was successfully introspected * @param authenticatedPrincipal the successful introspection output * @return a {@link BearerTokenAuthentication} */ static BearerTokenAuthentication convert(String introspectedToken, OAuth2AuthenticatedPrincipal authenticatedPrincipal) { Instant iat = authenticatedPrincipal.getAttribute(OAuth2TokenIntrospectionClaimNames.IAT); Instant exp = authenticatedPrincipal.getAttribute(OAuth2TokenIntrospectionClaimNames.EXP); OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, introspectedToken, iat, exp); return new BearerTokenAuthentication(authenticatedPrincipal, accessToken, authenticatedPrincipal.getAuthorities()); } /** * Provide with a custom bean to turn successful introspection result into an * {@link Authentication} instance of your choice. By default, * {@link BearerTokenAuthentication} will be built. * @param authenticationConverter the converter to use * @since 5.8 */ public void setAuthenticationConverter(OpaqueTokenAuthenticationConverter authenticationConverter) { Assert.notNull(authenticationConverter, "authenticationConverter cannot be null"); this.authenticationConverter = authenticationConverter; } }
7,458
43.136095
113
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationProvider.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Collection; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.convert.converter.Converter; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.jwt.BadJwtException; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.JwtException; import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException; import org.springframework.util.Assert; /** * An {@link AuthenticationProvider} implementation of the {@link Jwt}-encoded * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a>s for protecting OAuth 2.0 Resource Servers. * <p> * <p> * This {@link AuthenticationProvider} is responsible for decoding and verifying a * {@link Jwt}-encoded access token, returning its claims set as part of the * {@link Authentication} statement. * <p> * <p> * Scopes are translated into {@link GrantedAuthority}s according to the following * algorithm: * * 1. If there is a "scope" or "scp" attribute, then if a {@link String}, then split by * spaces and return, or if a {@link Collection}, then simply return 2. Take the resulting * {@link Collection} of {@link String}s and prepend the "SCOPE_" keyword, adding as * {@link GrantedAuthority}s. * * @author Josh Cummings * @author Joe Grandja * @author Jerome Wacongne ch4mp&#64;c4-soft.com * @since 5.1 * @see AuthenticationProvider * @see JwtDecoder */ public final class JwtAuthenticationProvider implements AuthenticationProvider { private final Log logger = LogFactory.getLog(getClass()); private final JwtDecoder jwtDecoder; private Converter<Jwt, ? extends AbstractAuthenticationToken> jwtAuthenticationConverter = new JwtAuthenticationConverter(); public JwtAuthenticationProvider(JwtDecoder jwtDecoder) { Assert.notNull(jwtDecoder, "jwtDecoder cannot be null"); this.jwtDecoder = jwtDecoder; } /** * Decode and validate the * <a href="https://tools.ietf.org/html/rfc6750#section-1.2" target="_blank">Bearer * Token</a>. * @param authentication the authentication request object. * @return A successful authentication * @throws AuthenticationException if authentication failed for some reason */ @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { BearerTokenAuthenticationToken bearer = (BearerTokenAuthenticationToken) authentication; Jwt jwt = getJwt(bearer); AbstractAuthenticationToken token = this.jwtAuthenticationConverter.convert(jwt); if (token.getDetails() == null) { token.setDetails(bearer.getDetails()); } this.logger.debug("Authenticated token"); return token; } private Jwt getJwt(BearerTokenAuthenticationToken bearer) { try { return this.jwtDecoder.decode(bearer.getToken()); } catch (BadJwtException failed) { this.logger.debug("Failed to authenticate since the JWT was invalid"); throw new InvalidBearerTokenException(failed.getMessage(), failed); } catch (JwtException failed) { throw new AuthenticationServiceException(failed.getMessage(), failed); } } @Override public boolean supports(Class<?> authentication) { return BearerTokenAuthenticationToken.class.isAssignableFrom(authentication); } public void setJwtAuthenticationConverter( Converter<Jwt, ? extends AbstractAuthenticationToken> jwtAuthenticationConverter) { Assert.notNull(jwtAuthenticationConverter, "jwtAuthenticationConverter cannot be null"); this.jwtAuthenticationConverter = jwtAuthenticationConverter; } }
4,774
38.139344
125
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtAuthenticationConverterAdapter.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import reactor.core.publisher.Mono; import org.springframework.core.convert.converter.Converter; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.util.Assert; /** * A reactive {@link Converter} for adapting a non-blocking imperative {@link Converter} * * @author Josh Cummings * @since 5.1.1 */ public class ReactiveJwtAuthenticationConverterAdapter implements Converter<Jwt, Mono<AbstractAuthenticationToken>> { private final Converter<Jwt, AbstractAuthenticationToken> delegate; public ReactiveJwtAuthenticationConverterAdapter(Converter<Jwt, AbstractAuthenticationToken> delegate) { Assert.notNull(delegate, "delegate cannot be null"); this.delegate = delegate; } @Override public final Mono<AbstractAuthenticationToken> convert(Jwt jwt) { return Mono.just(jwt).map(this.delegate::convert); } }
1,631
33.723404
117
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/ReactiveJwtGrantedAuthoritiesConverterAdapter.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Collection; import reactor.core.publisher.Flux; import org.springframework.core.convert.converter.Converter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.util.Assert; /** * Adapts a {@link Converter Converter&lt;Jwt, Collection&lt;GrantedAuthority&gt;&gt;} to * a {@link Converter Converter&lt;Jwt, Flux&lt;GrantedAuthority&gt;&gt;}. * <p> * Make sure the {@link Converter Converter&lt;Jwt, * Collection&lt;GrantedAuthority&gt;&gt;} being adapted is non-blocking. * </p> * * @author Eric Deandrea * @since 5.2 * @see JwtGrantedAuthoritiesConverter */ public final class ReactiveJwtGrantedAuthoritiesConverterAdapter implements Converter<Jwt, Flux<GrantedAuthority>> { private final Converter<Jwt, Collection<GrantedAuthority>> grantedAuthoritiesConverter; public ReactiveJwtGrantedAuthoritiesConverterAdapter( Converter<Jwt, Collection<GrantedAuthority>> grantedAuthoritiesConverter) { Assert.notNull(grantedAuthoritiesConverter, "grantedAuthoritiesConverter cannot be null"); this.grantedAuthoritiesConverter = grantedAuthoritiesConverter; } @Override public Flux<GrantedAuthority> convert(Jwt jwt) { return Flux.fromIterable(this.grantedAuthoritiesConverter.convert(jwt)); } }
2,022
35.125
116
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/AbstractOAuth2TokenAuthenticationToken.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Collection; import java.util.Map; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.SpringSecurityCoreVersion; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.oauth2.core.OAuth2Token; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.util.Assert; /** * Base class for {@link AbstractAuthenticationToken} implementations that expose common * attributes between different OAuth 2.0 Access Token Formats. * * <p> * For example, a {@link Jwt} could expose its {@link Jwt#getClaims() claims} via * {@link #getTokenAttributes()} or an &quot;Introspected&quot; OAuth 2.0 Access Token * could expose the attributes of the Introspection Response via * {@link #getTokenAttributes()}. * * @author Joe Grandja * @since 5.1 * @see OAuth2AccessToken * @see Jwt * @see <a target="_blank" href="https://tools.ietf.org/search/rfc7662#section-2.2">2.2 * Introspection Response</a> */ public abstract class AbstractOAuth2TokenAuthenticationToken<T extends OAuth2Token> extends AbstractAuthenticationToken { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; private Object principal; private Object credentials; private T token; /** * Sub-class constructor. */ protected AbstractOAuth2TokenAuthenticationToken(T token) { this(token, null); } /** * Sub-class constructor. * @param authorities the authorities assigned to the Access Token */ protected AbstractOAuth2TokenAuthenticationToken(T token, Collection<? extends GrantedAuthority> authorities) { this(token, token, token, authorities); } protected AbstractOAuth2TokenAuthenticationToken(T token, Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) { super(authorities); Assert.notNull(token, "token cannot be null"); Assert.notNull(principal, "principal cannot be null"); this.principal = principal; this.credentials = credentials; this.token = token; } @Override public Object getPrincipal() { return this.principal; } @Override public Object getCredentials() { return this.credentials; } /** * Get the token bound to this {@link Authentication}. */ public final T getToken() { return this.token; } /** * Returns the attributes of the access token. * @return a {@code Map} of the attributes in the access token. */ public abstract Map<String, Object> getTokenAttributes(); }
3,382
29.477477
112
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationToken.java
/* * Copyright 2002-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Collection; import java.util.Map; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.SpringSecurityCoreVersion; import org.springframework.security.core.Transient; import org.springframework.security.oauth2.jwt.Jwt; /** * An implementation of an {@link AbstractOAuth2TokenAuthenticationToken} representing a * {@link Jwt} {@code Authentication}. * * @author Joe Grandja * @since 5.1 * @see AbstractOAuth2TokenAuthenticationToken * @see Jwt */ @Transient public class JwtAuthenticationToken extends AbstractOAuth2TokenAuthenticationToken<Jwt> { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; private final String name; /** * Constructs a {@code JwtAuthenticationToken} using the provided parameters. * @param jwt the JWT */ public JwtAuthenticationToken(Jwt jwt) { super(jwt); this.name = jwt.getSubject(); } /** * Constructs a {@code JwtAuthenticationToken} using the provided parameters. * @param jwt the JWT * @param authorities the authorities assigned to the JWT */ public JwtAuthenticationToken(Jwt jwt, Collection<? extends GrantedAuthority> authorities) { super(jwt, authorities); this.setAuthenticated(true); this.name = jwt.getSubject(); } /** * Constructs a {@code JwtAuthenticationToken} using the provided parameters. * @param jwt the JWT * @param authorities the authorities assigned to the JWT * @param name the principal name */ public JwtAuthenticationToken(Jwt jwt, Collection<? extends GrantedAuthority> authorities, String name) { super(jwt, authorities); this.setAuthenticated(true); this.name = name; } @Override public Map<String, Object> getTokenAttributes() { return this.getToken().getClaims(); } /** * The principal name which is, by default, the {@link Jwt}'s subject */ @Override public String getName() { return this.name; } }
2,650
28.786517
106
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtReactiveAuthenticationManager.java
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import reactor.core.publisher.Mono; import org.springframework.core.convert.converter.Converter; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.ReactiveAuthenticationManager; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.oauth2.jwt.BadJwtException; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtException; import org.springframework.security.oauth2.jwt.ReactiveJwtDecoder; import org.springframework.security.oauth2.server.resource.InvalidBearerTokenException; import org.springframework.util.Assert; /** * A {@link ReactiveAuthenticationManager} for Jwt tokens. * * @author Rob Winch * @since 5.1 */ public final class JwtReactiveAuthenticationManager implements ReactiveAuthenticationManager { private final ReactiveJwtDecoder jwtDecoder; private Converter<Jwt, ? extends Mono<? extends AbstractAuthenticationToken>> jwtAuthenticationConverter = new ReactiveJwtAuthenticationConverterAdapter( new JwtAuthenticationConverter()); public JwtReactiveAuthenticationManager(ReactiveJwtDecoder jwtDecoder) { Assert.notNull(jwtDecoder, "jwtDecoder cannot be null"); this.jwtDecoder = jwtDecoder; } @Override public Mono<Authentication> authenticate(Authentication authentication) { // @formatter:off return Mono.justOrEmpty(authentication) .filter((a) -> a instanceof BearerTokenAuthenticationToken) .cast(BearerTokenAuthenticationToken.class) .map(BearerTokenAuthenticationToken::getToken) .flatMap(this.jwtDecoder::decode) .flatMap(this.jwtAuthenticationConverter::convert) .cast(Authentication.class) .onErrorMap(JwtException.class, this::onError); // @formatter:on } /** * Use the given {@link Converter} for converting a {@link Jwt} into an * {@link AbstractAuthenticationToken}. * @param jwtAuthenticationConverter the {@link Converter} to use */ public void setJwtAuthenticationConverter( Converter<Jwt, ? extends Mono<? extends AbstractAuthenticationToken>> jwtAuthenticationConverter) { Assert.notNull(jwtAuthenticationConverter, "jwtAuthenticationConverter cannot be null"); this.jwtAuthenticationConverter = jwtAuthenticationConverter; } private AuthenticationException onError(JwtException ex) { if (ex instanceof BadJwtException) { return new InvalidBearerTokenException(ex.getMessage(), ex); } return new AuthenticationServiceException(ex.getMessage(), ex); } }
3,397
38.976471
154
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtGrantedAuthoritiesConverter.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.convert.converter.Converter; import org.springframework.core.log.LogMessage; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** * Extracts the {@link GrantedAuthority}s from scope attributes typically found in a * {@link Jwt}. * * @author Eric Deandrea * @since 5.2 */ public final class JwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> { private final Log logger = LogFactory.getLog(getClass()); private static final String DEFAULT_AUTHORITY_PREFIX = "SCOPE_"; private static final String DEFAULT_AUTHORITIES_CLAIM_DELIMITER = " "; private static final Collection<String> WELL_KNOWN_AUTHORITIES_CLAIM_NAMES = Arrays.asList("scope", "scp"); private String authorityPrefix = DEFAULT_AUTHORITY_PREFIX; private String authoritiesClaimDelimiter = DEFAULT_AUTHORITIES_CLAIM_DELIMITER; private String authoritiesClaimName; /** * Extract {@link GrantedAuthority}s from the given {@link Jwt}. * @param jwt The {@link Jwt} token * @return The {@link GrantedAuthority authorities} read from the token scopes */ @Override public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String authority : getAuthorities(jwt)) { grantedAuthorities.add(new SimpleGrantedAuthority(this.authorityPrefix + authority)); } return grantedAuthorities; } /** * Sets the prefix to use for {@link GrantedAuthority authorities} mapped by this * converter. Defaults to * {@link JwtGrantedAuthoritiesConverter#DEFAULT_AUTHORITY_PREFIX}. * @param authorityPrefix The authority prefix * @since 5.2 */ public void setAuthorityPrefix(String authorityPrefix) { Assert.notNull(authorityPrefix, "authorityPrefix cannot be null"); this.authorityPrefix = authorityPrefix; } /** * Sets the regex to use for splitting the value of the authorities claim into * {@link GrantedAuthority authorities}. Defaults to * {@link JwtGrantedAuthoritiesConverter#DEFAULT_AUTHORITIES_CLAIM_DELIMITER}. * @param authoritiesClaimDelimiter The regex used to split the authorities * @since 6.1 */ public void setAuthoritiesClaimDelimiter(String authoritiesClaimDelimiter) { Assert.notNull(authoritiesClaimDelimiter, "authoritiesClaimDelimiter cannot be null"); this.authoritiesClaimDelimiter = authoritiesClaimDelimiter; } /** * Sets the name of token claim to use for mapping {@link GrantedAuthority * authorities} by this converter. Defaults to * {@link JwtGrantedAuthoritiesConverter#WELL_KNOWN_AUTHORITIES_CLAIM_NAMES}. * @param authoritiesClaimName The token claim name to map authorities * @since 5.2 */ public void setAuthoritiesClaimName(String authoritiesClaimName) { Assert.hasText(authoritiesClaimName, "authoritiesClaimName cannot be empty"); this.authoritiesClaimName = authoritiesClaimName; } private String getAuthoritiesClaimName(Jwt jwt) { if (this.authoritiesClaimName != null) { return this.authoritiesClaimName; } for (String claimName : WELL_KNOWN_AUTHORITIES_CLAIM_NAMES) { if (jwt.hasClaim(claimName)) { return claimName; } } return null; } private Collection<String> getAuthorities(Jwt jwt) { String claimName = getAuthoritiesClaimName(jwt); if (claimName == null) { this.logger.trace("Returning no authorities since could not find any claims that might contain scopes"); return Collections.emptyList(); } if (this.logger.isTraceEnabled()) { this.logger.trace(LogMessage.format("Looking for scopes in claim %s", claimName)); } Object authorities = jwt.getClaim(claimName); if (authorities instanceof String) { if (StringUtils.hasText((String) authorities)) { return Arrays.asList(((String) authorities).split(this.authoritiesClaimDelimiter)); } return Collections.emptyList(); } if (authorities instanceof Collection) { return castAuthoritiesToCollection(authorities); } return Collections.emptyList(); } @SuppressWarnings("unchecked") private Collection<String> castAuthoritiesToCollection(Object authorities) { return (Collection<String>) authorities; } }
5,273
34.635135
108
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/DelegatingJwtGrantedAuthoritiesConverter.java
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import org.springframework.core.convert.converter.Converter; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.util.Assert; /** * A {@link Jwt} to {@link GrantedAuthority} {@link Converter} that is a composite of * converters. * * @author Laszlo Stahorszki * @author Josh Cummings * @since 5.5 * @see org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter */ public class DelegatingJwtGrantedAuthoritiesConverter implements Converter<Jwt, Collection<GrantedAuthority>> { private final Collection<Converter<Jwt, Collection<GrantedAuthority>>> authoritiesConverters; /** * Constructs a {@link DelegatingJwtGrantedAuthoritiesConverter} using the provided * {@link Collection} of {@link Converter}s * @param authoritiesConverters the {@link Collection} of {@link Converter}s to use */ public DelegatingJwtGrantedAuthoritiesConverter( Collection<Converter<Jwt, Collection<GrantedAuthority>>> authoritiesConverters) { Assert.notNull(authoritiesConverters, "authoritiesConverters cannot be null"); this.authoritiesConverters = new ArrayList<>(authoritiesConverters); } /** * Constructs a {@link DelegatingJwtGrantedAuthoritiesConverter} using the provided * array of {@link Converter}s * @param authoritiesConverters the array of {@link Converter}s to use */ @SafeVarargs public DelegatingJwtGrantedAuthoritiesConverter( Converter<Jwt, Collection<GrantedAuthority>>... authoritiesConverters) { this(Arrays.asList(authoritiesConverters)); } /** * Extract {@link GrantedAuthority}s from the given {@link Jwt}. * <p> * The authorities are extracted from each delegated {@link Converter} one at a time. * For each converter, its authorities are added in order, with duplicates removed. * @param jwt The {@link Jwt} token * @return The {@link GrantedAuthority authorities} read from the token scopes */ @Override public Collection<GrantedAuthority> convert(Jwt jwt) { Collection<GrantedAuthority> result = new LinkedHashSet<>(); for (Converter<Jwt, Collection<GrantedAuthority>> authoritiesConverter : this.authoritiesConverters) { Collection<GrantedAuthority> authorities = authoritiesConverter.convert(jwt); if (authorities != null) { result.addAll(authorities); } } return result; } }
3,213
35.942529
111
java
null
spring-security-main/oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationConverter.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.oauth2.server.resource.authentication; import java.util.Collection; import org.springframework.core.convert.converter.Converter; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.security.oauth2.jwt.JwtClaimNames; import org.springframework.util.Assert; /** * @author Rob Winch * @author Josh Cummings * @author Evgeniy Cheban * @author Olivier Antoine * @since 5.1 */ public class JwtAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> { private Converter<Jwt, Collection<GrantedAuthority>> jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); private String principalClaimName = JwtClaimNames.SUB; @Override public final AbstractAuthenticationToken convert(Jwt jwt) { Collection<GrantedAuthority> authorities = this.jwtGrantedAuthoritiesConverter.convert(jwt); String principalClaimValue = jwt.getClaimAsString(this.principalClaimName); return new JwtAuthenticationToken(jwt, authorities, principalClaimValue); } /** * Sets the {@link Converter Converter&lt;Jwt, Collection&lt;GrantedAuthority&gt;&gt;} * to use. Defaults to {@link JwtGrantedAuthoritiesConverter}. * @param jwtGrantedAuthoritiesConverter The converter * @since 5.2 * @see JwtGrantedAuthoritiesConverter */ public void setJwtGrantedAuthoritiesConverter( Converter<Jwt, Collection<GrantedAuthority>> jwtGrantedAuthoritiesConverter) { Assert.notNull(jwtGrantedAuthoritiesConverter, "jwtGrantedAuthoritiesConverter cannot be null"); this.jwtGrantedAuthoritiesConverter = jwtGrantedAuthoritiesConverter; } /** * Sets the principal claim name. Defaults to {@link JwtClaimNames#SUB}. * @param principalClaimName The principal claim name * @since 5.4 */ public void setPrincipalClaimName(String principalClaimName) { Assert.hasText(principalClaimName, "principalClaimName cannot be empty"); this.principalClaimName = principalClaimName; } }
2,739
36.534247
124
java
null
spring-security-main/aspects/src/test/java/org/springframework/security/access/intercept/aspectj/aspect/AnnotationSecurityAspectTests.java
/* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.access.intercept.aspectj.aspect; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.security.access.AccessDecisionVoter; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.annotation.Secured; import org.springframework.security.access.annotation.SecuredAnnotationSecurityMetadataSource; import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; import org.springframework.security.access.expression.method.ExpressionBasedAnnotationAttributeFactory; import org.springframework.security.access.expression.method.ExpressionBasedPostInvocationAdvice; import org.springframework.security.access.expression.method.ExpressionBasedPreInvocationAdvice; import org.springframework.security.access.intercept.AfterInvocationProviderManager; import org.springframework.security.access.intercept.aspectj.AspectJMethodSecurityInterceptor; import org.springframework.security.access.prepost.PostFilter; import org.springframework.security.access.prepost.PostInvocationAdviceProvider; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter; import org.springframework.security.access.prepost.PrePostAnnotationSecurityMetadataSource; import org.springframework.security.access.vote.AffirmativeBased; import org.springframework.security.access.vote.RoleVoter; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Luke Taylor * @since 3.0.3 */ public class AnnotationSecurityAspectTests { private AffirmativeBased adm; @Mock private AuthenticationManager authman; private TestingAuthenticationToken anne = new TestingAuthenticationToken("anne", "", "ROLE_A"); // private TestingAuthenticationToken bob = new TestingAuthenticationToken("bob", "", // "ROLE_B"); private AspectJMethodSecurityInterceptor interceptor; private SecuredImpl secured = new SecuredImpl(); private SecuredImplSubclass securedSub = new SecuredImplSubclass(); private PrePostSecured prePostSecured = new PrePostSecured(); @BeforeEach public final void setUp() { MockitoAnnotations.initMocks(this); this.interceptor = new AspectJMethodSecurityInterceptor(); AccessDecisionVoter[] voters = new AccessDecisionVoter[] { new RoleVoter(), new PreInvocationAuthorizationAdviceVoter(new ExpressionBasedPreInvocationAdvice()) }; this.adm = new AffirmativeBased(Arrays.<AccessDecisionVoter<? extends Object>>asList(voters)); this.interceptor.setAccessDecisionManager(this.adm); this.interceptor.setAuthenticationManager(this.authman); this.interceptor.setSecurityMetadataSource(new SecuredAnnotationSecurityMetadataSource()); AnnotationSecurityAspect secAspect = AnnotationSecurityAspect.aspectOf(); secAspect.setSecurityInterceptor(this.interceptor); } @AfterEach public void clearContext() { SecurityContextHolder.clearContext(); } @Test public void securedInterfaceMethodAllowsAllAccess() { this.secured.securedMethod(); } @Test public void securedClassMethodDeniesUnauthenticatedAccess() { assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class) .isThrownBy(() -> this.secured.securedClassMethod()); } @Test public void securedClassMethodAllowsAccessToRoleA() { SecurityContextHolder.getContext().setAuthentication(this.anne); this.secured.securedClassMethod(); } @Test public void internalPrivateCallIsIntercepted() { SecurityContextHolder.getContext().setAuthentication(this.anne); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.secured.publicCallsPrivate()); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.securedSub.publicCallsPrivate()); } @Test public void protectedMethodIsIntercepted() { SecurityContextHolder.getContext().setAuthentication(this.anne); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.secured.protectedMethod()); } @Test public void overriddenProtectedMethodIsNotIntercepted() { // AspectJ doesn't inherit annotations this.securedSub.protectedMethod(); } // SEC-1262 @Test public void denyAllPreAuthorizeDeniesAccess() { configureForElAnnotations(); SecurityContextHolder.getContext().setAuthentication(this.anne); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.prePostSecured::denyAllMethod); } @Test public void postFilterIsApplied() { configureForElAnnotations(); SecurityContextHolder.getContext().setAuthentication(this.anne); List<String> objects = this.prePostSecured.postFilterMethod(); assertThat(objects).hasSize(2); assertThat(objects.contains("apple")).isTrue(); assertThat(objects.contains("aubergine")).isTrue(); } private void configureForElAnnotations() { DefaultMethodSecurityExpressionHandler eh = new DefaultMethodSecurityExpressionHandler(); this.interceptor.setSecurityMetadataSource( new PrePostAnnotationSecurityMetadataSource(new ExpressionBasedAnnotationAttributeFactory(eh))); this.interceptor.setAccessDecisionManager(this.adm); AfterInvocationProviderManager aim = new AfterInvocationProviderManager(); aim.setProviders(Arrays.asList(new PostInvocationAdviceProvider(new ExpressionBasedPostInvocationAdvice(eh)))); this.interceptor.setAfterInvocationManager(aim); } interface SecuredInterface { @Secured("ROLE_X") void securedMethod(); } static class SecuredImpl implements SecuredInterface { // Not really secured because AspectJ doesn't inherit annotations from interfaces @Override public void securedMethod() { } @Secured("ROLE_A") public void securedClassMethod() { } @Secured("ROLE_X") private void privateMethod() { } @Secured("ROLE_X") protected void protectedMethod() { } @Secured("ROLE_X") public void publicCallsPrivate() { privateMethod(); } } static class SecuredImplSubclass extends SecuredImpl { @Override protected void protectedMethod() { } @Override public void publicCallsPrivate() { super.publicCallsPrivate(); } } static class PrePostSecured { @PreAuthorize("denyAll") public void denyAllMethod() { } @PostFilter("filterObject.startsWith('a')") public List<String> postFilterMethod() { ArrayList<String> objects = new ArrayList<>(); objects.addAll(Arrays.asList(new String[] { "apple", "banana", "aubergine", "orange" })); return objects; } } }
7,755
33.936937
113
java
null
spring-security-main/aspects/src/test/java/org/springframework/security/authorization/method/aspectj/PostFilterAspectTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.authorization.method.aspectj; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.aopalliance.intercept.MethodInterceptor; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; import org.springframework.security.access.prepost.PostFilter; import org.springframework.security.authorization.method.PostFilterAuthorizationMethodInterceptor; import static org.assertj.core.api.Assertions.assertThat; /** * @author Luke Taylor * @since 3.0.3 */ public class PostFilterAspectTests { private MethodInterceptor interceptor; private PrePostSecured prePostSecured = new PrePostSecured(); @BeforeEach public final void setUp() { MockitoAnnotations.initMocks(this); this.interceptor = new PostFilterAuthorizationMethodInterceptor(); PostFilterAspect secAspect = PostFilterAspect.aspectOf(); secAspect.setSecurityInterceptor(this.interceptor); } @Test public void preFilterMethodWhenListThenFilters() { List<String> objects = new ArrayList<>(Arrays.asList("apple", "banana", "aubergine", "orange")); assertThat(this.prePostSecured.postFilterMethod(objects)).containsExactly("apple", "aubergine"); } static class PrePostSecured { @PostFilter("filterObject.startsWith('a')") List<String> postFilterMethod(List<String> objects) { return objects; } } }
2,040
29.462687
98
java
null
spring-security-main/aspects/src/test/java/org/springframework/security/authorization/method/aspectj/SecuredAspectTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.authorization.method.aspectj; import org.aopalliance.intercept.MethodInterceptor; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.annotation.Secured; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor; import org.springframework.security.core.context.SecurityContextHolder; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Luke Taylor * @since 3.0.3 */ public class SecuredAspectTests { private TestingAuthenticationToken anne = new TestingAuthenticationToken("anne", "", "ROLE_A"); private MethodInterceptor interceptor; private SecuredImpl secured = new SecuredImpl(); private SecuredImplSubclass securedSub = new SecuredImplSubclass(); @BeforeEach public final void setUp() { MockitoAnnotations.initMocks(this); this.interceptor = AuthorizationManagerBeforeMethodInterceptor.secured(); SecuredAspect secAspect = SecuredAspect.aspectOf(); secAspect.setSecurityInterceptor(this.interceptor); } @AfterEach public void clearContext() { SecurityContextHolder.clearContext(); } @Test public void securedInterfaceMethodAllowsAllAccess() { this.secured.securedMethod(); } @Test public void securedClassMethodDeniesUnauthenticatedAccess() { assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class) .isThrownBy(() -> this.secured.securedClassMethod()); } @Test public void securedClassMethodAllowsAccessToRoleA() { SecurityContextHolder.getContext().setAuthentication(this.anne); this.secured.securedClassMethod(); } @Test public void internalPrivateCallIsIntercepted() { SecurityContextHolder.getContext().setAuthentication(this.anne); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.secured.publicCallsPrivate()); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.securedSub.publicCallsPrivate()); } @Test public void protectedMethodIsIntercepted() { SecurityContextHolder.getContext().setAuthentication(this.anne); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.secured.protectedMethod()); } @Test public void overriddenProtectedMethodIsNotIntercepted() { // AspectJ doesn't inherit annotations this.securedSub.protectedMethod(); } interface SecuredInterface { @Secured("ROLE_X") void securedMethod(); } static class SecuredImpl implements SecuredInterface { // Not really secured because AspectJ doesn't inherit annotations from interfaces @Override public void securedMethod() { } @Secured("ROLE_A") void securedClassMethod() { } @Secured("ROLE_X") private void privateMethod() { } @Secured("ROLE_X") protected void protectedMethod() { } @Secured("ROLE_X") void publicCallsPrivate() { privateMethod(); } } static class SecuredImplSubclass extends SecuredImpl { @Override protected void protectedMethod() { } @Override public void publicCallsPrivate() { super.publicCallsPrivate(); } } }
4,086
27.381944
112
java
null
spring-security-main/aspects/src/test/java/org/springframework/security/authorization/method/aspectj/PreAuthorizeAspectTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.authorization.method.aspectj; import org.aopalliance.intercept.MethodInterceptor; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authorization.method.AuthorizationManagerBeforeMethodInterceptor; import org.springframework.security.core.context.SecurityContextHolder; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Luke Taylor * @since 3.0.3 */ public class PreAuthorizeAspectTests { private TestingAuthenticationToken anne = new TestingAuthenticationToken("anne", "", "ROLE_A"); private MethodInterceptor interceptor; private SecuredImpl secured = new SecuredImpl(); private SecuredImplSubclass securedSub = new SecuredImplSubclass(); private PrePostSecured prePostSecured = new PrePostSecured(); @BeforeEach public final void setUp() { MockitoAnnotations.initMocks(this); this.interceptor = AuthorizationManagerBeforeMethodInterceptor.preAuthorize(); PreAuthorizeAspect secAspect = PreAuthorizeAspect.aspectOf(); secAspect.setSecurityInterceptor(this.interceptor); } @AfterEach public void clearContext() { SecurityContextHolder.clearContext(); } @Test public void securedInterfaceMethodAllowsAllAccess() { this.secured.securedMethod(); } @Test public void securedClassMethodDeniesUnauthenticatedAccess() { assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class) .isThrownBy(() -> this.secured.securedClassMethod()); } @Test public void securedClassMethodAllowsAccessToRoleA() { SecurityContextHolder.getContext().setAuthentication(this.anne); this.secured.securedClassMethod(); } @Test public void internalPrivateCallIsIntercepted() { SecurityContextHolder.getContext().setAuthentication(this.anne); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.secured.publicCallsPrivate()); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.securedSub.publicCallsPrivate()); } @Test public void protectedMethodIsIntercepted() { SecurityContextHolder.getContext().setAuthentication(this.anne); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.secured.protectedMethod()); } @Test public void overriddenProtectedMethodIsNotIntercepted() { // AspectJ doesn't inherit annotations this.securedSub.protectedMethod(); } // SEC-1262 @Test public void denyAllPreAuthorizeDeniesAccess() { SecurityContextHolder.getContext().setAuthentication(this.anne); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.prePostSecured::denyAllMethod); } interface SecuredInterface { @PreAuthorize("hasRole('X')") void securedMethod(); } static class SecuredImpl implements SecuredInterface { // Not really secured because AspectJ doesn't inherit annotations from interfaces @Override public void securedMethod() { } @PreAuthorize("hasRole('A')") void securedClassMethod() { } @PreAuthorize("hasRole('X')") private void privateMethod() { } @PreAuthorize("hasRole('X')") protected void protectedMethod() { } @PreAuthorize("hasRole('X')") void publicCallsPrivate() { privateMethod(); } } static class SecuredImplSubclass extends SecuredImpl { @Override protected void protectedMethod() { } @Override public void publicCallsPrivate() { super.publicCallsPrivate(); } } static class PrePostSecured { @PreAuthorize("denyAll") void denyAllMethod() { } } }
4,565
27.360248
112
java
null
spring-security-main/aspects/src/test/java/org/springframework/security/authorization/method/aspectj/PostAuthorizeAspectTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.authorization.method.aspectj; import org.aopalliance.intercept.MethodInterceptor; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.prepost.PostAuthorize; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authorization.method.AuthorizationManagerAfterMethodInterceptor; import org.springframework.security.core.context.SecurityContextHolder; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Luke Taylor * @since 3.0.3 */ public class PostAuthorizeAspectTests { private TestingAuthenticationToken anne = new TestingAuthenticationToken("anne", "", "ROLE_A"); private MethodInterceptor interceptor; private SecuredImpl secured = new SecuredImpl(); private SecuredImplSubclass securedSub = new SecuredImplSubclass(); private PrePostSecured prePostSecured = new PrePostSecured(); @BeforeEach public final void setUp() { MockitoAnnotations.initMocks(this); this.interceptor = AuthorizationManagerAfterMethodInterceptor.postAuthorize(); PostAuthorizeAspect secAspect = PostAuthorizeAspect.aspectOf(); secAspect.setSecurityInterceptor(this.interceptor); } @AfterEach public void clearContext() { SecurityContextHolder.clearContext(); } @Test public void securedInterfaceMethodAllowsAllAccess() { this.secured.securedMethod(); } @Test public void securedClassMethodDeniesUnauthenticatedAccess() { assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class) .isThrownBy(() -> this.secured.securedClassMethod()); } @Test public void securedClassMethodAllowsAccessToRoleA() { SecurityContextHolder.getContext().setAuthentication(this.anne); this.secured.securedClassMethod(); } @Test public void internalPrivateCallIsIntercepted() { SecurityContextHolder.getContext().setAuthentication(this.anne); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.secured.publicCallsPrivate()); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.securedSub.publicCallsPrivate()); } @Test public void protectedMethodIsIntercepted() { SecurityContextHolder.getContext().setAuthentication(this.anne); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> this.secured.protectedMethod()); } @Test public void overriddenProtectedMethodIsNotIntercepted() { // AspectJ doesn't inherit annotations this.securedSub.protectedMethod(); } // SEC-1262 @Test public void denyAllPreAuthorizeDeniesAccess() { SecurityContextHolder.getContext().setAuthentication(this.anne); assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.prePostSecured::denyAllMethod); } interface SecuredInterface { @PostAuthorize("hasRole('X')") void securedMethod(); } static class SecuredImpl implements SecuredInterface { // Not really secured because AspectJ doesn't inherit annotations from interfaces @Override public void securedMethod() { } @PostAuthorize("hasRole('A')") void securedClassMethod() { } @PostAuthorize("hasRole('X')") private void privateMethod() { } @PostAuthorize("hasRole('X')") protected void protectedMethod() { } @PostAuthorize("hasRole('X')") void publicCallsPrivate() { privateMethod(); } } static class SecuredImplSubclass extends SecuredImpl { @Override protected void protectedMethod() { } @Override public void publicCallsPrivate() { super.publicCallsPrivate(); } } static class PrePostSecured { @PostAuthorize("denyAll") void denyAllMethod() { } } }
4,574
27.416149
112
java
null
spring-security-main/aspects/src/test/java/org/springframework/security/authorization/method/aspectj/PreFilterAspectTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.authorization.method.aspectj; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.aopalliance.intercept.MethodInterceptor; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.MockitoAnnotations; import org.springframework.security.access.prepost.PreFilter; import org.springframework.security.authorization.method.PreFilterAuthorizationMethodInterceptor; import static org.assertj.core.api.Assertions.assertThat; /** * @author Luke Taylor * @since 3.0.3 */ public class PreFilterAspectTests { private MethodInterceptor interceptor; private PrePostSecured prePostSecured = new PrePostSecured(); @BeforeEach public final void setUp() { MockitoAnnotations.initMocks(this); this.interceptor = new PreFilterAuthorizationMethodInterceptor(); PreFilterAspect secAspect = PreFilterAspect.aspectOf(); secAspect.setSecurityInterceptor(this.interceptor); } @Test public void preFilterMethodWhenListThenFilters() { List<String> objects = new ArrayList<>(Arrays.asList("apple", "banana", "aubergine", "orange")); assertThat(this.prePostSecured.preFilterMethod(objects)).containsExactly("apple", "aubergine"); } static class PrePostSecured { @PreFilter("filterObject.startsWith('a')") List<String> preFilterMethod(List<String> objects) { return objects; } } }
2,031
29.328358
98
java
null
spring-security-main/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationEntryPointTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.web; import java.net.URLEncoder; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.cas.ServiceProperties; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link CasAuthenticationEntryPoint}. * * @author Ben Alex */ public class CasAuthenticationEntryPointTests { @Test public void testDetectsMissingLoginFormUrl() throws Exception { CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); ep.setServiceProperties(new ServiceProperties()); assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet) .withMessage("loginUrl must be specified"); } @Test public void testDetectsMissingServiceProperties() throws Exception { CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); ep.setLoginUrl("https://cas/login"); assertThatIllegalArgumentException().isThrownBy(ep::afterPropertiesSet) .withMessage("serviceProperties must be specified"); } @Test public void testGettersSetters() { CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); ep.setLoginUrl("https://cas/login"); assertThat(ep.getLoginUrl()).isEqualTo("https://cas/login"); ep.setServiceProperties(new ServiceProperties()); assertThat(ep.getServiceProperties() != null).isTrue(); } @Test public void testNormalOperationWithRenewFalse() throws Exception { ServiceProperties sp = new ServiceProperties(); sp.setSendRenew(false); sp.setService("https://mycompany.com/bigWebApp/login/cas"); CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); ep.setLoginUrl("https://cas/login"); ep.setServiceProperties(sp); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/some_path"); MockHttpServletResponse response = new MockHttpServletResponse(); ep.afterPropertiesSet(); ep.commence(request, response, null); assertThat( "https://cas/login?service=" + URLEncoder.encode("https://mycompany.com/bigWebApp/login/cas", "UTF-8")) .isEqualTo(response.getRedirectedUrl()); } @Test public void testNormalOperationWithRenewTrue() throws Exception { ServiceProperties sp = new ServiceProperties(); sp.setSendRenew(true); sp.setService("https://mycompany.com/bigWebApp/login/cas"); CasAuthenticationEntryPoint ep = new CasAuthenticationEntryPoint(); ep.setLoginUrl("https://cas/login"); ep.setServiceProperties(sp); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/some_path"); MockHttpServletResponse response = new MockHttpServletResponse(); ep.afterPropertiesSet(); ep.commence(request, response, null); assertThat("https://cas/login?service=" + URLEncoder.encode("https://mycompany.com/bigWebApp/login/cas", "UTF-8") + "&renew=true") .isEqualTo(response.getRedirectedUrl()); } }
3,702
36.40404
107
java
null
spring-security-main/cas/src/test/java/org/springframework/security/cas/web/CasAuthenticationFilterTests.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.web; import jakarta.servlet.FilterChain; import org.apereo.cas.client.proxy.ProxyGrantingTicketStorage; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.cas.ServiceProperties; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; /** * Tests {@link CasAuthenticationFilter}. * * @author Ben Alex * @author Rob Winch */ public class CasAuthenticationFilterTests { @AfterEach public void tearDown() { SecurityContextHolder.clearContext(); } @Test public void testGettersSetters() { CasAuthenticationFilter filter = new CasAuthenticationFilter(); filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class)); filter.setProxyReceptorUrl("/someurl"); filter.setServiceProperties(new ServiceProperties()); } @Test public void testNormalOperation() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath("/login/cas"); request.addParameter("ticket", "ST-0-ER94xMJmn6pha35CQRoZ"); CasAuthenticationFilter filter = new CasAuthenticationFilter(); filter.setAuthenticationManager((a) -> a); assertThat(filter.requiresAuthentication(request, new MockHttpServletResponse())).isTrue(); Authentication result = filter.attemptAuthentication(request, new MockHttpServletResponse()); assertThat(result != null).isTrue(); } @Test public void testNullServiceTicketHandledGracefully() throws Exception { CasAuthenticationFilter filter = new CasAuthenticationFilter(); filter.setAuthenticationManager((a) -> { throw new BadCredentialsException("Rejected"); }); assertThatExceptionOfType(AuthenticationException.class).isThrownBy( () -> filter.attemptAuthentication(new MockHttpServletRequest(), new MockHttpServletResponse())); } @Test public void testRequiresAuthenticationFilterProcessUrl() { String url = "/login/cas"; CasAuthenticationFilter filter = new CasAuthenticationFilter(); filter.setFilterProcessesUrl(url); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setServletPath(url); assertThat(filter.requiresAuthentication(request, response)).isTrue(); } @Test public void testRequiresAuthenticationProxyRequest() { CasAuthenticationFilter filter = new CasAuthenticationFilter(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setServletPath("/pgtCallback"); assertThat(filter.requiresAuthentication(request, response)).isFalse(); filter.setProxyReceptorUrl(request.getServletPath()); assertThat(filter.requiresAuthentication(request, response)).isFalse(); filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class)); assertThat(filter.requiresAuthentication(request, response)).isTrue(); request.setServletPath("/other"); assertThat(filter.requiresAuthentication(request, response)).isFalse(); } @Test public void testRequiresAuthenticationAuthAll() { ServiceProperties properties = new ServiceProperties(); properties.setAuthenticateAllArtifacts(true); String url = "/login/cas"; CasAuthenticationFilter filter = new CasAuthenticationFilter(); filter.setFilterProcessesUrl(url); filter.setServiceProperties(properties); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setServletPath(url); assertThat(filter.requiresAuthentication(request, response)).isTrue(); request.setServletPath("/other"); assertThat(filter.requiresAuthentication(request, response)).isFalse(); request.setParameter(properties.getArtifactParameter(), "value"); assertThat(filter.requiresAuthentication(request, response)).isTrue(); SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("key", "principal", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"))); assertThat(filter.requiresAuthentication(request, response)).isTrue(); SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("un", "principal")); assertThat(filter.requiresAuthentication(request, response)).isTrue(); SecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken("un", "principal", "ROLE_ANONYMOUS")); assertThat(filter.requiresAuthentication(request, response)).isFalse(); } @Test public void testAuthenticateProxyUrl() throws Exception { CasAuthenticationFilter filter = new CasAuthenticationFilter(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.setServletPath("/pgtCallback"); filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class)); filter.setProxyReceptorUrl(request.getServletPath()); assertThat(filter.attemptAuthentication(request, response)).isNull(); } @Test public void testDoFilterAuthenticateAll() throws Exception { AuthenticationSuccessHandler successHandler = mock(AuthenticationSuccessHandler.class); AuthenticationManager manager = mock(AuthenticationManager.class); Authentication authentication = new TestingAuthenticationToken("un", "pwd", "ROLE_USER"); given(manager.authenticate(any(Authentication.class))).willReturn(authentication); ServiceProperties serviceProperties = new ServiceProperties(); serviceProperties.setAuthenticateAllArtifacts(true); MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("ticket", "ST-1-123"); request.setServletPath("/authenticate"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); CasAuthenticationFilter filter = new CasAuthenticationFilter(); filter.setServiceProperties(serviceProperties); filter.setAuthenticationSuccessHandler(successHandler); filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class)); filter.setAuthenticationManager(manager); filter.afterPropertiesSet(); filter.doFilter(request, response, chain); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNotNull() .withFailMessage("Authentication should not be null"); verify(chain).doFilter(request, response); verifyNoInteractions(successHandler); // validate for when the filterProcessUrl matches filter.setFilterProcessesUrl(request.getServletPath()); SecurityContextHolder.clearContext(); filter.doFilter(request, response, chain); verifyNoMoreInteractions(chain); verify(successHandler).onAuthenticationSuccess(request, response, authentication); } // SEC-1592 @Test public void testChainNotInvokedForProxyReceptor() throws Exception { CasAuthenticationFilter filter = new CasAuthenticationFilter(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); request.setServletPath("/pgtCallback"); filter.setProxyGrantingTicketStorage(mock(ProxyGrantingTicketStorage.class)); filter.setProxyReceptorUrl(request.getServletPath()); filter.doFilter(request, response, chain); verifyNoInteractions(chain); } @Test public void successfulAuthenticationWhenProxyRequestThenSavesSecurityContext() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter(ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER, "ticket"); MockHttpServletResponse response = new MockHttpServletResponse(); CasAuthenticationFilter filter = new CasAuthenticationFilter(); ServiceProperties serviceProperties = new ServiceProperties(); serviceProperties.setAuthenticateAllArtifacts(true); filter.setServiceProperties(serviceProperties); SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class); ReflectionTestUtils.setField(filter, "securityContextRepository", securityContextRepository); filter.successfulAuthentication(request, response, new MockFilterChain(), mock(Authentication.class)); verify(securityContextRepository).saveContext(any(SecurityContext.class), eq(request), eq(response)); } }
10,375
45.738739
107
java
null
spring-security-main/cas/src/test/java/org/springframework/security/cas/web/ServicePropertiesTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.web; import org.junit.jupiter.api.Test; import org.springframework.security.cas.SamlServiceProperties; import org.springframework.security.cas.ServiceProperties; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link ServiceProperties}. * * @author Ben Alex */ public class ServicePropertiesTests { @Test public void detectsMissingService() throws Exception { ServiceProperties sp = new ServiceProperties(); assertThatIllegalArgumentException().isThrownBy(sp::afterPropertiesSet); } @Test public void nullServiceWhenAuthenticateAllTokens() throws Exception { ServiceProperties sp = new ServiceProperties(); sp.setAuthenticateAllArtifacts(true); assertThatIllegalArgumentException().isThrownBy(sp::afterPropertiesSet); sp.setAuthenticateAllArtifacts(false); assertThatIllegalArgumentException().isThrownBy(sp::afterPropertiesSet); } @Test public void testGettersSetters() throws Exception { ServiceProperties[] sps = { new ServiceProperties(), new SamlServiceProperties() }; for (ServiceProperties sp : sps) { sp.setSendRenew(false); assertThat(sp.isSendRenew()).isFalse(); sp.setSendRenew(true); assertThat(sp.isSendRenew()).isTrue(); sp.setArtifactParameter("notticket"); assertThat(sp.getArtifactParameter()).isEqualTo("notticket"); sp.setServiceParameter("notservice"); assertThat(sp.getServiceParameter()).isEqualTo("notservice"); sp.setService("https://mycompany.com/service"); assertThat(sp.getService()).isEqualTo("https://mycompany.com/service"); sp.afterPropertiesSet(); } } }
2,332
33.308824
85
java
null
spring-security-main/cas/src/test/java/org/springframework/security/cas/web/authentication/DefaultServiceAuthenticationDetailsTests.java
/* * Copyright 2011-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.web.authentication; import java.util.regex.Pattern; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.GenericXmlApplicationContext; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.cas.ServiceProperties; import org.springframework.security.web.util.UrlUtils; import static org.assertj.core.api.Assertions.assertThat; /** * @author Rob Winch */ public class DefaultServiceAuthenticationDetailsTests { private DefaultServiceAuthenticationDetails details; private MockHttpServletRequest request; private Pattern artifactPattern; private String casServiceUrl; private ConfigurableApplicationContext context; @BeforeEach public void setUp() { this.casServiceUrl = "https://localhost:8443/j_spring_security_cas"; this.request = new MockHttpServletRequest(); this.request.setScheme("https"); this.request.setServerName("localhost"); this.request.setServerPort(8443); this.request.setRequestURI("/cas-sample/secure/"); this.artifactPattern = DefaultServiceAuthenticationDetails .createArtifactPattern(ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER); } @AfterEach public void cleanup() { if (this.context != null) { this.context.close(); } } @Test public void getServiceUrlNullQuery() throws Exception { this.details = new DefaultServiceAuthenticationDetails(this.casServiceUrl, this.request, this.artifactPattern); assertThat(this.details.getServiceUrl()).isEqualTo(UrlUtils.buildFullRequestUrl(this.request)); } @Test public void getServiceUrlTicketOnlyParam() throws Exception { this.request.setQueryString("ticket=123"); this.details = new DefaultServiceAuthenticationDetails(this.casServiceUrl, this.request, this.artifactPattern); String serviceUrl = this.details.getServiceUrl(); this.request.setQueryString(null); assertThat(serviceUrl).isEqualTo(UrlUtils.buildFullRequestUrl(this.request)); } @Test public void getServiceUrlTicketFirstMultiParam() throws Exception { this.request.setQueryString("ticket=123&other=value"); this.details = new DefaultServiceAuthenticationDetails(this.casServiceUrl, this.request, this.artifactPattern); String serviceUrl = this.details.getServiceUrl(); this.request.setQueryString("other=value"); assertThat(serviceUrl).isEqualTo(UrlUtils.buildFullRequestUrl(this.request)); } @Test public void getServiceUrlTicketLastMultiParam() throws Exception { this.request.setQueryString("other=value&ticket=123"); this.details = new DefaultServiceAuthenticationDetails(this.casServiceUrl, this.request, this.artifactPattern); String serviceUrl = this.details.getServiceUrl(); this.request.setQueryString("other=value"); assertThat(serviceUrl).isEqualTo(UrlUtils.buildFullRequestUrl(this.request)); } @Test public void getServiceUrlTicketMiddleMultiParam() throws Exception { this.request.setQueryString("other=value&ticket=123&last=this"); this.details = new DefaultServiceAuthenticationDetails(this.casServiceUrl, this.request, this.artifactPattern); String serviceUrl = this.details.getServiceUrl(); this.request.setQueryString("other=value&last=this"); assertThat(serviceUrl).isEqualTo(UrlUtils.buildFullRequestUrl(this.request)); } @Test public void getServiceUrlDoesNotUseHostHeader() throws Exception { this.casServiceUrl = "https://example.com/j_spring_security_cas"; this.request.setServerName("evil.com"); this.details = new DefaultServiceAuthenticationDetails(this.casServiceUrl, this.request, this.artifactPattern); assertThat(this.details.getServiceUrl()).isEqualTo("https://example.com/cas-sample/secure/"); } @Test public void getServiceUrlDoesNotUseHostHeaderExplicit() { this.casServiceUrl = "https://example.com/j_spring_security_cas"; this.request.setServerName("evil.com"); ServiceAuthenticationDetails details = loadServiceAuthenticationDetails( "defaultserviceauthenticationdetails-explicit.xml"); assertThat(details.getServiceUrl()).isEqualTo("https://example.com/cas-sample/secure/"); } private ServiceAuthenticationDetails loadServiceAuthenticationDetails(String resourceName) { this.context = new GenericXmlApplicationContext(getClass(), resourceName); ServiceAuthenticationDetailsSource source = this.context.getBean(ServiceAuthenticationDetailsSource.class); return source.buildDetails(this.request); } }
5,195
38.067669
113
java
null
spring-security-main/cas/src/test/java/org/springframework/security/cas/userdetails/GrantedAuthorityFromAssertionAttributesUserDetailsServiceTests.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.userdetails; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apereo.cas.client.authentication.AttributePrincipal; import org.apereo.cas.client.validation.Assertion; import org.junit.jupiter.api.Test; import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.UserDetails; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * @author Luke Taylor */ public class GrantedAuthorityFromAssertionAttributesUserDetailsServiceTests { @Test public void correctlyExtractsNamedAttributesFromAssertionAndConvertsThemToAuthorities() { GrantedAuthorityFromAssertionAttributesUserDetailsService uds = new GrantedAuthorityFromAssertionAttributesUserDetailsService( new String[] { "a", "b", "c", "d" }); uds.setConvertToUpperCase(false); Assertion assertion = mock(Assertion.class); AttributePrincipal principal = mock(AttributePrincipal.class); Map<String, Object> attributes = new HashMap<>(); attributes.put("a", Arrays.asList("role_a1", "role_a2")); attributes.put("b", "role_b"); attributes.put("c", "role_c"); attributes.put("d", null); attributes.put("someother", "unused"); given(assertion.getPrincipal()).willReturn(principal); given(principal.getAttributes()).willReturn(attributes); given(principal.getName()).willReturn("somebody"); CasAssertionAuthenticationToken token = new CasAssertionAuthenticationToken(assertion, "ticket"); UserDetails user = uds.loadUserDetails(token); Set<String> roles = AuthorityUtils.authorityListToSet(user.getAuthorities()); assertThat(roles).containsExactlyInAnyOrder("role_a1", "role_a2", "role_b", "role_c"); } }
2,558
38.984375
128
java
null
spring-security-main/cas/src/test/java/org/springframework/security/cas/jackson2/CasAuthenticationTokenMixinTests.java
/* * Copyright 2015-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.jackson2; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.Date; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.apereo.cas.client.authentication.AttributePrincipalImpl; import org.apereo.cas.client.validation.Assertion; import org.apereo.cas.client.validation.AssertionImpl; import org.json.JSONException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.security.cas.authentication.CasAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.jackson2.SecurityJackson2Modules; import static org.assertj.core.api.Assertions.assertThat; /** * @author Jitendra Singh * @since 4.2 */ public class CasAuthenticationTokenMixinTests { private static final String KEY = "casKey"; private static final String PASSWORD = "\"1234\""; private static final Date START_DATE = new Date(); private static final Date END_DATE = new Date(); public static final String AUTHORITY_JSON = "{\"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\", \"authority\": \"ROLE_USER\"}"; public static final String AUTHORITIES_SET_JSON = "[\"java.util.Collections$UnmodifiableSet\", [" + AUTHORITY_JSON + "]]"; public static final String AUTHORITIES_ARRAYLIST_JSON = "[\"java.util.Collections$UnmodifiableRandomAccessList\", [" + AUTHORITY_JSON + "]]"; // @formatter:off public static final String USER_JSON = "{" + "\"@class\": \"org.springframework.security.core.userdetails.User\", " + "\"username\": \"admin\"," + " \"password\": " + PASSWORD + ", " + "\"accountNonExpired\": true, " + "\"accountNonLocked\": true, " + "\"credentialsNonExpired\": true, " + "\"enabled\": true, " + "\"authorities\": " + AUTHORITIES_SET_JSON + "}"; // @formatter:on private static final String CAS_TOKEN_JSON = "{" + "\"@class\": \"org.springframework.security.cas.authentication.CasAuthenticationToken\", " + "\"keyHash\": " + KEY.hashCode() + "," + "\"principal\": " + USER_JSON + ", " + "\"credentials\": " + PASSWORD + ", " + "\"authorities\": " + AUTHORITIES_ARRAYLIST_JSON + "," + "\"userDetails\": " + USER_JSON + "," + "\"authenticated\": true, " + "\"details\": null," + "\"assertion\": {" + "\"@class\": \"org.apereo.cas.client.validation.AssertionImpl\", " + "\"principal\": {" + "\"@class\": \"org.apereo.cas.client.authentication.AttributePrincipalImpl\", " + "\"name\": \"assertName\", " + "\"attributes\": {\"@class\": \"java.util.Collections$EmptyMap\"}, " + "\"proxyGrantingTicket\": null, " + "\"proxyRetriever\": null" + "}, " + "\"validFromDate\": [\"java.util.Date\", " + START_DATE.getTime() + "], " + "\"validUntilDate\": [\"java.util.Date\", " + END_DATE.getTime() + "]," + "\"authenticationDate\": [\"java.util.Date\", " + START_DATE.getTime() + "], " + "\"attributes\": {\"@class\": \"java.util.Collections$EmptyMap\"}," + "\"context\": {\"@class\":\"java.util.HashMap\"}" + "}" + "}"; private static final String CAS_TOKEN_CLEARED_JSON = CAS_TOKEN_JSON.replaceFirst(PASSWORD, "null"); protected ObjectMapper mapper; @BeforeEach public void setup() { this.mapper = new ObjectMapper(); ClassLoader loader = getClass().getClassLoader(); this.mapper.registerModules(SecurityJackson2Modules.getModules(loader)); } @Test public void serializeCasAuthenticationTest() throws JsonProcessingException, JSONException { CasAuthenticationToken token = createCasAuthenticationToken(); String actualJson = this.mapper.writeValueAsString(token); JSONAssert.assertEquals(CAS_TOKEN_JSON, actualJson, true); } @Test public void serializeCasAuthenticationTestAfterEraseCredentialInvoked() throws JsonProcessingException, JSONException { CasAuthenticationToken token = createCasAuthenticationToken(); token.eraseCredentials(); String actualJson = this.mapper.writeValueAsString(token); JSONAssert.assertEquals(CAS_TOKEN_CLEARED_JSON, actualJson, true); } @Test public void deserializeCasAuthenticationTestAfterEraseCredentialInvoked() throws Exception { CasAuthenticationToken token = this.mapper.readValue(CAS_TOKEN_CLEARED_JSON, CasAuthenticationToken.class); assertThat(((UserDetails) token.getPrincipal()).getPassword()).isNull(); } @Test public void deserializeCasAuthenticationTest() throws IOException { CasAuthenticationToken token = this.mapper.readValue(CAS_TOKEN_JSON, CasAuthenticationToken.class); assertThat(token).isNotNull(); assertThat(token.getPrincipal()).isNotNull().isInstanceOf(User.class); assertThat(((User) token.getPrincipal()).getUsername()).isEqualTo("admin"); assertThat(((User) token.getPrincipal()).getPassword()).isEqualTo("1234"); assertThat(token.getUserDetails()).isNotNull().isInstanceOf(User.class); assertThat(token.getAssertion()).isNotNull().isInstanceOf(AssertionImpl.class); assertThat(token.getKeyHash()).isEqualTo(KEY.hashCode()); assertThat(token.getUserDetails().getAuthorities()).extracting(GrantedAuthority::getAuthority) .containsOnly("ROLE_USER"); assertThat(token.getAssertion().getAuthenticationDate()).isEqualTo(START_DATE); assertThat(token.getAssertion().getValidFromDate()).isEqualTo(START_DATE); assertThat(token.getAssertion().getValidUntilDate()).isEqualTo(END_DATE); assertThat(token.getAssertion().getPrincipal().getName()).isEqualTo("assertName"); assertThat(token.getAssertion().getAttributes()).hasSize(0); } private CasAuthenticationToken createCasAuthenticationToken() { User principal = new User("admin", "1234", Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))); Collection<? extends GrantedAuthority> authorities = Collections .singletonList(new SimpleGrantedAuthority("ROLE_USER")); Assertion assertion = new AssertionImpl(new AttributePrincipalImpl("assertName"), START_DATE, END_DATE, START_DATE, Collections.<String, Object>emptyMap()); return new CasAuthenticationToken(KEY, principal, principal.getPassword(), authorities, new User("admin", "1234", authorities), assertion); } }
7,110
44.877419
162
java
null
spring-security-main/cas/src/test/java/org/springframework/security/cas/authentication/SpringCacheBasedTicketCacheTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.authentication; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.cache.CacheManager; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests * {@link org.springframework.security.cas.authentication.SpringCacheBasedTicketCache}. * * @author Marten Deinum * @since 3.2 */ public class SpringCacheBasedTicketCacheTests extends AbstractStatelessTicketCacheTests { private static CacheManager cacheManager; @BeforeAll public static void initCacheManaer() { cacheManager = new ConcurrentMapCacheManager(); cacheManager.getCache("castickets"); } @Test public void testCacheOperation() throws Exception { SpringCacheBasedTicketCache cache = new SpringCacheBasedTicketCache(cacheManager.getCache("castickets")); final CasAuthenticationToken token = getToken(); // Check it gets stored in the cache cache.putTicketInCache(token); assertThat(cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ")).isEqualTo(token); // Check it gets removed from the cache cache.removeTicketFromCache(getToken()); assertThat(cache.getByTicketId("ST-0-ER94xMJmn6pha35CQRoZ")).isNull(); // Check it doesn't return values for null or unknown service tickets assertThat(cache.getByTicketId(null)).isNull(); assertThat(cache.getByTicketId("UNKNOWN_SERVICE_TICKET")).isNull(); } @Test public void testStartupDetectsMissingCache() throws Exception { assertThatIllegalArgumentException().isThrownBy(() -> new SpringCacheBasedTicketCache(null)); } }
2,348
34.590909
107
java
null
spring-security-main/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationTokenTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.authentication; import java.util.Collections; import java.util.List; import org.apereo.cas.client.validation.Assertion; import org.apereo.cas.client.validation.AssertionImpl; import org.junit.jupiter.api.Test; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests {@link CasAuthenticationToken}. * * @author Ben Alex */ public class CasAuthenticationTokenTests { private final List<GrantedAuthority> ROLES = AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"); private UserDetails makeUserDetails() { return makeUserDetails("user"); } private UserDetails makeUserDetails(final String name) { return new User(name, "password", true, true, true, true, this.ROLES); } @Test public void testConstructorRejectsNulls() { Assertion assertion = new AssertionImpl("test"); assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken(null, makeUserDetails(), "Password", this.ROLES, makeUserDetails(), assertion)); assertThatIllegalArgumentException().isThrownBy( () -> new CasAuthenticationToken("key", null, "Password", this.ROLES, makeUserDetails(), assertion)); assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken("key", makeUserDetails(), null, this.ROLES, makeUserDetails(), assertion)); assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, makeUserDetails(), null)); assertThatIllegalArgumentException().isThrownBy( () -> new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, null, assertion)); assertThatIllegalArgumentException().isThrownBy(() -> new CasAuthenticationToken("key", makeUserDetails(), "Password", AuthorityUtils.createAuthorityList("ROLE_1", null), makeUserDetails(), assertion)); } @Test public void constructorWhenEmptyKeyThenThrowsException() { assertThatIllegalArgumentException().isThrownBy( () -> new CasAuthenticationToken("", "user", "password", Collections.<GrantedAuthority>emptyList(), new User("user", "password", Collections.<GrantedAuthority>emptyList()), null)); } @Test public void testEqualsWhenEqual() { final Assertion assertion = new AssertionImpl("test"); CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, makeUserDetails(), assertion); CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, makeUserDetails(), assertion); assertThat(token2).isEqualTo(token1); } @Test public void testGetters() { // Build the proxy list returned in the ticket from CAS final Assertion assertion = new AssertionImpl("test"); CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, makeUserDetails(), assertion); assertThat(token.getKeyHash()).isEqualTo("key".hashCode()); assertThat(token.getPrincipal()).isEqualTo(makeUserDetails()); assertThat(token.getCredentials()).isEqualTo("Password"); assertThat(token.getAuthorities()).contains(new SimpleGrantedAuthority("ROLE_ONE")); assertThat(token.getAuthorities()).contains(new SimpleGrantedAuthority("ROLE_TWO")); assertThat(token.getAssertion()).isEqualTo(assertion); assertThat(token.getUserDetails().getUsername()).isEqualTo(makeUserDetails().getUsername()); } @Test public void testNoArgConstructorDoesntExist() { assertThatExceptionOfType(NoSuchMethodException.class) .isThrownBy(() -> CasAuthenticationToken.class.getDeclaredConstructor((Class[]) null)); } @Test public void testNotEqualsDueToAbstractParentEqualsCheck() { final Assertion assertion = new AssertionImpl("test"); CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, makeUserDetails(), assertion); CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails("OTHER_NAME"), "Password", this.ROLES, makeUserDetails(), assertion); assertThat(!token1.equals(token2)).isTrue(); } @Test public void testNotEqualsDueToKey() { final Assertion assertion = new AssertionImpl("test"); CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, makeUserDetails(), assertion); CasAuthenticationToken token2 = new CasAuthenticationToken("DIFFERENT_KEY", makeUserDetails(), "Password", this.ROLES, makeUserDetails(), assertion); assertThat(!token1.equals(token2)).isTrue(); } @Test public void testNotEqualsDueToAssertion() { final Assertion assertion = new AssertionImpl("test"); final Assertion assertion2 = new AssertionImpl("test"); CasAuthenticationToken token1 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, makeUserDetails(), assertion); CasAuthenticationToken token2 = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, makeUserDetails(), assertion2); assertThat(!token1.equals(token2)).isTrue(); } @Test public void testSetAuthenticated() { final Assertion assertion = new AssertionImpl("test"); CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, makeUserDetails(), assertion); assertThat(token.isAuthenticated()).isTrue(); token.setAuthenticated(false); assertThat(!token.isAuthenticated()).isTrue(); } @Test public void testToString() { final Assertion assertion = new AssertionImpl("test"); CasAuthenticationToken token = new CasAuthenticationToken("key", makeUserDetails(), "Password", this.ROLES, makeUserDetails(), assertion); String result = token.toString(); assertThat(result.lastIndexOf("Credentials (Service/Proxy Ticket):") != -1).isTrue(); } }
6,953
42.735849
114
java
null
spring-security-main/cas/src/test/java/org/springframework/security/cas/authentication/NullStatelessTicketCacheTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.authentication; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Test cases for the @link {@link NullStatelessTicketCache} * * @author Scott Battaglia * */ public class NullStatelessTicketCacheTests extends AbstractStatelessTicketCacheTests { private StatelessTicketCache cache = new NullStatelessTicketCache(); @Test public void testGetter() { assertThat(this.cache.getByTicketId(null)).isNull(); assertThat(this.cache.getByTicketId("test")).isNull(); } @Test public void testInsertAndGet() { final CasAuthenticationToken token = getToken(); this.cache.putTicketInCache(token); assertThat(this.cache.getByTicketId((String) token.getCredentials())).isNull(); } }
1,410
29.021277
86
java
null
spring-security-main/cas/src/test/java/org/springframework/security/cas/authentication/CasAuthenticationProviderTests.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.authentication; import java.util.HashMap; import java.util.Map; import org.apereo.cas.client.validation.Assertion; import org.apereo.cas.client.validation.AssertionImpl; import org.apereo.cas.client.validation.TicketValidator; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.cas.ServiceProperties; import org.springframework.security.cas.web.authentication.ServiceAuthenticationDetails; import org.springframework.security.core.Authentication; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.AuthenticationUserDetailsService; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.web.authentication.WebAuthenticationDetails; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * Tests {@link CasAuthenticationProvider}. * * @author Ben Alex * @author Scott Battaglia */ @SuppressWarnings("unchecked") public class CasAuthenticationProviderTests { private UserDetails makeUserDetails() { return new User("user", "password", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); } private UserDetails makeUserDetailsFromAuthoritiesPopulator() { return new User("user", "password", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_A", "ROLE_B")); } private ServiceProperties makeServiceProperties() { final ServiceProperties serviceProperties = new ServiceProperties(); serviceProperties.setSendRenew(false); serviceProperties.setService("http://test.com"); return serviceProperties; } @Test public void statefulAuthenticationIsSuccessful() throws Exception { CasAuthenticationProvider cap = new CasAuthenticationProvider(); cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); cap.setKey("qwerty"); StatelessTicketCache cache = new MockStatelessTicketCache(); cap.setStatelessTicketCache(cache); cap.setServiceProperties(makeServiceProperties()); cap.setTicketValidator(new MockTicketValidator(true)); cap.afterPropertiesSet(); CasServiceTicketAuthenticationToken token = CasServiceTicketAuthenticationToken.stateful("ST-123"); token.setDetails("details"); Authentication result = cap.authenticate(token); // Confirm ST-123 was NOT added to the cache assertThat(cache.getByTicketId("ST-456") == null).isTrue(); if (!(result instanceof CasAuthenticationToken)) { fail("Should have returned a CasAuthenticationToken"); } CasAuthenticationToken casResult = (CasAuthenticationToken) result; assertThat(casResult.getPrincipal()).isEqualTo(makeUserDetailsFromAuthoritiesPopulator()); assertThat(casResult.getCredentials()).isEqualTo("ST-123"); assertThat(casResult.getAuthorities()).contains(new SimpleGrantedAuthority("ROLE_A")); assertThat(casResult.getAuthorities()).contains(new SimpleGrantedAuthority("ROLE_B")); assertThat(casResult.getKeyHash()).isEqualTo(cap.getKey().hashCode()); assertThat(casResult.getDetails()).isEqualTo("details"); // Now confirm the CasAuthenticationToken is automatically re-accepted. // To ensure TicketValidator not called again, set it to deliver an exception... cap.setTicketValidator(new MockTicketValidator(false)); Authentication laterResult = cap.authenticate(result); assertThat(laterResult).isEqualTo(result); } @Test public void statelessAuthenticationIsSuccessful() throws Exception { CasAuthenticationProvider cap = new CasAuthenticationProvider(); cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); cap.setKey("qwerty"); StatelessTicketCache cache = new MockStatelessTicketCache(); cap.setStatelessTicketCache(cache); cap.setTicketValidator(new MockTicketValidator(true)); cap.setServiceProperties(makeServiceProperties()); cap.afterPropertiesSet(); CasServiceTicketAuthenticationToken token = CasServiceTicketAuthenticationToken.stateless("ST-456"); token.setDetails("details"); Authentication result = cap.authenticate(token); // Confirm ST-456 was added to the cache assertThat(cache.getByTicketId("ST-456") != null).isTrue(); if (!(result instanceof CasAuthenticationToken)) { fail("Should have returned a CasAuthenticationToken"); } assertThat(result.getPrincipal()).isEqualTo(makeUserDetailsFromAuthoritiesPopulator()); assertThat(result.getCredentials()).isEqualTo("ST-456"); assertThat(result.getDetails()).isEqualTo("details"); // Now try to authenticate again. To ensure TicketValidator not // called again, set it to deliver an exception... cap.setTicketValidator(new MockTicketValidator(false)); // Previously created CasServiceTicketAuthenticationToken is OK Authentication newResult = cap.authenticate(token); assertThat(newResult.getPrincipal()).isEqualTo(makeUserDetailsFromAuthoritiesPopulator()); assertThat(newResult.getCredentials()).isEqualTo("ST-456"); } @Test public void authenticateAllNullService() throws Exception { String serviceUrl = "https://service/context"; ServiceAuthenticationDetails details = mock(ServiceAuthenticationDetails.class); given(details.getServiceUrl()).willReturn(serviceUrl); TicketValidator validator = mock(TicketValidator.class); given(validator.validate(any(String.class), any(String.class))).willReturn(new AssertionImpl("rod")); ServiceProperties serviceProperties = makeServiceProperties(); serviceProperties.setAuthenticateAllArtifacts(true); CasAuthenticationProvider cap = new CasAuthenticationProvider(); cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); cap.setKey("qwerty"); cap.setTicketValidator(validator); cap.setServiceProperties(serviceProperties); cap.afterPropertiesSet(); String ticket = "ST-456"; CasServiceTicketAuthenticationToken token = CasServiceTicketAuthenticationToken.stateless(ticket); Authentication result = cap.authenticate(token); } @Test public void authenticateAllAuthenticationIsSuccessful() throws Exception { String serviceUrl = "https://service/context"; ServiceAuthenticationDetails details = mock(ServiceAuthenticationDetails.class); given(details.getServiceUrl()).willReturn(serviceUrl); TicketValidator validator = mock(TicketValidator.class); given(validator.validate(any(String.class), any(String.class))).willReturn(new AssertionImpl("rod")); ServiceProperties serviceProperties = makeServiceProperties(); serviceProperties.setAuthenticateAllArtifacts(true); CasAuthenticationProvider cap = new CasAuthenticationProvider(); cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); cap.setKey("qwerty"); cap.setTicketValidator(validator); cap.setServiceProperties(serviceProperties); cap.afterPropertiesSet(); String ticket = "ST-456"; CasServiceTicketAuthenticationToken token = CasServiceTicketAuthenticationToken.stateless(ticket); Authentication result = cap.authenticate(token); verify(validator).validate(ticket, serviceProperties.getService()); serviceProperties.setAuthenticateAllArtifacts(true); result = cap.authenticate(token); verify(validator, times(2)).validate(ticket, serviceProperties.getService()); token.setDetails(details); result = cap.authenticate(token); verify(validator).validate(ticket, serviceUrl); serviceProperties.setAuthenticateAllArtifacts(false); serviceProperties.setService(null); cap.setServiceProperties(serviceProperties); cap.afterPropertiesSet(); result = cap.authenticate(token); verify(validator, times(2)).validate(ticket, serviceUrl); token.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest())); assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token)); cap.setServiceProperties(null); cap.afterPropertiesSet(); assertThatIllegalStateException().isThrownBy(() -> cap.authenticate(token)); } @Test public void missingTicketIdIsDetected() throws Exception { CasAuthenticationProvider cap = new CasAuthenticationProvider(); cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); cap.setKey("qwerty"); StatelessTicketCache cache = new MockStatelessTicketCache(); cap.setStatelessTicketCache(cache); cap.setTicketValidator(new MockTicketValidator(true)); cap.setServiceProperties(makeServiceProperties()); cap.afterPropertiesSet(); CasServiceTicketAuthenticationToken token = CasServiceTicketAuthenticationToken.stateful(""); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> cap.authenticate(token)); } @Test public void invalidKeyIsDetected() throws Exception { final Assertion assertion = new AssertionImpl("test"); CasAuthenticationProvider cap = new CasAuthenticationProvider(); cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); cap.setKey("qwerty"); StatelessTicketCache cache = new MockStatelessTicketCache(); cap.setStatelessTicketCache(cache); cap.setTicketValidator(new MockTicketValidator(true)); cap.setServiceProperties(makeServiceProperties()); cap.afterPropertiesSet(); CasAuthenticationToken token = new CasAuthenticationToken("WRONG_KEY", makeUserDetails(), "credentials", AuthorityUtils.createAuthorityList("XX"), makeUserDetails(), assertion); assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> cap.authenticate(token)); } @Test public void detectsMissingAuthoritiesPopulator() throws Exception { CasAuthenticationProvider cap = new CasAuthenticationProvider(); cap.setKey("qwerty"); cap.setStatelessTicketCache(new MockStatelessTicketCache()); cap.setTicketValidator(new MockTicketValidator(true)); cap.setServiceProperties(makeServiceProperties()); assertThatIllegalArgumentException().isThrownBy(() -> cap.afterPropertiesSet()); } @Test public void detectsMissingKey() throws Exception { CasAuthenticationProvider cap = new CasAuthenticationProvider(); cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); cap.setStatelessTicketCache(new MockStatelessTicketCache()); cap.setTicketValidator(new MockTicketValidator(true)); cap.setServiceProperties(makeServiceProperties()); assertThatIllegalArgumentException().isThrownBy(() -> cap.afterPropertiesSet()); } @Test public void detectsMissingStatelessTicketCache() throws Exception { CasAuthenticationProvider cap = new CasAuthenticationProvider(); // set this explicitly to null to test failure cap.setStatelessTicketCache(null); cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); cap.setKey("qwerty"); cap.setTicketValidator(new MockTicketValidator(true)); cap.setServiceProperties(makeServiceProperties()); assertThatIllegalArgumentException().isThrownBy(() -> cap.afterPropertiesSet()); } @Test public void detectsMissingTicketValidator() throws Exception { CasAuthenticationProvider cap = new CasAuthenticationProvider(); cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); cap.setKey("qwerty"); cap.setStatelessTicketCache(new MockStatelessTicketCache()); cap.setServiceProperties(makeServiceProperties()); assertThatIllegalArgumentException().isThrownBy(() -> cap.afterPropertiesSet()); } @Test public void gettersAndSettersMatch() throws Exception { CasAuthenticationProvider cap = new CasAuthenticationProvider(); cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); cap.setKey("qwerty"); cap.setStatelessTicketCache(new MockStatelessTicketCache()); cap.setTicketValidator(new MockTicketValidator(true)); cap.setServiceProperties(makeServiceProperties()); cap.afterPropertiesSet(); // TODO disabled because why do we need to expose this? // assertThat(cap.getUserDetailsService() != null).isTrue(); assertThat(cap.getKey()).isEqualTo("qwerty"); assertThat(cap.getStatelessTicketCache() != null).isTrue(); assertThat(cap.getTicketValidator() != null).isTrue(); } @Test public void ignoresClassesItDoesNotSupport() throws Exception { CasAuthenticationProvider cap = new CasAuthenticationProvider(); cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); cap.setKey("qwerty"); cap.setStatelessTicketCache(new MockStatelessTicketCache()); cap.setTicketValidator(new MockTicketValidator(true)); cap.setServiceProperties(makeServiceProperties()); cap.afterPropertiesSet(); TestingAuthenticationToken token = new TestingAuthenticationToken("user", "password", "ROLE_A"); assertThat(cap.supports(TestingAuthenticationToken.class)).isFalse(); // Try it anyway assertThat(cap.authenticate(token)).isNull(); } @Test public void ignoresUsernamePasswordAuthenticationTokensWithoutCasIdentifiersAsPrincipal() throws Exception { CasAuthenticationProvider cap = new CasAuthenticationProvider(); cap.setAuthenticationUserDetailsService(new MockAuthoritiesPopulator()); cap.setKey("qwerty"); cap.setStatelessTicketCache(new MockStatelessTicketCache()); cap.setTicketValidator(new MockTicketValidator(true)); cap.setServiceProperties(makeServiceProperties()); cap.afterPropertiesSet(); UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("some_normal_user", "password", AuthorityUtils.createAuthorityList("ROLE_A")); assertThat(cap.authenticate(token)).isNull(); } @Test public void supportsRequiredTokens() { CasAuthenticationProvider cap = new CasAuthenticationProvider(); assertThat(cap.supports(CasServiceTicketAuthenticationToken.class)).isTrue(); assertThat(cap.supports(CasAuthenticationToken.class)).isTrue(); } private class MockAuthoritiesPopulator implements AuthenticationUserDetailsService { @Override public UserDetails loadUserDetails(final Authentication token) throws UsernameNotFoundException { return makeUserDetailsFromAuthoritiesPopulator(); } } private class MockStatelessTicketCache implements StatelessTicketCache { private Map<String, CasAuthenticationToken> cache = new HashMap<>(); @Override public CasAuthenticationToken getByTicketId(String serviceTicket) { return this.cache.get(serviceTicket); } @Override public void putTicketInCache(CasAuthenticationToken token) { this.cache.put(token.getCredentials().toString(), token); } @Override public void removeTicketFromCache(CasAuthenticationToken token) { throw new UnsupportedOperationException("mock method not implemented"); } @Override public void removeTicketFromCache(String serviceTicket) { throw new UnsupportedOperationException("mock method not implemented"); } } private class MockTicketValidator implements TicketValidator { private boolean returnTicket; MockTicketValidator(boolean returnTicket) { this.returnTicket = returnTicket; } @Override public Assertion validate(final String ticket, final String service) { if (this.returnTicket) { return new AssertionImpl("rod"); } throw new BadCredentialsException("As requested from mock"); } } }
16,666
43.209549
109
java
null
spring-security-main/cas/src/test/java/org/springframework/security/cas/authentication/AbstractStatelessTicketCacheTests.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.authentication; import java.util.ArrayList; import java.util.List; import org.apereo.cas.client.validation.Assertion; import org.apereo.cas.client.validation.AssertionImpl; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.User; /** * @author Scott Battaglia * @since 2.0 * */ public abstract class AbstractStatelessTicketCacheTests { protected CasAuthenticationToken getToken() { List<String> proxyList = new ArrayList<>(); proxyList.add("https://localhost/newPortal/login/cas"); User user = new User("rod", "password", true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO")); final Assertion assertion = new AssertionImpl("rod"); return new CasAuthenticationToken("key", user, "ST-0-ER94xMJmn6pha35CQRoZ", AuthorityUtils.createAuthorityList("ROLE_ONE", "ROLE_TWO"), user, assertion); } }
1,582
33.413043
81
java
null
spring-security-main/cas/src/main/java/org/springframework/security/cas/package-info.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Spring Security support for Apereo's Central Authentication Service * (<a href="https://github.com/apereo/cas">CAS</a>). */ package org.springframework.security.cas;
798
35.318182
75
java
null
spring-security-main/cas/src/main/java/org/springframework/security/cas/SamlServiceProperties.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas; /** * Sets the appropriate parameters for CAS's implementation of SAML (which is not * guaranteed to be actually SAML compliant). * * @author Scott Battaglia * @since 3.0 */ public final class SamlServiceProperties extends ServiceProperties { public static final String DEFAULT_SAML_ARTIFACT_PARAMETER = "SAMLart"; public static final String DEFAULT_SAML_SERVICE_PARAMETER = "TARGET"; public SamlServiceProperties() { super.setArtifactParameter(DEFAULT_SAML_ARTIFACT_PARAMETER); super.setServiceParameter(DEFAULT_SAML_SERVICE_PARAMETER); } }
1,230
31.394737
81
java
null
spring-security-main/cas/src/main/java/org/springframework/security/cas/ServiceProperties.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; /** * Stores properties related to this CAS service. * <p> * Each web application capable of processing CAS tickets is known as a service. This * class stores the properties that are relevant to the local CAS service, being the * application that is being secured by Spring Security. * * @author Ben Alex */ public class ServiceProperties implements InitializingBean { public static final String DEFAULT_CAS_ARTIFACT_PARAMETER = "ticket"; public static final String DEFAULT_CAS_SERVICE_PARAMETER = "service"; private String service; private boolean authenticateAllArtifacts; private boolean sendRenew = false; private String artifactParameter = DEFAULT_CAS_ARTIFACT_PARAMETER; private String serviceParameter = DEFAULT_CAS_SERVICE_PARAMETER; @Override public void afterPropertiesSet() { Assert.hasLength(this.service, "service cannot be empty."); Assert.hasLength(this.artifactParameter, "artifactParameter cannot be empty."); Assert.hasLength(this.serviceParameter, "serviceParameter cannot be empty."); } /** * Represents the service the user is authenticating to. * <p> * This service is the callback URL belonging to the local Spring Security System for * Spring secured application. For example, * * <pre> * https://www.mycompany.com/application/login/cas * </pre> * @return the URL of the service the user is authenticating to */ public final String getService() { return this.service; } /** * Indicates whether the <code>renew</code> parameter should be sent to the CAS login * URL and CAS validation URL. * <p> * If <code>true</code>, it will force CAS to authenticate the user again (even if the * user has previously authenticated). During ticket validation it will require the * ticket was generated as a consequence of an explicit login. High security * applications would probably set this to <code>true</code>. Defaults to * <code>false</code>, providing automated single sign on. * @return whether to send the <code>renew</code> parameter to CAS */ public final boolean isSendRenew() { return this.sendRenew; } public final void setSendRenew(final boolean sendRenew) { this.sendRenew = sendRenew; } public final void setService(final String service) { this.service = service; } public final String getArtifactParameter() { return this.artifactParameter; } /** * Configures the Request Parameter to look for when attempting to see if a CAS ticket * was sent from the server. * @param artifactParameter the id to use. Default is "ticket". */ public final void setArtifactParameter(final String artifactParameter) { this.artifactParameter = artifactParameter; } /** * Configures the Request parameter to look for when attempting to send a request to * CAS. * @return the service parameter to use. Default is "service". */ public final String getServiceParameter() { return this.serviceParameter; } public final void setServiceParameter(final String serviceParameter) { this.serviceParameter = serviceParameter; } public final boolean isAuthenticateAllArtifacts() { return this.authenticateAllArtifacts; } /** * If true, then any non-null artifact (ticket) should be authenticated. Additionally, * the service will be determined dynamically in order to ensure the service matches * the expected value for this artifact. * @param authenticateAllArtifacts */ public final void setAuthenticateAllArtifacts(final boolean authenticateAllArtifacts) { this.authenticateAllArtifacts = authenticateAllArtifacts; } }
4,342
31.654135
88
java
null
spring-security-main/cas/src/main/java/org/springframework/security/cas/web/package-info.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Authenticates standard web browser users via CAS. */ package org.springframework.security.cas.web;
730
33.809524
75
java
null
spring-security-main/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationFilter.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.web; import java.io.IOException; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apereo.cas.client.proxy.ProxyGrantingTicketStorage; import org.apereo.cas.client.util.CommonUtils; import org.apereo.cas.client.validation.TicketValidator; import org.springframework.core.log.LogMessage; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.authentication.AuthenticationDetailsSource; import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent; import org.springframework.security.cas.ServiceProperties; import org.springframework.security.cas.authentication.CasServiceTicketAuthenticationToken; import org.springframework.security.cas.web.authentication.ServiceAuthenticationDetails; import org.springframework.security.cas.web.authentication.ServiceAuthenticationDetailsSource; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; import org.springframework.security.web.context.HttpSessionSecurityContextRepository; import org.springframework.security.web.context.SecurityContextRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; /** * Processes a CAS service ticket, obtains proxy granting tickets, and processes proxy * tickets. * <h2>Service Tickets</h2> * <p> * A service ticket consists of an opaque ticket string. It arrives at this filter by the * user's browser successfully authenticating using CAS, and then receiving a HTTP * redirect to a <code>service</code>. The opaque ticket string is presented in the * <code>ticket</code> request parameter. * <p> * This filter monitors the <code>service</code> URL so it can receive the service ticket * and process it. By default this filter processes the URL <tt>/login/cas</tt>. When * processing this URL, the value of {@link ServiceProperties#getService()} is used as the * <tt>service</tt> when validating the <code>ticket</code>. This means that it is * important that {@link ServiceProperties#getService()} specifies the same value as the * <tt>filterProcessesUrl</tt>. * <p> * Processing the service ticket involves creating a * <code>CasServiceTicketAuthenticationToken</code> which uses * {@link CasServiceTicketAuthenticationToken#CAS_STATEFUL_IDENTIFIER} for the * <code>principal</code> and the opaque ticket string as the <code>credentials</code>. * <h2>Obtaining Proxy Granting Tickets</h2> * <p> * If specified, the filter can also monitor the <code>proxyReceptorUrl</code>. The filter * will respond to requests matching this url so that the CAS Server can provide a PGT to * the filter. Note that in addition to the <code>proxyReceptorUrl</code> a non-null * <code>proxyGrantingTicketStorage</code> must be provided in order for the filter to * respond to proxy receptor requests. By configuring a shared * {@link ProxyGrantingTicketStorage} between the {@link TicketValidator} and the * CasAuthenticationFilter one can have the CasAuthenticationFilter handle the proxying * requirements for CAS. * <h2>Proxy Tickets</h2> * <p> * The filter can process tickets present on any url. This is useful when wanting to * process proxy tickets. In order for proxy tickets to get processed * {@link ServiceProperties#isAuthenticateAllArtifacts()} must return <code>true</code>. * Additionally, if the request is already authenticated, authentication will <b>not</b> * occur. Last, {@link AuthenticationDetailsSource#buildDetails(Object)} must return a * {@link ServiceAuthenticationDetails}. This can be accomplished using the * {@link ServiceAuthenticationDetailsSource}. In this case * {@link ServiceAuthenticationDetails#getServiceUrl()} will be used for the service url. * <p> * Processing the proxy ticket involves creating a * <code>CasServiceTicketAuthenticationToken</code> which uses * {@link CasServiceTicketAuthenticationToken#CAS_STATELESS_IDENTIFIER} for the * <code>principal</code> and the opaque ticket string as the <code>credentials</code>. * When a proxy ticket is successfully authenticated, the FilterChain continues and the * <code>authenticationSuccessHandler</code> is not used. * <h2>Notes about the <code>AuthenticationManager</code></h2> * <p> * The configured <code>AuthenticationManager</code> is expected to provide a provider * that can recognise <code>CasServiceTicketAuthenticationToken</code>s containing this * special <code>principal</code> name, and process them accordingly by validation with * the CAS server. Additionally, it should be capable of using the result of * {@link ServiceAuthenticationDetails#getServiceUrl()} as the service when validating the * ticket. * <h2>Example Configuration</h2> * <p> * An example configuration that supports service tickets, obtaining proxy granting * tickets, and proxy tickets is illustrated below: * * <pre> * &lt;b:bean id=&quot;serviceProperties&quot; * class=&quot;org.springframework.security.cas.ServiceProperties&quot; * p:service=&quot;https://service.example.com/cas-sample/login/cas&quot; * p:authenticateAllArtifacts=&quot;true&quot;/&gt; * &lt;b:bean id=&quot;casEntryPoint&quot; * class=&quot;org.springframework.security.cas.web.CasAuthenticationEntryPoint&quot; * p:serviceProperties-ref=&quot;serviceProperties&quot; p:loginUrl=&quot;https://login.example.org/cas/login&quot; /&gt; * &lt;b:bean id=&quot;casFilter&quot; * class=&quot;org.springframework.security.cas.web.CasAuthenticationFilter&quot; * p:authenticationManager-ref=&quot;authManager&quot; * p:serviceProperties-ref=&quot;serviceProperties&quot; * p:proxyGrantingTicketStorage-ref=&quot;pgtStorage&quot; * p:proxyReceptorUrl=&quot;/login/cas/proxyreceptor&quot;&gt; * &lt;b:property name=&quot;authenticationDetailsSource&quot;&gt; * &lt;b:bean class=&quot;org.springframework.security.cas.web.authentication.ServiceAuthenticationDetailsSource&quot;/&gt; * &lt;/b:property&gt; * &lt;b:property name=&quot;authenticationFailureHandler&quot;&gt; * &lt;b:bean class=&quot;org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler&quot; * p:defaultFailureUrl=&quot;/casfailed.jsp&quot;/&gt; * &lt;/b:property&gt; * &lt;/b:bean&gt; * &lt;!-- * NOTE: In a real application you should not use an in memory implementation. You will also want * to ensure to clean up expired tickets by calling ProxyGrantingTicketStorage.cleanup() * --&gt; * &lt;b:bean id=&quot;pgtStorage&quot; class=&quot;org.apereo.cas.client.proxy.ProxyGrantingTicketStorageImpl&quot;/&gt; * &lt;b:bean id=&quot;casAuthProvider&quot; class=&quot;org.springframework.security.cas.authentication.CasAuthenticationProvider&quot; * p:serviceProperties-ref=&quot;serviceProperties&quot; * p:key=&quot;casAuthProviderKey&quot;&gt; * &lt;b:property name=&quot;authenticationUserDetailsService&quot;&gt; * &lt;b:bean * class=&quot;org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper&quot;&gt; * &lt;b:constructor-arg ref=&quot;userService&quot; /&gt; * &lt;/b:bean&gt; * &lt;/b:property&gt; * &lt;b:property name=&quot;ticketValidator&quot;&gt; * &lt;b:bean * class=&quot;org.apereo.cas.client.validation.Cas20ProxyTicketValidator&quot; * p:acceptAnyProxy=&quot;true&quot; * p:proxyCallbackUrl=&quot;https://service.example.com/cas-sample/login/cas/proxyreceptor&quot; * p:proxyGrantingTicketStorage-ref=&quot;pgtStorage&quot;&gt; * &lt;b:constructor-arg value=&quot;https://login.example.org/cas&quot; /&gt; * &lt;/b:bean&gt; * &lt;/b:property&gt; * &lt;b:property name=&quot;statelessTicketCache&quot;&gt; * &lt;b:bean class=&quot;org.springframework.security.cas.authentication.EhCacheBasedTicketCache&quot;&gt; * &lt;b:property name=&quot;cache&quot;&gt; * &lt;b:bean class=&quot;net.sf.ehcache.Cache&quot; * init-method=&quot;initialise&quot; * destroy-method=&quot;dispose&quot;&gt; * &lt;b:constructor-arg value=&quot;casTickets&quot;/&gt; * &lt;b:constructor-arg value=&quot;50&quot;/&gt; * &lt;b:constructor-arg value=&quot;true&quot;/&gt; * &lt;b:constructor-arg value=&quot;false&quot;/&gt; * &lt;b:constructor-arg value=&quot;3600&quot;/&gt; * &lt;b:constructor-arg value=&quot;900&quot;/&gt; * &lt;/b:bean&gt; * &lt;/b:property&gt; * &lt;/b:bean&gt; * &lt;/b:property&gt; * &lt;/b:bean&gt; * </pre> * * @author Ben Alex * @author Rob Winch */ public class CasAuthenticationFilter extends AbstractAuthenticationProcessingFilter { /** * The last portion of the receptor url, i.e. /proxy/receptor */ private RequestMatcher proxyReceptorMatcher; /** * The backing storage to store ProxyGrantingTicket requests. */ private ProxyGrantingTicketStorage proxyGrantingTicketStorage; private String artifactParameter = ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER; private boolean authenticateAllArtifacts; private AuthenticationFailureHandler proxyFailureHandler = new SimpleUrlAuthenticationFailureHandler(); private SecurityContextRepository securityContextRepository = new HttpSessionSecurityContextRepository(); private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); public CasAuthenticationFilter() { super("/login/cas"); setAuthenticationFailureHandler(new SimpleUrlAuthenticationFailureHandler()); setSecurityContextRepository(this.securityContextRepository); } @Override protected final void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { boolean continueFilterChain = proxyTicketRequest(serviceTicketRequest(request, response), request); if (!continueFilterChain) { super.successfulAuthentication(request, response, chain, authResult); return; } this.logger.debug( LogMessage.format("Authentication success. Updating SecurityContextHolder to contain: %s", authResult)); SecurityContext context = this.securityContextHolderStrategy.createEmptyContext(); context.setAuthentication(authResult); this.securityContextHolderStrategy.setContext(context); this.securityContextRepository.saveContext(context, request, response); if (this.eventPublisher != null) { this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass())); } chain.doFilter(request, response); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException { // if the request is a proxy request process it and return null to indicate the // request has been processed if (proxyReceptorRequest(request)) { this.logger.debug("Responding to proxy receptor request"); CommonUtils.readAndRespondToProxyReceptorRequest(request, response, this.proxyGrantingTicketStorage); return null; } String serviceTicket = obtainArtifact(request); if (serviceTicket == null) { this.logger.debug("Failed to obtain an artifact (cas ticket)"); serviceTicket = ""; } boolean serviceTicketRequest = serviceTicketRequest(request, response); CasServiceTicketAuthenticationToken authRequest = serviceTicketRequest ? CasServiceTicketAuthenticationToken.stateful(serviceTicket) : CasServiceTicketAuthenticationToken.stateless(serviceTicket); authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request)); return this.getAuthenticationManager().authenticate(authRequest); } /** * If present, gets the artifact (CAS ticket) from the {@link HttpServletRequest}. * @param request * @return if present the artifact from the {@link HttpServletRequest}, else null */ protected String obtainArtifact(HttpServletRequest request) { return request.getParameter(this.artifactParameter); } /** * Overridden to provide proxying capabilities. */ @Override protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) { final boolean serviceTicketRequest = serviceTicketRequest(request, response); final boolean result = serviceTicketRequest || proxyReceptorRequest(request) || (proxyTicketRequest(serviceTicketRequest, request)); if (this.logger.isDebugEnabled()) { this.logger.debug("requiresAuthentication = " + result); } return result; } /** * Sets the {@link AuthenticationFailureHandler} for proxy requests. * @param proxyFailureHandler */ public final void setProxyAuthenticationFailureHandler(AuthenticationFailureHandler proxyFailureHandler) { Assert.notNull(proxyFailureHandler, "proxyFailureHandler cannot be null"); this.proxyFailureHandler = proxyFailureHandler; } /** * Wraps the {@link AuthenticationFailureHandler} to distinguish between handling * proxy ticket authentication failures and service ticket failures. */ @Override public final void setAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) { super.setAuthenticationFailureHandler(new CasAuthenticationFailureHandler(failureHandler)); } public final void setProxyReceptorUrl(final String proxyReceptorUrl) { this.proxyReceptorMatcher = new AntPathRequestMatcher("/**" + proxyReceptorUrl); } public final void setProxyGrantingTicketStorage(final ProxyGrantingTicketStorage proxyGrantingTicketStorage) { this.proxyGrantingTicketStorage = proxyGrantingTicketStorage; } public final void setServiceProperties(final ServiceProperties serviceProperties) { this.artifactParameter = serviceProperties.getArtifactParameter(); this.authenticateAllArtifacts = serviceProperties.isAuthenticateAllArtifacts(); } /** * Indicates if the request is elgible to process a service ticket. This method exists * for readability. * @param request * @param response * @return */ private boolean serviceTicketRequest(HttpServletRequest request, HttpServletResponse response) { boolean result = super.requiresAuthentication(request, response); this.logger.debug(LogMessage.format("serviceTicketRequest = %s", result)); return result; } /** * Indicates if the request is elgible to process a proxy ticket. * @param request * @return */ private boolean proxyTicketRequest(boolean serviceTicketRequest, HttpServletRequest request) { if (serviceTicketRequest) { return false; } boolean result = this.authenticateAllArtifacts && obtainArtifact(request) != null && !authenticated(); this.logger.debug(LogMessage.format("proxyTicketRequest = %s", result)); return result; } /** * Determines if a user is already authenticated. * @return */ private boolean authenticated() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return authentication != null && authentication.isAuthenticated() && !(authentication instanceof AnonymousAuthenticationToken); } /** * Indicates if the request is elgible to be processed as the proxy receptor. * @param request * @return */ private boolean proxyReceptorRequest(HttpServletRequest request) { final boolean result = proxyReceptorConfigured() && this.proxyReceptorMatcher.matches(request); this.logger.debug(LogMessage.format("proxyReceptorRequest = %s", result)); return result; } /** * Determines if the {@link CasAuthenticationFilter} is configured to handle the proxy * receptor requests. * @return */ private boolean proxyReceptorConfigured() { final boolean result = this.proxyGrantingTicketStorage != null && this.proxyReceptorMatcher != null; this.logger.debug(LogMessage.format("proxyReceptorConfigured = %s", result)); return result; } /** * A wrapper for the AuthenticationFailureHandler that will flex the * {@link AuthenticationFailureHandler} that is used. The value * {@link CasAuthenticationFilter#setProxyAuthenticationFailureHandler(AuthenticationFailureHandler)} * will be used for proxy requests that fail. The value * {@link CasAuthenticationFilter#setAuthenticationFailureHandler(AuthenticationFailureHandler)} * will be used for service tickets that fail. */ private class CasAuthenticationFailureHandler implements AuthenticationFailureHandler { private final AuthenticationFailureHandler serviceTicketFailureHandler; CasAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) { Assert.notNull(failureHandler, "failureHandler"); this.serviceTicketFailureHandler = failureHandler; } @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { if (serviceTicketRequest(request, response)) { this.serviceTicketFailureHandler.onAuthenticationFailure(request, response, exception); } else { CasAuthenticationFilter.this.proxyFailureHandler.onAuthenticationFailure(request, response, exception); } } } }
18,842
46.583333
136
java
null
spring-security-main/cas/src/main/java/org/springframework/security/cas/web/CasAuthenticationEntryPoint.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.web; import java.io.IOException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apereo.cas.client.util.CommonUtils; import org.springframework.beans.factory.InitializingBean; import org.springframework.security.cas.ServiceProperties; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.util.Assert; /** * Used by the <code>ExceptionTranslationFilter</code> to commence authentication via the * JA-SIG Central Authentication Service (CAS). * <p> * The user's browser will be redirected to the JA-SIG CAS enterprise-wide login page. * This page is specified by the <code>loginUrl</code> property. Once login is complete, * the CAS login page will redirect to the page indicated by the <code>service</code> * property. The <code>service</code> is a HTTP URL belonging to the current application. * The <code>service</code> URL is monitored by the {@link CasAuthenticationFilter}, which * will validate the CAS login was successful. * * @author Ben Alex * @author Scott Battaglia */ public class CasAuthenticationEntryPoint implements AuthenticationEntryPoint, InitializingBean { private ServiceProperties serviceProperties; private String loginUrl; /** * Determines whether the Service URL should include the session id for the specific * user. As of CAS 3.0.5, the session id will automatically be stripped. However, * older versions of CAS (i.e. CAS 2), do not automatically strip the session * identifier (this is a bug on the part of the older server implementations), so an * option to disable the session encoding is provided for backwards compatibility. * * By default, encoding is enabled. */ private boolean encodeServiceUrlWithSessionId = true; @Override public void afterPropertiesSet() { Assert.hasLength(this.loginUrl, "loginUrl must be specified"); Assert.notNull(this.serviceProperties, "serviceProperties must be specified"); Assert.notNull(this.serviceProperties.getService(), "serviceProperties.getService() cannot be null."); } @Override public final void commence(final HttpServletRequest servletRequest, HttpServletResponse response, AuthenticationException authenticationException) throws IOException { String urlEncodedService = createServiceUrl(servletRequest, response); String redirectUrl = createRedirectUrl(urlEncodedService); preCommence(servletRequest, response); new DefaultRedirectStrategy().sendRedirect(servletRequest, response, redirectUrl); // response.sendRedirect(redirectUrl); } /** * Constructs a new Service Url. The default implementation relies on the CAS client * to do the bulk of the work. * @param request the HttpServletRequest * @param response the HttpServlet Response * @return the constructed service url. CANNOT be NULL. */ protected String createServiceUrl(HttpServletRequest request, HttpServletResponse response) { return CommonUtils.constructServiceUrl(null, response, this.serviceProperties.getService(), null, this.serviceProperties.getArtifactParameter(), this.encodeServiceUrlWithSessionId); } /** * Constructs the Url for Redirection to the CAS server. Default implementation relies * on the CAS client to do the bulk of the work. * @param serviceUrl the service url that should be included. * @return the redirect url. CANNOT be NULL. */ protected String createRedirectUrl(String serviceUrl) { return CommonUtils.constructRedirectUrl(this.loginUrl, this.serviceProperties.getServiceParameter(), serviceUrl, this.serviceProperties.isSendRenew(), false); } /** * Template method for you to do your own pre-processing before the redirect occurs. * @param request the HttpServletRequest * @param response the HttpServletResponse */ protected void preCommence(HttpServletRequest request, HttpServletResponse response) { } /** * The enterprise-wide CAS login URL. Usually something like * <code>https://www.mycompany.com/cas/login</code>. * @return the enterprise-wide CAS login URL */ public final String getLoginUrl() { return this.loginUrl; } public final ServiceProperties getServiceProperties() { return this.serviceProperties; } public final void setLoginUrl(String loginUrl) { this.loginUrl = loginUrl; } public final void setServiceProperties(ServiceProperties serviceProperties) { this.serviceProperties = serviceProperties; } /** * Sets whether to encode the service url with the session id or not. * @param encodeServiceUrlWithSessionId whether to encode the service url with the * session id or not. */ public final void setEncodeServiceUrlWithSessionId(boolean encodeServiceUrlWithSessionId) { this.encodeServiceUrlWithSessionId = encodeServiceUrlWithSessionId; } /** * Sets whether to encode the service url with the session id or not. * @return whether to encode the service url with the session id or not. * */ protected boolean getEncodeServiceUrlWithSessionId() { return this.encodeServiceUrlWithSessionId; } }
5,860
37.559211
114
java
null
spring-security-main/cas/src/main/java/org/springframework/security/cas/web/authentication/package-info.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Authentication processing mechanisms which respond to the submission of authentication * credentials using CAS. */ package org.springframework.security.cas.web.authentication;
808
35.772727
89
java
null
spring-security-main/cas/src/main/java/org/springframework/security/cas/web/authentication/ServiceAuthenticationDetailsSource.java
/* * Copyright 2011-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.web.authentication; import java.net.MalformedURLException; import java.util.regex.Pattern; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.authentication.AuthenticationDetailsSource; import org.springframework.security.cas.ServiceProperties; import org.springframework.util.Assert; /** * The {@code AuthenticationDetailsSource} that is set on the * {@code CasAuthenticationFilter} should return a value that implements * {@code ServiceAuthenticationDetails} if the application needs to authenticate dynamic * service urls. The * {@code ServiceAuthenticationDetailsSource#buildDetails(HttpServletRequest)} creates a * default {@code ServiceAuthenticationDetails}. * * @author Rob Winch */ public class ServiceAuthenticationDetailsSource implements AuthenticationDetailsSource<HttpServletRequest, ServiceAuthenticationDetails> { private final Pattern artifactPattern; private ServiceProperties serviceProperties; /** * Creates an implementation that uses the specified ServiceProperties and the default * CAS artifactParameterName. * @param serviceProperties The ServiceProperties to use to construct the serviceUrl. */ public ServiceAuthenticationDetailsSource(ServiceProperties serviceProperties) { this(serviceProperties, ServiceProperties.DEFAULT_CAS_ARTIFACT_PARAMETER); } /** * Creates an implementation that uses the specified artifactParameterName * @param serviceProperties The ServiceProperties to use to construct the serviceUrl. * @param artifactParameterName the artifactParameterName that is removed from the * current URL. The result becomes the service url. Cannot be null and cannot be an * empty String. */ public ServiceAuthenticationDetailsSource(ServiceProperties serviceProperties, String artifactParameterName) { Assert.notNull(serviceProperties, "serviceProperties cannot be null"); this.serviceProperties = serviceProperties; this.artifactPattern = DefaultServiceAuthenticationDetails.createArtifactPattern(artifactParameterName); } /** * @param context the {@code HttpServletRequest} object. * @return the {@code ServiceAuthenticationDetails} containing information about the * current request */ @Override public ServiceAuthenticationDetails buildDetails(HttpServletRequest context) { try { return new DefaultServiceAuthenticationDetails(this.serviceProperties.getService(), context, this.artifactPattern); } catch (MalformedURLException ex) { throw new RuntimeException(ex); } } }
3,195
37.047619
111
java
null
spring-security-main/cas/src/main/java/org/springframework/security/cas/web/authentication/ServiceAuthenticationDetails.java
/* * Copyright 2011-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.web.authentication; import java.io.Serializable; import org.springframework.security.cas.ServiceProperties; import org.springframework.security.cas.authentication.CasAuthenticationProvider; import org.springframework.security.core.Authentication; /** * In order for the {@link CasAuthenticationProvider} to provide the correct service url * to authenticate the ticket, the returned value of {@link Authentication#getDetails()} * should implement this interface when tickets can be sent to any URL rather than only * {@link ServiceProperties#getService()}. * * @author Rob Winch * @see ServiceAuthenticationDetailsSource */ public interface ServiceAuthenticationDetails extends Serializable { /** * Gets the absolute service url (i.e. https://example.com/service/). * @return the service url. Cannot be <code>null</code>. */ String getServiceUrl(); }
1,535
34.72093
88
java
null
spring-security-main/cas/src/main/java/org/springframework/security/cas/web/authentication/DefaultServiceAuthenticationDetails.java
/* * Copyright 2011-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.web.authentication; import java.net.MalformedURLException; import java.net.URL; import java.util.regex.Pattern; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.security.web.util.UrlUtils; import org.springframework.util.Assert; /** * A default implementation of {@link ServiceAuthenticationDetails} that figures out the * value for {@link #getServiceUrl()} by inspecting the current {@link HttpServletRequest} * and using the current URL minus the artifact and the corresponding value. * * @author Rob Winch */ final class DefaultServiceAuthenticationDetails extends WebAuthenticationDetails implements ServiceAuthenticationDetails { private static final long serialVersionUID = 6192409090610517700L; private final String serviceUrl; /** * Creates a new instance * @param request the current {@link HttpServletRequest} to obtain the * {@link #getServiceUrl()} from. * @param artifactPattern the {@link Pattern} that will be used to clean up the query * string from containing the artifact name and value. This can be created using * {@link #createArtifactPattern(String)}. */ DefaultServiceAuthenticationDetails(String casService, HttpServletRequest request, Pattern artifactPattern) throws MalformedURLException { super(request); URL casServiceUrl = new URL(casService); int port = getServicePort(casServiceUrl); final String query = getQueryString(request, artifactPattern); this.serviceUrl = UrlUtils.buildFullRequestUrl(casServiceUrl.getProtocol(), casServiceUrl.getHost(), port, request.getRequestURI(), query); } /** * Returns the current URL minus the artifact parameter and its value, if present. * @see org.springframework.security.cas.web.authentication.ServiceAuthenticationDetails#getServiceUrl() */ @Override public String getServiceUrl() { return this.serviceUrl; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj) || !(obj instanceof DefaultServiceAuthenticationDetails)) { return false; } ServiceAuthenticationDetails that = (ServiceAuthenticationDetails) obj; return this.serviceUrl.equals(that.getServiceUrl()); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + this.serviceUrl.hashCode(); return result; } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append(super.toString()); result.append("ServiceUrl: "); result.append(this.serviceUrl); return result.toString(); } /** * If present, removes the artifactParameterName and the corresponding value from the * query String. * @param request * @return the query String minus the artifactParameterName and the corresponding * value. */ private String getQueryString(final HttpServletRequest request, final Pattern artifactPattern) { final String query = request.getQueryString(); if (query == null) { return null; } String result = artifactPattern.matcher(query).replaceFirst(""); if (result.length() == 0) { return null; } // strip off the trailing & only if the artifact was the first query param return result.startsWith("&") ? result.substring(1) : result; } /** * Creates a {@link Pattern} that can be passed into the constructor. This allows the * {@link Pattern} to be reused for every instance of * {@link DefaultServiceAuthenticationDetails}. * @param artifactParameterName * @return */ static Pattern createArtifactPattern(String artifactParameterName) { Assert.hasLength(artifactParameterName, "artifactParameterName is expected to have a length"); return Pattern.compile("&?" + Pattern.quote(artifactParameterName) + "=[^&]*"); } /** * Gets the port from the casServiceURL ensuring to return the proper value if the * default port is being used. * @param casServiceUrl the casServerUrl to be used (i.e. * "https://example.com/context/login/cas") * @return the port that is configured for the casServerUrl */ private static int getServicePort(URL casServiceUrl) { int port = casServiceUrl.getPort(); if (port == -1) { port = casServiceUrl.getDefaultPort(); } return port; } }
4,985
32.918367
108
java
null
spring-security-main/cas/src/main/java/org/springframework/security/cas/userdetails/AbstractCasAssertionUserDetailsService.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.userdetails; import org.apereo.cas.client.validation.Assertion; import org.springframework.security.cas.authentication.CasAssertionAuthenticationToken; import org.springframework.security.core.userdetails.AuthenticationUserDetailsService; import org.springframework.security.core.userdetails.UserDetails; /** * Abstract class for using the provided CAS assertion to construct a new User object. * This generally is most useful when combined with a SAML-based response from the CAS * Server/client. * * @author Scott Battaglia * @since 3.0 */ public abstract class AbstractCasAssertionUserDetailsService implements AuthenticationUserDetailsService<CasAssertionAuthenticationToken> { @Override public final UserDetails loadUserDetails(final CasAssertionAuthenticationToken token) { return loadUserDetails(token.getAssertion()); } /** * Protected template method for construct a * {@link org.springframework.security.core.userdetails.UserDetails} via the supplied * CAS assertion. * @param assertion the assertion to use to construct the new UserDetails. CANNOT be * NULL. * @return the newly constructed UserDetails. */ protected abstract UserDetails loadUserDetails(Assertion assertion); }
1,893
35.423077
88
java
null
spring-security-main/cas/src/main/java/org/springframework/security/cas/userdetails/GrantedAuthorityFromAssertionAttributesUserDetailsService.java
/* * Copyright 2004, 2005, 2006 Acegi Technology Pty Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.userdetails; import java.util.ArrayList; import java.util.List; import org.apereo.cas.client.validation.Assertion; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.util.Assert; /** * Populates the {@link org.springframework.security.core.GrantedAuthority}s for a user by * reading a list of attributes that were returned as part of the CAS response. Each * attribute is read and each value of the attribute is turned into a GrantedAuthority. If * the attribute has no value then its not added. * * @author Scott Battaglia * @since 3.0 */ public final class GrantedAuthorityFromAssertionAttributesUserDetailsService extends AbstractCasAssertionUserDetailsService { private static final String NON_EXISTENT_PASSWORD_VALUE = "NO_PASSWORD"; private final String[] attributes; private boolean convertToUpperCase = true; public GrantedAuthorityFromAssertionAttributesUserDetailsService(final String[] attributes) { Assert.notNull(attributes, "attributes cannot be null."); Assert.isTrue(attributes.length > 0, "At least one attribute is required to retrieve roles from."); this.attributes = attributes; } @SuppressWarnings("unchecked") @Override protected UserDetails loadUserDetails(final Assertion assertion) { List<GrantedAuthority> grantedAuthorities = new ArrayList<>(); for (String attribute : this.attributes) { Object value = assertion.getPrincipal().getAttributes().get(attribute); if (value != null) { if (value instanceof List) { for (Object o : (List<?>) value) { grantedAuthorities.add(createSimpleGrantedAuthority(o)); } } else { grantedAuthorities.add(createSimpleGrantedAuthority(value)); } } } return new User(assertion.getPrincipal().getName(), NON_EXISTENT_PASSWORD_VALUE, true, true, true, true, grantedAuthorities); } private SimpleGrantedAuthority createSimpleGrantedAuthority(Object o) { return new SimpleGrantedAuthority(this.convertToUpperCase ? o.toString().toUpperCase() : o.toString()); } /** * Converts the returned attribute values to uppercase values. * @param convertToUpperCase true if it should convert, false otherwise. */ public void setConvertToUpperCase(final boolean convertToUpperCase) { this.convertToUpperCase = convertToUpperCase; } }
3,187
35.227273
106
java
null
spring-security-main/cas/src/main/java/org/springframework/security/cas/jackson2/AttributePrincipalImplMixin.java
/* * Copyright 2015-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.cas.jackson2; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.apereo.cas.client.proxy.ProxyRetriever; /** * Helps in deserialize * {@link org.apereo.cas.client.authentication.AttributePrincipalImpl} which is used with * {@link org.springframework.security.cas.authentication.CasAuthenticationToken}. Type * information will be stored in property named @class. * <p> * <pre> * ObjectMapper mapper = new ObjectMapper(); * mapper.registerModule(new CasJackson2Module()); * </pre> * * @author Jitendra Singh * @since 4.2 * @see CasJackson2Module * @see org.springframework.security.jackson2.SecurityJackson2Modules */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE) @JsonIgnoreProperties(ignoreUnknown = true) class AttributePrincipalImplMixin { /** * Mixin Constructor helps in deserialize * {@link org.apereo.cas.client.authentication.AttributePrincipalImpl} * @param name the unique identifier for the principal. * @param attributes the key/value pairs for this principal. * @param proxyGrantingTicket the ticket associated with this principal. * @param proxyRetriever the ProxyRetriever implementation to call back to the CAS * server. */ @JsonCreator AttributePrincipalImplMixin(@JsonProperty("name") String name, @JsonProperty("attributes") Map<String, Object> attributes, @JsonProperty("proxyGrantingTicket") String proxyGrantingTicket, @JsonProperty("proxyRetriever") ProxyRetriever proxyRetriever) { } }
2,592
37.701493
115
java